summaryrefslogtreecommitdiff
path: root/src/util/numeric.cpp
blob: a48a72a8a8e8c912d8d2062c2423f2123ee9b75a (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
/*
Minetest
Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>

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

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include "numeric.h"

#include "log.h"
#include "../constants.h" // BS, MAP_BLOCKSIZE
#include "../noise.h" // PseudoRandom, PcgRandom
#include "../threading/mutex_auto_lock.h"
#include <cstring>


// myrand

PcgRandom g_pcgrand;

u32 myrand()
{
	return g_pcgrand.next();
}

void mysrand(unsigned int seed)
{
	g_pcgrand.seed(seed);
}

void myrand_bytes(void *out, size_t len)
{
	g_pcgrand.bytes(out, len);
}

int myrand_range(int min, int max)
{
	return g_pcgrand.range(min, max);
}


/*
	64-bit unaligned version of MurmurHash
*/
u64 murmur_hash_64_ua(const void *key, int len, unsigned int seed)
{
	const u64 m = 0xc6a4a7935bd1e995ULL;
	const int r = 47;
	u64 h = seed ^ (len * m);

	const u64 *data = (const u64 *)key;
	const u64 *end = data + (len / 8);

	while (data != end) {
		u64 k;
		memcpy(&k, data, sizeof(u64));
		data++;

		k *= m;
		k ^= k >> r;
		k *= m;

		h ^= k;
		h *= m;
	}

	const unsigned char *data2 = (const unsigned char *)data;
	switch (len & 7) {
		case 7: h ^= (u64)data2[6] << 48;
		case 6: h ^= (u64)data2[5] << 40;
		case 5: h ^= (u64)data2[4] << 32;
		case 4: h ^= (u64)data2[3] << 24;
		case 3: h ^= (u64)data2[2] << 16;
		case 2: h ^= (u64)data2[1] << 8;
		case 1: h ^= (u64)data2[0];
				h *= m;
	}

	h ^= h >> r;
	h *= m;
	h ^= h >> r;

	return h;
}

/*
	blockpos_b: position of block in block coordinates
	camera_pos: position of camera in nodes
	camera_dir: an unit vector pointing to camera direction
	range: viewing range
	distance_ptr: return location for distance from the camera
*/
bool isBlockInSight(v3s16 blockpos_b, v3f camera_pos, v3f camera_dir,
		f32 camera_fov, f32 range, f32 *distance_ptr)
{
	// Maximum radius of a block.  The magic number is
	// sqrt(3.0) / 2.0 in literal form.
	const f32 block_max_radius = 0.866025403784 * MAP_BLOCKSIZE * BS;

	v3s16 blockpos_nodes = blockpos_b * MAP_BLOCKSIZE;

	// Block center position
	v3f blockpos(
			((float)blockpos_nodes.X + MAP_BLOCKSIZE/2) * BS,
			((float)blockpos_nodes.Y + MAP_BLOCKSIZE/2) * BS,
			((float)blockpos_nodes.Z + MAP_BLOCKSIZE/2) * BS
	);

	// Block position relative to camera
	v3f blockpos_relative = blockpos - camera_pos;

	// Total distance
	f32 d = MYMAX(0, blockpos_relative.getLength() - block_max_radius);

	if(distance_ptr)
		*distance_ptr = d;

	// If block is far away, it's not in sight
	if(d > range)
		return false;

	// If block is (nearly) touching the camera, don't
	// bother validating further (that is, render it anyway)
	if(d == 0)
		return true;

	// Adjust camera position, for purposes of computing the angle,
	// such that a block that has any portion visible with the
	// current camera position will have the center visible at the
	// adjusted postion
	f32 adjdist = block_max_radius / cos((M_PI - camera_fov) / 2);

	// Block position relative to adjusted camera
	v3f blockpos_adj = blockpos - (camera_pos - camera_dir * adjdist);

	// Distance in camera direction (+=front, -=back)
	f32 dforward = blockpos_adj.dotProduct(camera_dir);

	// Cosine of the angle between the camera direction
	// and the block direction (camera_dir is an unit vector)
	f32 cosangle = dforward / blockpos_adj.getLength();

	// If block is not in the field of view, skip it
	// HOTFIX: use sligthly increased angle (+10%) to fix too agressive
	// culling. Somebody have to find out whats wrong with the math here.
	// Previous value: camera_fov / 2
	if(cosangle < cos(camera_fov * 0.55))
		return false;

	return true;
}
atc.train_set_command(train, command, iconnid==1) atprint("Sending ATC Command to", train_id, ":", command, "iconnid=",iconnid) return true else atwarn("ATC rail at", pos, ": Sending command failed: The train",train_id,"does not exist. This seems to be a bug.") end else atwarn("ATC rail at", pos, ": Sending command failed: There's no train at this position. This seems to be a bug.") end else atwarn("ATC rail at", pos, ": Sending command failed: Entry for controller not found.") atwarn("ATC rail at", pos, ": Please visit controller and click 'Save'") end return false end -- Resets any ATC commands the train is currently executing, including the target speed (tarvelocity) it is instructed to hold -- if keep_tarvel is set, does not clear the tarvelocity function atc.train_reset_command(train, keep_tarvel) train.atc_command=nil train.atc_delay=nil train.atc_brake_target=nil train.atc_wait_finish=nil train.atc_arrow=nil if not keep_tarvel then train.tarvelocity=nil end end --nodes local idxtrans={static=1, mesecon=2, digiline=3} local apn_func=function(pos) -- FIX for long-persisting ndb bug: there's no node in parameter 2 of this function! local meta=minetest.get_meta(pos) if meta then meta:set_string("infotext", attrans("ATC controller, unconfigured.")) meta:set_string("formspec", atc.get_atc_controller_formspec(pos, meta)) end end advtrains.atc_function = function(def, preset, suffix, rotation) return { after_place_node=apn_func, after_dig_node=function(pos) advtrains.invalidate_all_paths(pos) advtrains.ndb.clear(pos) local pts=minetest.pos_to_string(pos) atc.controllers[pts]=nil end, on_receive_fields = function(pos, formname, fields, player) if advtrains.is_protected(pos, player:get_player_name()) then minetest.record_protection_violation(pos, player:get_player_name()) return end local meta=minetest.get_meta(pos) if meta then if not fields.save then --[[--maybe only the dropdown changed if fields.mode then meta:set_string("mode", idxtrans[fields.mode]) if fields.mode=="digiline" then meta:set_string("infotext", attrans("ATC controller, mode @1\nChannel: @2", fields.mode, meta:get_string("command")) ) else meta:set_string("infotext", attrans("ATC controller, mode @1\nCommand: @2", fields.mode, meta:get_string("command")) ) end meta:set_string("formspec", atc.get_atc_controller_formspec(pos, meta)) end]]-- return end --meta:set_string("mode", idxtrans[fields.mode]) meta:set_string("command", fields.command) --meta:set_string("command_on", fields.command_on) meta:set_string("channel", fields.channel) --if fields.mode=="digiline" then -- meta:set_string("infotext", attrans("ATC controller, mode @1\nChannel: @2", fields.mode, meta:get_string("command")) ) --else meta:set_string("infotext", attrans("ATC controller, mode @1\nCommand: @2", "-", meta:get_string("command")) ) --end meta:set_string("formspec", atc.get_atc_controller_formspec(pos, meta)) local pts=minetest.pos_to_string(pos) local _, conns=advtrains.get_rail_info_at(pos, advtrains.all_tracktypes) atc.controllers[pts]={command=fields.command} if #advtrains.occ.get_trains_at(pos) > 0 then atc.send_command(pos) end end end, advtrains = { on_train_enter = function(pos, train_id) atc.send_command(pos) end, }, } end function atc.get_atc_controller_formspec(pos, meta) local mode=tonumber(meta:get_string("mode")) or 1 local command=meta:get_string("command") local command_on=meta:get_string("command_on") local channel=meta:get_string("channel") local formspec="size[8,6]" -- "dropdown[0,0;3;mode;static,mesecon,digiline;"..mode.."]" if mode<3 then formspec=formspec.."field[0.5,1.5;7,1;command;"..attrans("Command")..";"..minetest.formspec_escape(command).."]" if tonumber(mode)==2 then formspec=formspec.."field[0.5,3;7,1;command_on;"..attrans("Command (on)")..";"..minetest.formspec_escape(command_on).."]" end else formspec=formspec.."field[0.5,1.5;7,1;channel;"..attrans("Digiline channel")..";"..minetest.formspec_escape(channel).."]" end return formspec.."button_exit[0.5,4.5;7,1;save;"..attrans("Save").."]" end --from trainlogic.lua train step local matchptn={ ["SM"]=function(id, train) train.tarvelocity=train.max_speed return 2 end, ["S([0-9]+)"]=function(id, train, match) train.tarvelocity=tonumber(match) return #match+1 end, ["B([0-9]+)"]=function(id, train, match) if train.velocity>tonumber(match) then train.atc_brake_target=tonumber(match) if not train.tarvelocity or train.tarvelocity>train.atc_brake_target then train.tarvelocity=train.atc_brake_target end end return #match+1 end, ["BB"]=function(id, train) train.atc_brake_target = -1 train.tarvelocity = 0 return 2 end, ["W"]=function(id, train) train.atc_wait_finish=true return 1 end, ["D([0-9]+)"]=function(id, train, match) train.atc_delay=tonumber(match) return #match+1 end, ["R"]=function(id, train) if train.velocity<=0 then advtrains.invert_train(id) advtrains.train_ensure_init(id, train) -- no one minds if this failed... this shouldn't even be called without train being initialized... else atwarn(sid(id), attrans("ATC Reverse command warning: didn't reverse train, train moving!")) end return 1 end, ["O([LRC])"]=function(id, train, match) local tt={L=-1, R=1, C=0} local arr=train.atc_arrow and 1 or -1 train.door_open = tt[match]*arr return 2 end, ["K"] = function(id, train) if train.door_open == 0 then atwarn(sid(id), attrans("ATC Kick command warning: Doors closed")) return 1 end if train.velocity > 0 then atwarn(sid(id), attrans("ATC Kick command warning: Train moving")) return 1 end local tp = train.trainparts for i=1,#tp do local data = advtrains.wagons[tp[i]] local obj = advtrains.wagon_objects[tp[i]] if data and obj then local ent = obj:get_luaentity() if ent then for seatno,seat in pairs(ent.seats) do if data.seatp[seatno] and not ent:is_driver_stand(seat) then ent:get_off(seatno) end end end end end return 1 end, ["A([01])"]=function(id, train, match) if not advtrains.interlocking then return 2 end advtrains.interlocking.ars_set_disable(train, match=="0") return 2 end, } eval_conditional = function(command, arrow, speed) --conditional statement? local is_cond, cond_applies, compare local cond, rest=string.match(command, "^I([%+%-])(.+)$") if cond then is_cond=true if cond=="+" then cond_applies=arrow end if cond=="-" then cond_applies=not arrow end else cond, compare, rest=string.match(command, "^I([<>]=?)([0-9]+)(.+)$") if cond and compare then is_cond=true if cond=="<" then cond_applies=speed<tonumber(compare) end if cond==">" then cond_applies=speed>tonumber(compare) end if cond=="<=" then cond_applies=speed<=tonumber(compare) end if cond==">=" then cond_applies=speed>=tonumber(compare) end end end if is_cond then atprint("Evaluating if statement: "..command) atprint("Cond: "..(cond or "nil")) atprint("Applies: "..(cond_applies and "true" or "false")) atprint("Rest: "..rest) --find end of conditional statement local nest, pos, elsepos=0, 1 while nest>=0 do if pos>#rest then atwarn(sid(id), attrans("ATC command syntax error: I statement not closed: @1",command)) return "" end local char=string.sub(rest, pos, pos) if char=="I" then nest=nest+1 end if char==";" then nest=nest-1 end if nest==0 and char=="E" then elsepos=pos+0 end pos=pos+1 end if not elsepos then elsepos=pos-1 end if cond_applies then command=string.sub(rest, 1, elsepos-1)..string.sub(rest, pos) else command=string.sub(rest, elsepos+1, pos-2)..string.sub(rest, pos) end atprint("Result: "..command) end return command end function atc.execute_atc_command(id, train) --strip whitespaces local command=string.match(train.atc_command, "^%s*(.*)$") if string.match(command, "^%s*$") then train.atc_command=nil return end train.atc_command = eval_conditional(command, train.atc_arrow, train.velocity) if not train.atc_command then return end command=string.match(train.atc_command, "^%s*(.*)$") if string.match(command, "^%s*$") then train.atc_command=nil return end for pattern, func in pairs(matchptn) do local match=string.match(command, "^"..pattern) if match then local patlen=func(id, train, match) atprint("Executing: "..string.sub(command, 1, patlen)) train.atc_command=string.sub(command, patlen+1) if train.atc_delay<=0 and not train.atc_wait_finish then --continue (recursive, cmds shouldn't get too long, and it's a end-recursion.) atc.execute_atc_command(id, train) end return end end atwarn(sid(id), attrans("ATC command parse error: Unknown command: @1", command)) atc.train_reset_command(train, true) end --move table to desired place advtrains.atc=atc