aboutsummaryrefslogtreecommitdiff
path: root/advtrains_interlocking/train_sections.lua
blob: 21d3d133ed6f8643b7d96946b30b5c167bffcf9f (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
-- train_related.lua
-- Occupation of track sections - mainly implementation of train callbacks

--[[
Track section occupation is saved as follows

In train:
train.il_sections = {
	[n] = {ts_id = <...> (origin = <sigd>)}
}
-- "origin" is the TCB (signal describer) the train initially entered this section

In track section
ts.trains = {
	[n] = <train_id>
}

When any inconsistency is detected, we will assume the most restrictive setup.
It will be possible to indicate a section "free" via the GUI.
]]

local ildb = advtrains.interlocking.db

local sigd_equal = advtrains.interlocking.sigd_equal

local function itexist(tbl, com)
	for _,item in ipairs(tbl) do
		if (item==com) then
			return true
		end
	end
	return false
end
local function itkexist(tbl, ikey, com)
	for _,item in ipairs(tbl) do
		if item[ikey] == com then
			return true
		end
	end
	return false
end

local function itremove(tbl, com)
	local i=1
	while i <= #tbl do
		if tbl[i] == com then
			table.remove(tbl, i)
		else
			i = i + 1
		end
	end
end
local function itkremove(tbl, ikey, com)
	local i=1
	while i <= #tbl do
		if tbl[i][ikey] == com then
			table.remove(tbl, i)
		else
			i = i + 1
		end
	end
end

local function setsection(tid, train, ts_id, ts, sigd)
	-- train
	if not train.il_sections then train.il_sections = {} end
	if not itkexist(train.il_sections, "ts_id", ts_id) then
		table.insert(train.il_sections, {ts_id = ts_id, origin = origin})
	end
	
	-- ts
	if not ts.trains then ts.trains = {} end
	if not itexist(ts.trains, tid) then
		table.insert(ts.trains, tid)
	end
	
	-- routes
	local tcbs = advtrains.interlocking.db.get_tcbs(sigd)
	
	-- route setting - clear route state
	if ts.route then
		--atdebug(tid,"enters",ts_id,"examining Routestate",ts.route)
		if not sigd_equal(ts.route.entry, sigd) then
			-- Train entered not from the route. Locate origin and cancel route!
			atwarn("Train",tid,"hit route",ts.route.rsn,"!")
			advtrains.interlocking.route.cancel_route_from(ts.route.origin)
			atwarn("Route was cancelled.")
		else
			-- train entered route regularily. Reset route and signal
			tcbs.route_committed = nil
			tcbs.route_comitted = nil -- TODO compatibility cleanup
			tcbs.aspect = nil
			tcbs.route_origin = nil
			advtrains.interlocking.update_signal_aspect(tcbs)
			if tcbs.signal and sigd_equal(ts.route.entry, ts.route.origin) then
				if tcbs.route_auto and tcbs.routeset then
					--atdebug("Resetting route (",ts.route.origin,")")
					advtrains.interlocking.route.update_route(ts.route.origin, tcbs)
				else
					tcbs.routeset = nil
				end
			end
		end
		ts.route = nil
	end
	if tcbs.signal then
		advtrains.interlocking.route.update_route(sigd, tcbs)
	end
end

local function freesection(tid, train, ts_id, ts)
	-- train
	if not train.il_sections then train.il_sections = {} end
	itkremove(train.il_sections, "ts_id", ts_id)
	
	-- ts
	if not ts.trains then ts.trains = {} end
	itremove(ts.trains, tid)
	
	if ts.route_post then
		advtrains.interlocking.route.free_route_locks(ts_id, ts.route_post.locks)
		if ts.route_post.next then
			--this does nothing when the train went the right way, because
			-- "route" info is already cleared.
			advtrains.interlocking.route.cancel_route_from(ts.route_post.next)
		end
		ts.route_post = nil
	end
	-- This must be delayed, because this code is executed in-between a train step
	-- TODO use luaautomation timers?
	minetest.after(0, advtrains.interlocking.route.update_waiting, "ts", ts_id)
end


-- This is regular operation
-- The train is on a track and drives back and forth

-- This sets the section for both directions, to be failsafe
advtrains.tnc_register_on_enter(function(pos, id, train, index)
	local tcb = ildb.get_tcb(pos)
	if tcb then
		for connid=1,2 do
			local ts = tcb[connid].ts_id and ildb.get_ts(tcb[connid].ts_id)
			if ts then
				setsection(id, train, tcb[connid].ts_id, ts, {p=pos, s=connid})
			end
		end
	end
end)


-- this time, of course, only clear the backside (cp connid)
advtrains.tnc_register_on_leave(function(pos, id, train, index)
	local tcb = ildb.get_tcb(pos)
	if tcb and train.path_cp[index] then
		local connid = train.path_cp[index]
		local ts = tcb[connid].ts_id and ildb.get_ts(tcb[connid].ts_id)
		if ts then
			freesection(id, train, tcb[connid].ts_id, ts)
		end
	end
end)

-- those callbacks are needed to account for created and removed trains (also regarding coupling)

advtrains.te_register_on_create(function(id, train)
	-- let's see what track sections we find here
	local index = atround(train.index)
	local pos = advtrains.path_get(train, index)
	local ts_id, origin = ildb.get_ts_at_pos(pos)
	if ts_id then
		local ts = ildb.get_ts(ts_id)
		if ts then
			setsection(id, train, ts_id, ts, origin)
		else
			atwarn("ILDB corruption: TCB",origin," has invalid TS reference")
		end
		-- Make train a shunt move
		train.is_shunt = true
	elseif ts_id==nil then
		atlog("Train",id,": Unable to determine whether to block a track section!")
	else
		--atdebug("Train",id,": Outside of interlocked area!")
	end
end)

advtrains.te_register_on_remove(function(id, train)
	if train.il_sections then
		for idx, item in ipairs(train.il_sections) do
			
			local ts = item.ts_id and ildb.get_ts(item.ts_id)
			
			if ts and ts.trains then
				itremove(ts.trains, id)
			end
		end
		train.il_sections = nil
	end
end)
class="hl opt">!= NULL) delete[] data; u32 l = MAP_BLOCKSIZE * MAP_BLOCKSIZE * MAP_BLOCKSIZE; data = new MapNode[l]; for(u32 i=0; i<l; i++){ //data[i] = MapNode(); data[i] = MapNode(CONTENT_IGNORE); } raiseModified(MOD_STATE_WRITE_NEEDED, "reallocate"); } /* Flags */ bool isDummy() { return (data == NULL); } void unDummify() { assert(isDummy()); reallocate(); } // m_modified methods void raiseModified(u32 mod, const std::string &reason="unknown") { if(mod > m_modified){ m_modified = mod; m_modified_reason = reason; m_modified_reason_too_long = false; if(m_modified >= MOD_STATE_WRITE_AT_UNLOAD){ m_disk_timestamp = m_timestamp; } } else if(mod == m_modified){ if(!m_modified_reason_too_long){ if(m_modified_reason.size() < 40) m_modified_reason += ", " + reason; else{ m_modified_reason += "..."; m_modified_reason_too_long = true; } } } } u32 getModified() { return m_modified; } std::string getModifiedReason() { return m_modified_reason; } void resetModified() { m_modified = MOD_STATE_CLEAN; m_modified_reason = "none"; m_modified_reason_too_long = false; } // is_underground getter/setter bool getIsUnderground() { return is_underground; } void setIsUnderground(bool a_is_underground) { is_underground = a_is_underground; raiseModified(MOD_STATE_WRITE_NEEDED, "setIsUnderground"); } void setLightingExpired(bool expired) { if(expired != m_lighting_expired){ m_lighting_expired = expired; raiseModified(MOD_STATE_WRITE_NEEDED, "setLightingExpired"); } } bool getLightingExpired() { return m_lighting_expired; } bool isGenerated() { return m_generated; } void setGenerated(bool b) { if(b != m_generated){ raiseModified(MOD_STATE_WRITE_NEEDED, "setGenerated"); m_generated = b; } } bool isValid() { if(m_lighting_expired) return false; if(data == NULL) return false; return true; } /* Position stuff */ v3s16 getPos() { return m_pos; } v3s16 getPosRelative() { return m_pos * MAP_BLOCKSIZE; } core::aabbox3d<s16> getBox() { return core::aabbox3d<s16>(getPosRelative(), getPosRelative() + v3s16(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE) - v3s16(1,1,1)); } /* Regular MapNode get-setters */ bool isValidPosition(v3s16 p) { if(data == NULL) return false; return (p.X >= 0 && p.X < MAP_BLOCKSIZE && p.Y >= 0 && p.Y < MAP_BLOCKSIZE && p.Z >= 0 && p.Z < MAP_BLOCKSIZE); } MapNode getNode(s16 x, s16 y, s16 z) { if(data == NULL) throw InvalidPositionException(); if(x < 0 || x >= MAP_BLOCKSIZE) throw InvalidPositionException(); if(y < 0 || y >= MAP_BLOCKSIZE) throw InvalidPositionException(); if(z < 0 || z >= MAP_BLOCKSIZE) throw InvalidPositionException(); return data[z*MAP_BLOCKSIZE*MAP_BLOCKSIZE + y*MAP_BLOCKSIZE + x]; } MapNode getNode(v3s16 p) { return getNode(p.X, p.Y, p.Z); } MapNode getNodeNoEx(v3s16 p) { try{ return getNode(p.X, p.Y, p.Z); }catch(InvalidPositionException &e){ return MapNode(CONTENT_IGNORE); } } void setNode(s16 x, s16 y, s16 z, MapNode & n) { if(data == NULL) throw InvalidPositionException(); if(x < 0 || x >= MAP_BLOCKSIZE) throw InvalidPositionException(); if(y < 0 || y >= MAP_BLOCKSIZE) throw InvalidPositionException(); if(z < 0 || z >= MAP_BLOCKSIZE) throw InvalidPositionException(); data[z*MAP_BLOCKSIZE*MAP_BLOCKSIZE + y*MAP_BLOCKSIZE + x] = n; raiseModified(MOD_STATE_WRITE_NEEDED, "setNode"); } void setNode(v3s16 p, MapNode & n) { setNode(p.X, p.Y, p.Z, n); } /* Non-checking variants of the above */ MapNode getNodeNoCheck(s16 x, s16 y, s16 z) { if(data == NULL) throw InvalidPositionException(); return data[z*MAP_BLOCKSIZE*MAP_BLOCKSIZE + y*MAP_BLOCKSIZE + x]; } MapNode getNodeNoCheck(v3s16 p) { return getNodeNoCheck(p.X, p.Y, p.Z); } void setNodeNoCheck(s16 x, s16 y, s16 z, MapNode & n) { if(data == NULL) throw InvalidPositionException(); data[z*MAP_BLOCKSIZE*MAP_BLOCKSIZE + y*MAP_BLOCKSIZE + x] = n; raiseModified(MOD_STATE_WRITE_NEEDED, "setNodeNoCheck"); } void setNodeNoCheck(v3s16 p, MapNode & n) { setNodeNoCheck(p.X, p.Y, p.Z, n); } /* These functions consult the parent container if the position is not valid on this MapBlock. */ bool isValidPositionParent(v3s16 p); MapNode getNodeParent(v3s16 p); void setNodeParent(v3s16 p, MapNode & n); MapNode getNodeParentNoEx(v3s16 p); void drawbox(s16 x0, s16 y0, s16 z0, s16 w, s16 h, s16 d, MapNode node) { for(u16 z=0; z<d; z++) for(u16 y=0; y<h; y++) for(u16 x=0; x<w; x++) setNode(x0+x, y0+y, z0+z, node); } // See comments in mapblock.cpp bool propagateSunlight(std::set<v3s16> & light_sources, bool remove_light=false, bool *black_air_left=NULL); // Copies data to VoxelManipulator to getPosRelative() void copyTo(VoxelManipulator &dst); // Copies data from VoxelManipulator getPosRelative() void copyFrom(VoxelManipulator &dst); /* Update day-night lighting difference flag. Sets m_day_night_differs to appropriate value. These methods don't care about neighboring blocks. */ void actuallyUpdateDayNightDiff(); /* Call this to schedule what the previous function does to be done when the value is actually needed. */ void expireDayNightDiff(); bool getDayNightDiff() { if(m_day_night_differs_expired) actuallyUpdateDayNightDiff(); return m_day_night_differs; } /* Miscellaneous stuff */ /* Tries to measure ground level. Return value: -1 = only air -2 = only ground -3 = random fail 0...MAP_BLOCKSIZE-1 = ground level */ s16 getGroundLevel(v2s16 p2d); /* Timestamp (see m_timestamp) NOTE: BLOCK_TIMESTAMP_UNDEFINED=0xffffffff means there is no timestamp. */ void setTimestamp(u32 time) { m_timestamp = time; raiseModified(MOD_STATE_WRITE_AT_UNLOAD, "setTimestamp"); } void setTimestampNoChangedFlag(u32 time) { m_timestamp = time; } u32 getTimestamp() { return m_timestamp; } u32 getDiskTimestamp() { return m_disk_timestamp; } /* See m_usage_timer */ void resetUsageTimer() { m_usage_timer = 0; } void incrementUsageTimer(float dtime) { m_usage_timer += dtime; } u32 getUsageTimer() { return m_usage_timer; } /* See m_refcount */ void refGrab() { m_refcount++; } void refDrop() { m_refcount--; } int refGet() { return m_refcount; } /* Node Timers */ // Get timer NodeTimer getNodeTimer(v3s16 p){ return m_node_timers.get(p); } // Deletes timer void removeNodeTimer(v3s16 p){ m_node_timers.remove(p); } // Deletes old timer and sets a new one void setNodeTimer(v3s16 p, NodeTimer t){ m_node_timers.set(p,t); } // Deletes all timers void clearNodeTimers(){ m_node_timers.clear(); } /* Serialization */ // These don't write or read version by itself // Set disk to true for on-disk format, false for over-the-network format void serialize(std::ostream &os, u8 version, bool disk); // If disk == true: In addition to doing other things, will add // unknown blocks from id-name mapping to wndef void deSerialize(std::istream &is, u8 version, bool disk); private: /* Private methods */ void deSerialize_pre22(std::istream &is, u8 version, bool disk); /* Used only internally, because changes can't be tracked */ MapNode & getNodeRef(s16 x, s16 y, s16 z) { if(data == NULL) throw InvalidPositionException(); if(x < 0 || x >= MAP_BLOCKSIZE) throw InvalidPositionException(); if(y < 0 || y >= MAP_BLOCKSIZE) throw InvalidPositionException(); if(z < 0 || z >= MAP_BLOCKSIZE) throw InvalidPositionException(); return data[z*MAP_BLOCKSIZE*MAP_BLOCKSIZE + y*MAP_BLOCKSIZE + x]; } MapNode & getNodeRef(v3s16 &p) { return getNodeRef(p.X, p.Y, p.Z); } public: /* Public member variables */ #ifndef SERVER // Only on client MapBlockMesh *mesh; //JMutex mesh_mutex; #endif NodeMetadataList m_node_metadata; NodeTimerList m_node_timers; StaticObjectList m_static_objects; private: /* Private member variables */ // NOTE: Lots of things rely on this being the Map Map *m_parent; // Position in blocks on parent v3s16 m_pos; IGameDef *m_gamedef; /* If NULL, block is a dummy block. Dummy blocks are used for caching not-found-on-disk blocks. */ MapNode * data; /* - On the server, this is used for telling whether the block has been modified from the one on disk. - On the client, this is used for nothing. */ u32 m_modified; std::string m_modified_reason; bool m_modified_reason_too_long; /* When propagating sunlight and the above block doesn't exist, sunlight is assumed if this is false. In practice this is set to true if the block is completely undeground with nothing visible above the ground except caves. */ bool is_underground; /* Set to true if changes has been made that make the old lighting values wrong but the lighting hasn't been actually updated. If this is false, lighting is exactly right. If this is true, lighting might be wrong or right. */ bool m_lighting_expired; // Whether day and night lighting differs bool m_day_night_differs; bool m_day_night_differs_expired; bool m_generated; /* When block is removed from active blocks, this is set to gametime. Value BLOCK_TIMESTAMP_UNDEFINED=0xffffffff means there is no timestamp. */ u32 m_timestamp; // The on-disk (or to-be on-disk) timestamp value u32 m_disk_timestamp; /* When the block is accessed, this is set to 0. Map will unload the block when this reaches a timeout. */ float m_usage_timer; /* Reference count; currently used for determining if this block is in the list of blocks to be drawn. */ int m_refcount; }; inline bool blockpos_over_limit(v3s16 p) { return (p.X < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE || p.X > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE || p.Y < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE || p.Y > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE || p.Z < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE || p.Z > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE); } /* Returns the position of the block where the node is located */ inline v3s16 getNodeBlockPos(v3s16 p) { return getContainerPos(p, MAP_BLOCKSIZE); } inline v2s16 getNodeSectorPos(v2s16 p) { return getContainerPos(p, MAP_BLOCKSIZE); } inline s16 getNodeBlockY(s16 y) { return getContainerPos(y, MAP_BLOCKSIZE); } /* Get a quick string to describe what a block actually contains */ std::string analyze_block(MapBlock *block); #endif