aboutsummaryrefslogtreecommitdiff
path: root/builtin/common/misc_helpers.lua
blob: 39fca7d1e919a1593a9326411cfcdfd0979e749d (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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
-- Minetest: builtin/misc_helpers.lua

--------------------------------------------------------------------------------
function basic_dump(o)
	local tp = type(o)
	if tp == "number" then
		return tostring(o)
	elseif tp == "string" then
		return string.format("%q", o)
	elseif tp == "boolean" then
		return tostring(o)
	elseif tp == "nil" then
		return "nil"
	-- Uncomment for full function dumping support.
	-- Not currently enabled because bytecode isn't very human-readable and
	-- dump's output is intended for humans.
	--elseif tp == "function" then
	--	return string.format("loadstring(%q)", string.dump(o))
	else
		return string.format("<%s>", tp)
	end
end

local keywords = {
	["and"] = true,
	["break"] = true,
	["do"] = true,
	["else"] = true,
	["elseif"] = true,
	["end"] = true,
	["false"] = true,
	["for"] = true,
	["function"] = true,
	["goto"] = true,  -- Lua 5.2
	["if"] = true,
	["in"] = true,
	["local"] = true,
	["nil"] = true,
	["not"] = true,
	["or"] = true,
	["repeat"] = true,
	["return"] = true,
	["then"] = true,
	["true"] = true,
	["until"] = true,
	["while"] = true,
}
local function is_valid_identifier(str)
	if not str:find("^[a-zA-Z_][a-zA-Z0-9_]*$") or keywords[str] then
		return false
	end
	return true
end

--------------------------------------------------------------------------------
-- Dumps values in a line-per-value format.
-- For example, {test = {"Testing..."}} becomes:
--   _["test"] = {}
--   _["test"][1] = "Testing..."
-- This handles tables as keys and circular references properly.
-- It also handles multiple references well, writing the table only once.
-- The dumped argument is internal-only.

function dump2(o, name, dumped)
	name = name or "_"
	-- "dumped" is used to keep track of serialized tables to handle
	-- multiple references and circular tables properly.
	-- It only contains tables as keys.  The value is the name that
	-- the table has in the dump, eg:
	-- {x = {"y"}} -> dumped[{"y"}] = '_["x"]'
	dumped = dumped or {}
	if type(o) ~= "table" then
		return string.format("%s = %s\n", name, basic_dump(o))
	end
	if dumped[o] then
		return string.format("%s = %s\n", name, dumped[o])
	end
	dumped[o] = name
	-- This contains a list of strings to be concatenated later (because
	-- Lua is slow at individual concatenation).
	local t = {}
	for k, v in pairs(o) do
		local keyStr
		if type(k) == "table" then
			if dumped[k] then
				keyStr = dumped[k]
			else
				-- Key tables don't have a name, so use one of
				-- the form _G["table: 0xFFFFFFF"]
				keyStr = string.format("_G[%q]", tostring(k))
				-- Dump key table
				table.insert(t, dump2(k, keyStr, dumped))
			end
		else
			keyStr = basic_dump(k)
		end
		local vname = string.format("%s[%s]", name, keyStr)
		table.insert(t, dump2(v, vname, dumped))
	end
	return string.format("%s = {}\n%s", name, table.concat(t))
end

--------------------------------------------------------------------------------
-- This dumps values in a one-statement format.
-- For example, {test = {"Testing..."}} becomes:
-- [[{
-- 	test = {
-- 		"Testing..."
-- 	}
-- }]]
-- This supports tables as keys, but not circular references.
-- It performs poorly with multiple references as it writes out the full
-- table each time.
-- The indent field specifies a indentation string, it defaults to a tab.
-- Use the empty string to disable indentation.
-- The dumped and level arguments are internal-only.

function dump(o, indent, nested, level)
	if type(o) ~= "table" then
		return basic_dump(o)
	end
	-- Contains table -> true/nil of currently nested tables
	nested = nested or {}
	if nested[o] then
		return "<circular reference>"
	end
	nested[o] = true
	indent = indent or "\t"
	level = level or 1
	local t = {}
	local dumped_indexes = {}
	for i, v in ipairs(o) do
		table.insert(t, dump(v, indent, nested, level + 1))
		dumped_indexes[i] = true
	end
	for k, v in pairs(o) do
		if not dumped_indexes[k] then
			if type(k) ~= "string" or not is_valid_identifier(k) then
				k = "["..dump(k, indent, nested, level + 1).."]"
			end
			v = dump(v, indent, nested, level + 1)
			table.insert(t, k.." = "..v)
		end
	end
	nested[o] = nil
	if indent ~= "" then
		local indent_str = "\n"..string.rep(indent, level)
		local end_indent_str = "\n"..string.rep(indent, level - 1)
		return string.format("{%s%s%s}",
				indent_str,
				table.concat(t, ","..indent_str),
				end_indent_str)
	end
	return "{"..table.concat(t, ", ").."}"
end

--------------------------------------------------------------------------------
-- Localize functions to avoid table lookups (better performance).
local table_insert = table.insert
local str_sub, str_find = string.sub, string.find
function string.split(str, delim, include_empty, max_splits, sep_is_pattern)
	delim = delim or ","
	max_splits = max_splits or -1
	local items = {}
	local pos, len, seplen = 1, #str, #delim
	local plain = not sep_is_pattern
	max_splits = max_splits + 1
	repeat
		local np, npe = str_find(str, delim, pos, plain)
		np, npe = (np or (len+1)), (npe or (len+1))
		if (not np) or (max_splits == 1) then
			np = len + 1
			npe = np
		end
		local s = str_sub(str, pos, np - 1)
		if include_empty or (s ~= "") then
			max_splits = max_splits - 1
			table_insert(items, s)
		end
		pos = npe + 1
	until (max_splits == 0) or (pos > (len + 1))
	return items
end

--------------------------------------------------------------------------------
function file_exists(filename)
	local f = io.open(filename, "r")
	if f==nil then
		return false
	else
		f:close()
		return true
	end
end

--------------------------------------------------------------------------------
function string:trim()
	return (self:gsub("^%s*(.-)%s*$", "%1"))
end

assert(string.trim("\n \t\tfoo bar\t ") == "foo bar")

--------------------------------------------------------------------------------
function math.hypot(x, y)
	local t
	x = math.abs(x)
	y = math.abs(y)
	t = math.min(x, y)
	x = math.max(x, y)
	if x == 0 then return 0 end
	t = t / x
	return x * math.sqrt(1 + t * t)
end

--------------------------------------------------------------------------------
function math.sign(x, tolerance)
	tolerance = tolerance or 0
	if x > tolerance then
		return 1
	elseif x < -tolerance then
		return -1
	end
	return 0
end

--------------------------------------------------------------------------------
function get_last_folder(text,count)
	local parts = text:split(DIR_DELIM)

	if count == nil then
		return parts[#parts]
	end

	local retval = ""
	for i=1,count,1 do
		retval = retval .. parts[#parts - (count-i)] .. DIR_DELIM
	end

	return retval
end

--------------------------------------------------------------------------------
function cleanup_path(temppath)

	local parts = temppath:split("-")
	temppath = ""
	for i=1,#parts,1 do
		if temppath ~= "" then
			temppath = temppath .. "_"
		end
		temppath = temppath .. parts[i]
	end

	parts = temppath:split(".")
	temppath = ""
	for i=1,#parts,1 do
		if temppath ~= "" then
			temppath = temppath .. "_"
		end
		temppath = temppath .. parts[i]
	end

	parts = temppath:split("'")
	temppath = ""
	for i=1,#parts,1 do
		if temppath ~= "" then
			temppath = temppath .. ""
		end
		temppath = temppath .. parts[i]
	end

	parts = temppath:split(" ")
	temppath = ""
	for i=1,#parts,1 do
		if temppath ~= "" then
			temppath = temppath
		end
		temppath = temppath .. parts[i]
	end

	return temppath
end

function core.formspec_escape(text)
	if text ~= nil then
		text = string.gsub(text,"\\","\\\\")
		text = string.gsub(text,"%]","\\]")
		text = string.gsub(text,"%[","\\[")
		text = string.gsub(text,";","\\;")
		text = string.gsub(text,",","\\,")
	end
	return text
end


function core.splittext(text,charlimit)
	local retval = {}

	local current_idx = 1

	local start,stop = string.find(text," ",current_idx)
	local nl_start,nl_stop = string.find(text,"\n",current_idx)
	local gotnewline = false
	if nl_start ~= nil and (start == nil or nl_start < start) then
		start = nl_start
		stop = nl_stop
		gotnewline = true
	end
	local last_line = ""
	while start ~= nil do
		if string.len(last_line) + (stop-start) > charlimit then
			table.insert(retval,last_line)
			last_line = ""
		end

		if last_line ~= "" then
			last_line = last_line .. " "
		end

		last_line = last_line .. string.sub(text,current_idx,stop -1)

		if gotnewline then
			table.insert(retval,last_line)
			last_line = ""
			gotnewline = false
		end
		current_idx = stop+1

		start,stop = string.find(text," ",current_idx)
		nl_start,nl_stop = string.find(text,"\n",current_idx)

		if nl_start ~= nil and (start == nil or nl_start < start) then
			start = nl_start
			stop = nl_stop
			gotnewline = true
		end
	end

	--add last part of text
	if string.len(last_line) + (string.len(text) - current_idx) > charlimit then
			table.insert(retval,last_line)
			table.insert(retval,string.sub(text,current_idx))
	else
		last_line = last_line .. " " .. string.sub(text,current_idx)
		table.insert(retval,last_line)
	end

	return retval
end

--------------------------------------------------------------------------------

if INIT == "game" then
	local dirs1 = {9, 18, 7, 12}
	local dirs2 = {20, 23, 22, 21}

	function core.rotate_and_place(itemstack, placer, pointed_thing,
				infinitestacks, orient_flags)
		orient_flags = orient_flags or {}

		local unode = core.get_node_or_nil(pointed_thing.under)
		if not unode then
			return
		end
		local undef = core.registered_nodes[unode.name]
		if undef and undef.on_rightclick then
			undef.on_rightclick(pointed_thing.under, unode, placer,
					itemstack, pointed_thing)
			return
		end
		local pitch = placer:get_look_pitch()
		local fdir = core.dir_to_facedir(placer:get_look_dir())
		local wield_name = itemstack:get_name()

		local above = pointed_thing.above
		local under = pointed_thing.under
		local iswall = (above.y == under.y)
		local isceiling = not iswall and (above.y < under.y)
		local anode = core.get_node_or_nil(above)
		if not anode then
			return
		end
		local pos = pointed_thing.above
		local node = anode

		if undef and undef.buildable_to then
			pos = pointed_thing.under
			node = unode
			iswall = false
		end

		if core.is_protected(pos, placer:get_player_name()) then
			core.record_protection_violation(pos,
					placer:get_player_name())
			return
		end

		local ndef = core.registered_nodes[node.name]
		if not ndef or not ndef.buildable_to then
			return
		end

		if orient_flags.force_floor then
			iswall = false
			isceiling = false
		elseif orient_flags.force_ceiling then
			iswall = false
			isceiling = true
		elseif orient_flags.force_wall then
			iswall = true
			isceiling = false
		elseif orient_flags.invert_wall then
			iswall = not iswall
		end

		if iswall then
			core.set_node(pos, {name = wield_name,
					param2 = dirs1[fdir+1]})
		elseif isceiling then
			if orient_flags.force_facedir then
				core.set_node(pos, {name = wield_name,
						param2 = 20})
			else
				core.set_node(pos, {name = wield_name,
						param2 = dirs2[fdir+1]})
			end
		else -- place right side up
			if orient_flags.force_facedir then
				core.set_node(pos, {name = wield_name,
						param2 = 0})
			else
				core.set_node(pos, {name = wield_name,
						param2 = fdir})
			end
		end

		if not infinitestacks then
			itemstack:take_item()
			return itemstack
		end
	end


--------------------------------------------------------------------------------
--Wrapper for rotate_and_place() to check for sneak and assume Creative mode
--implies infinite stacks when performing a 6d rotation.
--------------------------------------------------------------------------------


	core.rotate_node = function(itemstack, placer, pointed_thing)
		core.rotate_and_place(itemstack, placer, pointed_thing,
				core.setting_getbool("creative_mode"),
				{invert_wall = placer:get_player_control().sneak})
		return itemstack
	end
end

--------------------------------------------------------------------------------
function core.explode_table_event(evt)
	if evt ~= nil then
		local parts = evt:split(":")
		if #parts == 3 then
			local t = parts[1]:trim()
			local r = tonumber(parts[2]:trim())
			local c = tonumber(parts[3]:trim())
			if type(r) == "number" and type(c) == "number"
					and t ~= "INV" then
				return {type=t, row=r, column=c}
			end
		end
	end
	return {type="INV", row=0, column=0}
end

--------------------------------------------------------------------------------
function core.explode_textlist_event(evt)
	if evt ~= nil then
		local parts = evt:split(":")
		if #parts == 2 then
			local t = parts[1]:trim()
			local r = tonumber(parts[2]:trim())
			if type(r) == "number" and t ~= "INV" then
				return {type=t, index=r}
			end
		end
	end
	return {type="INV", index=0}
end

--------------------------------------------------------------------------------
function core.explode_scrollbar_event(evt)
	local retval = core.explode_textlist_event(evt)

	retval.value = retval.index
	retval.index = nil

	return retval
end

--------------------------------------------------------------------------------
function core.pos_to_string(pos, decimal_places)
	local x = pos.x
	local y = pos.y
	local z = pos.z
	if decimal_places ~= nil then
		x = string.format("%." .. decimal_places .. "f", x)
		y = string.format("%." .. decimal_places .. "f", y)
		z = string.format("%." .. decimal_places .. "f", z)
	end
	return "(" .. x .. "," .. y .. "," .. z .. ")"
end

--------------------------------------------------------------------------------
function core.string_to_pos(value)
	if value == nil then
		return nil
	end

	local p = {}
	p.x, p.y, p.z = string.match(value, "^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
	if p.x and p.y and p.z then
		p.x = tonumber(p.x)
		p.y = tonumber(p.y)
		p.z = tonumber(p.z)
		return p
	end
	local p = {}
	p.x, p.y, p.z = string.match(value, "^%( *([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+) *%)$")
	if p.x and p.y and p.z then
		p.x = tonumber(p.x)
		p.y = tonumber(p.y)
		p.z = tonumber(p.z)
		return p
	end
	return nil
end

assert(core.string_to_pos("10.0, 5, -2").x == 10)
assert(core.string_to_pos("( 10.0, 5, -2)").z == -2)
assert(core.string_to_pos("asd, 5, -2)") == nil)

--------------------------------------------------------------------------------
function table.copy(t, seen)
	local n = {}
	seen = seen or {}
	seen[t] = n
	for k, v in pairs(t) do
		n[(type(k) == "table" and (seen[k] or table.copy(k, seen))) or k] =
			(type(v) == "table" and (seen[v] or table.copy(v, seen))) or v
	end
	return n
end
--------------------------------------------------------------------------------
-- mainmenu only functions
--------------------------------------------------------------------------------
if INIT == "mainmenu" then
	function core.get_game(index)
		local games = game.get_games()

		if index > 0 and index <= #games then
			return games[index]
		end

		return nil
	end

	function fgettext_ne(text, ...)
		text = core.gettext(text)
		local arg = {n=select('#', ...), ...}
		if arg.n >= 1 then
			-- Insert positional parameters ($1, $2, ...)
			local result = ''
			local pos = 1
			while pos <= text:len() do
				local newpos = text:find('[$]', pos)
				if newpos == nil then
					result = result .. text:sub(pos)
					pos = text:len() + 1
				else
					local paramindex =
						tonumber(text:sub(newpos+1, newpos+1))
					result = result .. text:sub(pos, newpos-1)
						.. tostring(arg[paramindex])
					pos = newpos + 2
				end
			end
			text = result
		end
		return text
	end

	function fgettext(text, ...)
		return core.formspec_escape(fgettext_ne(text, ...))
	end
end

n> bool need_to_grab = true; // Try to use local texture instead if asked to if (prefer_local){ std::string path = getTexturePath(name); if (path != ""){ video::IImage *img2 = driver->createImageFromFile(path.c_str()); if (img2){ toadd = img2; need_to_grab = false; } } } if (need_to_grab) toadd->grab(); m_images[name] = toadd; } video::IImage* get(const std::string &name) { std::map<std::string, video::IImage*>::iterator n; n = m_images.find(name); if (n != m_images.end()) return n->second; return NULL; } // Primarily fetches from cache, secondarily tries to read from filesystem video::IImage* getOrLoad(const std::string &name, IrrlichtDevice *device) { std::map<std::string, video::IImage*>::iterator n; n = m_images.find(name); if (n != m_images.end()){ n->second->grab(); // Grab for caller return n->second; } video::IVideoDriver* driver = device->getVideoDriver(); std::string path = getTexturePath(name); if (path == ""){ infostream<<"SourceImageCache::getOrLoad(): No path found for \"" <<name<<"\""<<std::endl; return NULL; } infostream<<"SourceImageCache::getOrLoad(): Loading path \""<<path <<"\""<<std::endl; video::IImage *img = driver->createImageFromFile(path.c_str()); if (img){ m_images[name] = img; img->grab(); // Grab for caller } return img; } private: std::map<std::string, video::IImage*> m_images; }; /* TextureSource */ class TextureSource : public IWritableTextureSource { public: TextureSource(IrrlichtDevice *device); virtual ~TextureSource(); /* Example case: Now, assume a texture with the id 1 exists, and has the name "stone.png^mineral1". Then a random thread calls getTextureId for a texture called "stone.png^mineral1^crack0". ...Now, WTF should happen? Well: - getTextureId strips off stuff recursively from the end until the remaining part is found, or nothing is left when something is stripped out But it is slow to search for textures by names and modify them like that? - ContentFeatures is made to contain ids for the basic plain textures - Crack textures can be slow by themselves, but the framework must be fast. Example case #2: - Assume a texture with the id 1 exists, and has the name "stone.png^mineral_coal.png". - Now getNodeTile() stumbles upon a node which uses texture id 1, and determines that MATERIAL_FLAG_CRACK must be applied to the tile - MapBlockMesh::animate() finds the MATERIAL_FLAG_CRACK and has received the current crack level 0 from the client. It finds out the name of the texture with getTextureName(1), appends "^crack0" to it and gets a new texture id with getTextureId("stone.png^mineral_coal.png^crack0"). */ /* Gets a texture id from cache or - if main thread, generates the texture, adds to cache and returns id. - if other thread, adds to request queue and waits for main thread. The id 0 points to a NULL texture. It is returned in case of error. */ u32 getTextureId(const std::string &name); // Finds out the name of a cached texture. std::string getTextureName(u32 id); /* If texture specified by the name pointed by the id doesn't exist, create it, then return the cached texture. Can be called from any thread. If called from some other thread and not found in cache, the call is queued to the main thread for processing. */ video::ITexture* getTexture(u32 id); video::ITexture* getTexture(const std::string &name, u32 *id = NULL); /* Get a texture specifically intended for mesh application, i.e. not HUD, compositing, or other 2D use. This texture may be a different size and may have had additional filters applied. */ video::ITexture* getTextureForMesh(const std::string &name, u32 *id); // Returns a pointer to the irrlicht device virtual IrrlichtDevice* getDevice() { return m_device; } bool isKnownSourceImage(const std::string &name) { bool is_known = false; bool cache_found = m_source_image_existence.get(name, &is_known); if (cache_found) return is_known; // Not found in cache; find out if a local file exists is_known = (getTexturePath(name) != ""); m_source_image_existence.set(name, is_known); return is_known; } // Processes queued texture requests from other threads. // Shall be called from the main thread. void processQueue(); // Insert an image into the cache without touching the filesystem. // Shall be called from the main thread. void insertSourceImage(const std::string &name, video::IImage *img); // Rebuild images and textures from the current set of source images // Shall be called from the main thread. void rebuildImagesAndTextures(); // Render a mesh to a texture. // Returns NULL if render-to-texture failed. // Shall be called from the main thread. video::ITexture* generateTextureFromMesh( const TextureFromMeshParams &params); // Generates an image from a full string like // "stone.png^mineral_coal.png^[crack:1:0". // Shall be called from the main thread. video::IImage* generateImage(const std::string &name); video::ITexture* getNormalTexture(const std::string &name); video::SColor getTextureAverageColor(const std::string &name); video::ITexture *getShaderFlagsTexture(bool normamap_present); private: // The id of the thread that is allowed to use irrlicht directly threadid_t m_main_thread; // The irrlicht device IrrlichtDevice *m_device; // Cache of source images // This should be only accessed from the main thread SourceImageCache m_sourcecache; // Generate a texture u32 generateTexture(const std::string &name); // Generate image based on a string like "stone.png" or "[crack:1:0". // if baseimg is NULL, it is created. Otherwise stuff is made on it. bool generateImagePart(std::string part_of_name, video::IImage *& baseimg); // Thread-safe cache of what source images are known (true = known) MutexedMap<std::string, bool> m_source_image_existence; // A texture id is index in this array. // The first position contains a NULL texture. std::vector<TextureInfo> m_textureinfo_cache; // Maps a texture name to an index in the former. std::map<std::string, u32> m_name_to_id; // The two former containers are behind this mutex Mutex m_textureinfo_cache_mutex; // Queued texture fetches (to be processed by the main thread) RequestQueue<std::string, u32, u8, u8> m_get_texture_queue; // Textures that have been overwritten with other ones // but can't be deleted because the ITexture* might still be used std::vector<video::ITexture*> m_texture_trash; // Cached settings needed for making textures from meshes bool m_setting_trilinear_filter; bool m_setting_bilinear_filter; bool m_setting_anisotropic_filter; }; IWritableTextureSource* createTextureSource(IrrlichtDevice *device) { return new TextureSource(device); } TextureSource::TextureSource(IrrlichtDevice *device): m_device(device) { assert(m_device); // Pre-condition m_main_thread = thr_get_current_thread_id(); // Add a NULL TextureInfo as the first index, named "" m_textureinfo_cache.push_back(TextureInfo("")); m_name_to_id[""] = 0; // Cache some settings // Note: Since this is only done once, the game must be restarted // for these settings to take effect m_setting_trilinear_filter = g_settings->getBool("trilinear_filter"); m_setting_bilinear_filter = g_settings->getBool("bilinear_filter"); m_setting_anisotropic_filter = g_settings->getBool("anisotropic_filter"); } TextureSource::~TextureSource() { video::IVideoDriver* driver = m_device->getVideoDriver(); unsigned int textures_before = driver->getTextureCount(); for (std::vector<TextureInfo>::iterator iter = m_textureinfo_cache.begin(); iter != m_textureinfo_cache.end(); ++iter) { //cleanup texture if (iter->texture) driver->removeTexture(iter->texture); } m_textureinfo_cache.clear(); for (std::vector<video::ITexture*>::iterator iter = m_texture_trash.begin(); iter != m_texture_trash.end(); ++iter) { video::ITexture *t = *iter; //cleanup trashed texture driver->removeTexture(t); } infostream << "~TextureSource() "<< textures_before << "/" << driver->getTextureCount() << std::endl; } u32 TextureSource::getTextureId(const std::string &name) { //infostream<<"getTextureId(): \""<<name<<"\""<<std::endl; { /* See if texture already exists */ MutexAutoLock lock(m_textureinfo_cache_mutex); std::map<std::string, u32>::iterator n; n = m_name_to_id.find(name); if (n != m_name_to_id.end()) { return n->second; } } /* Get texture */ if (thr_is_current_thread(m_main_thread)) { return generateTexture(name); } else { infostream<<"getTextureId(): Queued: name=\""<<name<<"\""<<std::endl; // We're gonna ask the result to be put into here static ResultQueue<std::string, u32, u8, u8> result_queue; // Throw a request in m_get_texture_queue.add(name, 0, 0, &result_queue); /*infostream<<"Waiting for texture from main thread, name=\"" <<name<<"\""<<std::endl;*/ try { while(true) { // Wait result for a second GetResult<std::string, u32, u8, u8> result = result_queue.pop_front(1000); if (result.key == name) { return result.item; } } } catch(ItemNotFoundException &e) { errorstream<<"Waiting for texture " << name << " timed out."<<std::endl; return 0; } } infostream<<"getTextureId(): Failed"<<std::endl; return 0; } // Draw an image on top of an another one, using the alpha channel of the // source image static void blit_with_alpha(video::IImage *src, video::IImage *dst, v2s32 src_pos, v2s32 dst_pos, v2u32 size); // Like blit_with_alpha, but only modifies destination pixels that // are fully opaque static void blit_with_alpha_overlay(video::IImage *src, video::IImage *dst, v2s32 src_pos, v2s32 dst_pos, v2u32 size); // Apply a color to an image. Uses an int (0-255) to calculate the ratio. // If the ratio is 255 or -1 and keep_alpha is true, then it multiples the // color alpha with the destination alpha. // Otherwise, any pixels that are not fully transparent get the color alpha. static void apply_colorize(video::IImage *dst, v2u32 dst_pos, v2u32 size, video::SColor color, int ratio, bool keep_alpha); // Apply a mask to an image static void apply_mask(video::IImage *mask, video::IImage *dst, v2s32 mask_pos, v2s32 dst_pos, v2u32 size); // Draw or overlay a crack static void draw_crack(video::IImage *crack, video::IImage *dst, bool use_overlay, s32 frame_count, s32 progression, video::IVideoDriver *driver); // Brighten image void brighten(video::IImage *image); // Parse a transform name u32 parseImageTransform(const std::string& s); // Apply transform to image dimension core::dimension2d<u32> imageTransformDimension(u32 transform, core::dimension2d<u32> dim); // Apply transform to image data void imageTransform(u32 transform, video::IImage *src, video::IImage *dst); /* This method generates all the textures */ u32 TextureSource::generateTexture(const std::string &name) { //infostream << "generateTexture(): name=\"" << name << "\"" << std::endl; // Empty name means texture 0 if (name == "") { infostream<<"generateTexture(): name is empty"<<std::endl; return 0; } { /* See if texture already exists */ MutexAutoLock lock(m_textureinfo_cache_mutex); std::map<std::string, u32>::iterator n; n = m_name_to_id.find(name); if (n != m_name_to_id.end()) { return n->second; } } /* Calling only allowed from main thread */ if (!thr_is_current_thread(m_main_thread)) { errorstream<<"TextureSource::generateTexture() " "called not from main thread"<<std::endl; return 0; } video::IVideoDriver *driver = m_device->getVideoDriver(); sanity_check(driver); video::IImage *img = generateImage(name); video::ITexture *tex = NULL; if (img != NULL) { #ifdef __ANDROID__ img = Align2Npot2(img, driver); #endif // Create texture from resulting image tex = driver->addTexture(name.c_str(), img); guiScalingCache(io::path(name.c_str()), driver, img); img->drop(); } /* Add texture to caches (add NULL textures too) */ MutexAutoLock lock(m_textureinfo_cache_mutex); u32 id = m_textureinfo_cache.size(); TextureInfo ti(name, tex); m_textureinfo_cache.push_back(ti); m_name_to_id[name] = id; return id; } std::string TextureSource::getTextureName(u32 id) { MutexAutoLock lock(m_textureinfo_cache_mutex); if (id >= m_textureinfo_cache.size()) { errorstream<<"TextureSource::getTextureName(): id="<<id <<" >= m_textureinfo_cache.size()=" <<m_textureinfo_cache.size()<<std::endl; return ""; } return m_textureinfo_cache[id].name; } video::ITexture* TextureSource::getTexture(u32 id) { MutexAutoLock lock(m_textureinfo_cache_mutex); if (id >= m_textureinfo_cache.size()) return NULL; return m_textureinfo_cache[id].texture; } video::ITexture* TextureSource::getTexture(const std::string &name, u32 *id) { u32 actual_id = getTextureId(name); if (id){ *id = actual_id; } return getTexture(actual_id); } video::ITexture* TextureSource::getTextureForMesh(const std::string &name, u32 *id) { return getTexture(name + "^[applyfiltersformesh", id); } void TextureSource::processQueue() { /* Fetch textures */ //NOTE this is only thread safe for ONE consumer thread! if (!m_get_texture_queue.empty()) { GetRequest<std::string, u32, u8, u8> request = m_get_texture_queue.pop(); /*infostream<<"TextureSource::processQueue(): " <<"got texture request with " <<"name=\""<<request.key<<"\"" <<std::endl;*/ m_get_texture_queue.pushResult(request, generateTexture(request.key)); } } void TextureSource::insertSourceImage(const std::string &name, video::IImage *img) { //infostream<<"TextureSource::insertSourceImage(): name="<<name<<std::endl; sanity_check(thr_is_current_thread(m_main_thread)); m_sourcecache.insert(name, img, true, m_device->getVideoDriver()); m_source_image_existence.set(name, true); } void TextureSource::rebuildImagesAndTextures() { MutexAutoLock lock(m_textureinfo_cache_mutex); video::IVideoDriver* driver = m_device->getVideoDriver(); sanity_check(driver); // Recreate textures for (u32 i=0; i<m_textureinfo_cache.size(); i++){ TextureInfo *ti = &m_textureinfo_cache[i]; video::IImage *img = generateImage(ti->name); #ifdef __ANDROID__ img = Align2Npot2(img, driver); sanity_check(img->getDimension().Height == npot2(img->getDimension().Height)); sanity_check(img->getDimension().Width == npot2(img->getDimension().Width)); #endif // Create texture from resulting image video::ITexture *t = NULL; if (img) { t = driver->addTexture(ti->name.c_str(), img); guiScalingCache(io::path(ti->name.c_str()), driver, img); img->drop(); } video::ITexture *t_old = ti->texture; // Replace texture ti->texture = t; if (t_old) m_texture_trash.push_back(t_old); } } video::ITexture* TextureSource::generateTextureFromMesh( const TextureFromMeshParams &params) { video::IVideoDriver *driver = m_device->getVideoDriver(); sanity_check(driver); #ifdef __ANDROID__ const GLubyte* renderstr = glGetString(GL_RENDERER); std::string renderer((char*) renderstr); // use no render to texture hack if ( (renderer.find("Adreno") != std::string::npos) || (renderer.find("Mali") != std::string::npos) || (renderer.find("Immersion") != std::string::npos) || (renderer.find("Tegra") != std::string::npos) || g_settings->getBool("inventory_image_hack") ) { // Get a scene manager scene::ISceneManager *smgr_main = m_device->getSceneManager(); sanity_check(smgr_main); scene::ISceneManager *smgr = smgr_main->createNewSceneManager(); sanity_check(smgr); const float scaling = 0.2; scene::IMeshSceneNode* meshnode = smgr->addMeshSceneNode(params.mesh, NULL, -1, v3f(0,0,0), v3f(0,0,0), v3f(1.0 * scaling,1.0 * scaling,1.0 * scaling), true); meshnode->setMaterialFlag(video::EMF_LIGHTING, true); meshnode->setMaterialFlag(video::EMF_ANTI_ALIASING, true); meshnode->setMaterialFlag(video::EMF_TRILINEAR_FILTER, m_setting_trilinear_filter); meshnode->setMaterialFlag(video::EMF_BILINEAR_FILTER, m_setting_bilinear_filter); meshnode->setMaterialFlag(video::EMF_ANISOTROPIC_FILTER, m_setting_anisotropic_filter); scene::ICameraSceneNode* camera = smgr->addCameraSceneNode(0, params.camera_position, params.camera_lookat); // second parameter of setProjectionMatrix (isOrthogonal) is ignored camera->setProjectionMatrix(params.camera_projection_matrix, false); smgr->setAmbientLight(params.ambient_light); smgr->addLightSceneNode(0, params.light_position, params.light_color, params.light_radius*scaling); core::dimension2d<u32> screen = driver->getScreenSize(); // Render scene driver->beginScene(true, true, video::SColor(0,0,0,0)); driver->clearZBuffer(); smgr->drawAll(); core::dimension2d<u32> partsize(screen.Width * scaling,screen.Height * scaling); irr::video::IImage* rawImage = driver->createImage(irr::video::ECF_A8R8G8B8, partsize); u8* pixels = static_cast<u8*>(rawImage->lock()); if (!pixels) { rawImage->drop(); return NULL; } core::rect<s32> source( screen.Width /2 - (screen.Width * (scaling / 2)), screen.Height/2 - (screen.Height * (scaling / 2)), screen.Width /2 + (screen.Width * (scaling / 2)), screen.Height/2 + (screen.Height * (scaling / 2)) ); glReadPixels(source.UpperLeftCorner.X, source.UpperLeftCorner.Y, partsize.Width, partsize.Height, GL_RGBA, GL_UNSIGNED_BYTE, pixels); driver->endScene(); // Drop scene manager smgr->drop(); unsigned int pixelcount = partsize.Width*partsize.Height; u8* runptr = pixels; for (unsigned int i=0; i < pixelcount; i++) { u8 B = *runptr; u8 G = *(runptr+1); u8 R = *(runptr+2); u8 A = *(runptr+3); //BGRA -> RGBA *runptr = R; runptr ++; *runptr = G; runptr ++; *runptr = B; runptr ++; *runptr = A; runptr ++; } video::IImage* inventory_image = driver->createImage(irr::video::ECF_A8R8G8B8, params.dim); rawImage->copyToScaling(inventory_image); rawImage->drop(); guiScalingCache(io::path(params.rtt_texture_name.c_str()), driver, inventory_image); video::ITexture *rtt = driver->addTexture(params.rtt_texture_name.c_str(), inventory_image); inventory_image->drop(); if (rtt == NULL) { errorstream << "TextureSource::generateTextureFromMesh(): failed to recreate texture from image: " << params.rtt_texture_name << std::endl; return NULL; } driver->makeColorKeyTexture(rtt, v2s32(0,0)); if (params.delete_texture_on_shutdown) m_texture_trash.push_back(rtt); return rtt; } #endif if (driver->queryFeature(video::EVDF_RENDER_TO_TARGET) == false) { static bool warned = false; if (!warned) { errorstream<<"TextureSource::generateTextureFromMesh(): " <<"EVDF_RENDER_TO_TARGET not supported."<<std::endl; warned = true; } return NULL; } // Create render target texture video::ITexture *rtt = driver->addRenderTargetTexture( params.dim, params.rtt_texture_name.c_str(), video::ECF_A8R8G8B8); if (rtt == NULL) { errorstream<<"TextureSource::generateTextureFromMesh(): " <<"addRenderTargetTexture returned NULL."<<std::endl; return NULL; } // Set render target if (!driver->setRenderTarget(rtt, false, true, video::SColor(0,0,0,0))) { driver->removeTexture(rtt); errorstream<<"TextureSource::generateTextureFromMesh(): " <<"failed to set render target"<<std::endl; return NULL; } // Get a scene manager scene::ISceneManager *smgr_main = m_device->getSceneManager(); assert(smgr_main); scene::ISceneManager *smgr = smgr_main->createNewSceneManager(); assert(smgr); scene::IMeshSceneNode* meshnode = smgr->addMeshSceneNode(params.mesh, NULL, -1, v3f(0,0,0), v3f(0,0,0), v3f(1,1,1), true); meshnode->setMaterialFlag(video::EMF_LIGHTING, true); meshnode->setMaterialFlag(video::EMF_ANTI_ALIASING, true); meshnode->setMaterialFlag(video::EMF_TRILINEAR_FILTER, m_setting_trilinear_filter); meshnode->setMaterialFlag(video::EMF_BILINEAR_FILTER, m_setting_bilinear_filter); meshnode->setMaterialFlag(video::EMF_ANISOTROPIC_FILTER, m_setting_anisotropic_filter); scene::ICameraSceneNode* camera = smgr->addCameraSceneNode(0, params.camera_position, params.camera_lookat); // second parameter of setProjectionMatrix (isOrthogonal) is ignored camera->setProjectionMatrix(params.camera_projection_matrix, false); smgr->setAmbientLight(params.ambient_light); smgr->addLightSceneNode(0, params.light_position, params.light_color, params.light_radius); // Render scene driver->beginScene(true, true, video::SColor(0,0,0,0)); smgr->drawAll(); driver->endScene(); // Drop scene manager smgr->drop(); // Unset render target driver->setRenderTarget(0, false, true, 0); if (params.delete_texture_on_shutdown) m_texture_trash.push_back(rtt); return rtt; } video::IImage* TextureSource::generateImage(const std::string &name) { /* Get the base image */ const char separator = '^'; const char paren_open = '('; const char paren_close = ')'; // Find last separator in the name s32 last_separator_pos = -1; u8 paren_bal = 0; for (s32 i = name.size() - 1; i >= 0; i--) { switch(name[i]) { case separator: if (paren_bal == 0) { last_separator_pos = i; i = -1; // break out of loop } break; case paren_open: if (paren_bal == 0) { errorstream << "generateImage(): unbalanced parentheses" << "(extranous '(') while generating texture \"" << name << "\"" << std::endl; return NULL; } paren_bal--; break; case paren_close: paren_bal++; break; default: break; } } if (paren_bal > 0) { errorstream << "generateImage(): unbalanced parentheses" << "(missing matching '(') while generating texture \"" << name << "\"" << std::endl; return NULL; } video::IImage *baseimg = NULL; /* If separator was found, make the base image using a recursive call. */ if (last_separator_pos != -1) { baseimg = generateImage(name.substr(0, last_separator_pos)); } video::IVideoDriver* driver = m_device->getVideoDriver(); sanity_check(driver); /* Parse out the last part of the name of the image and act according to it */ std::string last_part_of_name = name.substr(last_separator_pos + 1); /* If this name is enclosed in parentheses, generate it and blit it onto the base image */ if (last_part_of_name[0] == paren_open && last_part_of_name[last_part_of_name.size() - 1] == paren_close) { std::string name2 = last_part_of_name.substr(1, last_part_of_name.size() - 2); video::IImage *tmp = generateImage(name2); if (!tmp) { errorstream << "generateImage(): " "Failed to generate \"" << name2 << "\"" << std::endl; return NULL; } core::dimension2d<u32> dim = tmp->getDimension(); if (!baseimg) baseimg = driver->createImage(video::ECF_A8R8G8B8, dim); blit_with_alpha(tmp, baseimg, v2s32(0, 0), v2s32(0, 0), dim); tmp->drop(); } else if (!generateImagePart(last_part_of_name, baseimg)) { // Generate image according to part of name errorstream << "generateImage(): " "Failed to generate \"" << last_part_of_name << "\"" << std::endl; } // If no resulting image, print a warning if (baseimg == NULL) { errorstream << "generateImage(): baseimg is NULL (attempted to" " create texture \"" << name << "\")" << std::endl; } return baseimg; } #ifdef __ANDROID__ #include <GLES/gl.h> /** * Check and align image to npot2 if required by hardware * @param image image to check for npot2 alignment * @param driver driver to use for image operations * @return image or copy of image aligned to npot2 */ video::IImage * Align2Npot2(video::IImage * image, video::IVideoDriver* driver) { if (image == NULL) { return image; } core::dimension2d<u32> dim = image->getDimension(); std::string extensions = (char*) glGetString(GL_EXTENSIONS); if (extensions.find("GL_OES_texture_npot") != std::string::npos) { return image; } unsigned int height = npot2(dim.Height); unsigned int width = npot2(dim.Width); if ((dim.Height == height) && (dim.Width == width)) { return image; } if (dim.Height > height) { height *= 2; } if (dim.Width > width) { width *= 2; } video::IImage *targetimage = driver->createImage(video::ECF_A8R8G8B8, core::dimension2d<u32>(width, height)); if (targetimage != NULL) { image->copyToScaling(targetimage); } image->drop(); return targetimage; } #endif bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& baseimg) { video::IVideoDriver* driver = m_device->getVideoDriver(); sanity_check(driver); // Stuff starting with [ are special commands if (part_of_name.size() == 0 || part_of_name[0] != '[') { video::IImage *image = m_sourcecache.getOrLoad(part_of_name, m_device); #ifdef __ANDROID__ image = Align2Npot2(image, driver); #endif if (image == NULL) { if (part_of_name != "") { if (part_of_name.find("_normal.png") == std::string::npos){ errorstream<<"generateImage(): Could not load image \"" <<part_of_name<<"\""<<" while building texture"<<std::endl; errorstream<<"generateImage(): Creating a dummy" <<" image for \""<<part_of_name<<"\""<<std::endl; } else { infostream<<"generateImage(): Could not load normal map \"" <<part_of_name<<"\""<<std::endl; infostream<<"generateImage(): Creating a dummy" <<" normal map for \""<<part_of_name<<"\""<<std::endl; } } // Just create a dummy image //core::dimension2d<u32> dim(2,2); core::dimension2d<u32> dim(1,1); image = driver->createImage(video::ECF_A8R8G8B8, dim); sanity_check(image != NULL); /*image->setPixel(0,0, video::SColor(255,255,0,0)); image->setPixel(1,0, video::SColor(255,0,255,0)); image->setPixel(0,1, video::SColor(255,0,0,255)); image->setPixel(1,1, video::SColor(255,255,0,255));*/ image->setPixel(0,0, video::SColor(255,myrand()%256, myrand()%256,myrand()%256)); /*image->setPixel(1,0, video::SColor(255,myrand()%256, myrand()%256,myrand()%256)); image->setPixel(0,1, video::SColor(255,myrand()%256, myrand()%256,myrand()%256)); image->setPixel(1,1, video::SColor(255,myrand()%256, myrand()%256,myrand()%256));*/ } // If base image is NULL, load as base. if (baseimg == NULL) { //infostream<<"Setting "<<part_of_name<<" as base"<<std::endl; /* Copy it this way to get an alpha channel. Otherwise images with alpha cannot be blitted on images that don't have alpha in the original file. */ core::dimension2d<u32> dim = image->getDimension(); baseimg = driver->createImage(video::ECF_A8R8G8B8, dim); image->copyTo(baseimg); } // Else blit on base. else { //infostream<<"Blitting "<<part_of_name<<" on base"<<std::endl; // Size of the copied area core::dimension2d<u32> dim = image->getDimension(); //core::dimension2d<u32> dim(16,16); // Position to copy the blitted to in the base image core::position2d<s32> pos_to(0,0); // Position to copy the blitted from in the blitted image core::position2d<s32> pos_from(0,0); // Blit /*image->copyToWithAlpha(baseimg, pos_to, core::rect<s32>(pos_from, dim), video::SColor(255,255,255,255), NULL);*/ core::dimension2d<u32> dim_dst = baseimg->getDimension(); if (dim == dim_dst) { blit_with_alpha(image, baseimg, pos_from, pos_to, dim); } else if (dim.Width * dim.Height < dim_dst.Width * dim_dst.Height) { // Upscale overlying image video::IImage* scaled_image = m_device->getVideoDriver()-> createImage(video::ECF_A8R8G8B8, dim_dst); image->copyToScaling(scaled_image); blit_with_alpha(scaled_image, baseimg, pos_from, pos_to, dim_dst); scaled_image->drop(); } else { // Upscale base image video::IImage* scaled_base = m_device->getVideoDriver()-> createImage(video::ECF_A8R8G8B8, dim); baseimg->copyToScaling(scaled_base); baseimg->drop(); baseimg = scaled_base; blit_with_alpha(image, baseimg, pos_from, pos_to, dim); } } //cleanup image->drop(); } else { // A special texture modification /*infostream<<"generateImage(): generating special " <<"modification \""<<part_of_name<<"\"" <<std::endl;*/ /* [crack:N:P [cracko:N:P Adds a cracking texture N = animation frame count, P = crack progression */ if (str_starts_with(part_of_name, "[crack")) { if (baseimg == NULL) { errorstream<<"generateImagePart(): baseimg == NULL " <<"for part_of_name=\""<<part_of_name <<"\", cancelling."<<std::endl; return false; } // Crack image number and overlay option bool use_overlay = (part_of_name[6] == 'o'); Strfnd sf(part_of_name); sf.next(":"); s32 frame_count = stoi(sf.next(":")); s32 progression = stoi(sf.next(":")); if (progression >= 0) { /* Load crack image. It is an image with a number of cracking stages horizontally tiled. */ video::IImage *img_crack = m_sourcecache.getOrLoad( "crack_anylength.png", m_device); if (img_crack) { draw_crack(img_crack, baseimg, use_overlay, frame_count, progression, driver); img_crack->drop(); } } } /* [combine:WxH:X,Y=filename:X,Y=filename2 Creates a bigger texture from an amount of smaller ones */ else if (str_starts_with(part_of_name, "[combine")) { Strfnd sf(part_of_name); sf.next(":"); u32 w0 = stoi(sf.next("x")); u32 h0 = stoi(sf.next(":")); //infostream<<"combined w="<<w0<<" h="<<h0<<std::endl; core::dimension2d<u32> dim(w0,h0); if (baseimg == NULL) { baseimg = driver->createImage(video::ECF_A8R8G8B8, dim); baseimg->fill(video::SColor(0,0,0,0)); } while (sf.at_end() == false) { u32 x = stoi(sf.next(",")); u32 y = stoi(sf.next("=")); std::string filename = sf.next(":"); infostream<<"Adding \""<<filename <<"\" to combined ("<<x<<","<<y<<")" <<std::endl; video::IImage *img = m_sourcecache.getOrLoad(filename, m_device); if (img) { core::dimension2d<u32> dim = img->getDimension(); infostream<<"Size "<<dim.Width <<"x"<<dim.Height<<std::endl; core::position2d<s32> pos_base(x, y); video::IImage *img2 = driver->createImage(video::ECF_A8R8G8B8, dim); img->copyTo(img2); img->drop(); /*img2->copyToWithAlpha(baseimg, pos_base, core::rect<s32>(v2s32(0,0), dim), video::SColor(255,255,255,255), NULL);*/ blit_with_alpha(img2, baseimg, v2s32(0,0), pos_base, dim); img2->drop(); } else { errorstream << "generateImagePart(): Failed to load image \"" << filename << "\" for [combine" << std::endl; } } } /* "[brighten" */ else if (str_starts_with(part_of_name, "[brighten")) { if (baseimg == NULL) { errorstream<<"generateImagePart(): baseimg==NULL " <<"for part_of_name=\""<<part_of_name <<"\", cancelling."<<std::endl; return false; } brighten(baseimg); } /* "[noalpha" Make image completely opaque. Used for the leaves texture when in old leaves mode, so that the transparent parts don't look completely black when simple alpha channel is used for rendering. */