optimize path_get_index_by_offset

Instead of calling path_get_adjacent twice (which calls path_get
twice, i.e. 4 times overall), we call path_get directly only 2 times
with min and max indices to generate all the path we need for
calculations.
This commit is contained in:
techniX 2020-07-10 12:02:23 +02:00 committed by Gabriel Pérez-Cerezo
parent f33bb563e7
commit 74bf177cc8
1 changed files with 15 additions and 7 deletions

View File

@ -286,16 +286,26 @@ end
-- This function determines the index resulting from moving along the path by 'offset' meters
-- starting from 'index'. See also the comment on the top of the file.
function advtrains.path_get_index_by_offset(train, index, offset)
local advtrains_path_get = advtrains.path_get
-- Step 1: determine my current absolute pos on the path
local start_index_f = math.floor(index)
local _, _, frac = advtrains.path_get_adjacent(train, index)
local start_index_f = atfloor(index)
local end_index_f = start_index_f + 1
local c_idx = atfloor(index + offset)
local c_idx_f = c_idx + 1
local frac = index - start_index_f
advtrains_path_get(train, math.min(start_index_f, end_index_f, c_idx, c_idx_f))
advtrains_path_get(train, math.max(start_index_f, end_index_f, c_idx, c_idx_f))
local dist1, dist2 = train.path_dist[start_index_f], train.path_dist[start_index_f+1]
local start_dist = n_interpolate(dist1, dist2, frac)
local start_dist = dist1 + (dist2-dist1)*frac
-- Step 2: determine the total end distance and estimate the index we'd come out
local end_dist = start_dist + offset
local c_idx = math.floor(index + offset)
local c_idx = atfloor(index + offset)
-- Step 3: move forward/backward to find real index
-- We assume here that the distance between 2 path items is never smaller than 1.
@ -306,9 +316,7 @@ function advtrains.path_get_index_by_offset(train, index, offset)
-- Desired position: -------#------
-- Path items : --|--|--|--|--
-- c_idx : ^
advtrains.path_get_adjacent(train, c_idx)
while train.path_dist[c_idx] < end_dist do
c_idx = c_idx + 1
end