forked from weliveindetail/CriticalSnake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostprocess.html
376 lines (317 loc) Β· 12 KB
/
postprocess.html
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
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CriticalSnake Postprocess</title>
<style>
body {
font-size: 1rem;
}
#osm-map {
position: absolute;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div id="osm-map"></div>
<link rel="stylesheet" href="3rd-party/leaflet16/leaflet.css">
<script src="3rd-party/leaflet16/leaflet.js"></script>
<script src="3rd-party/leaflet-semicircle20/Semicircle.js"></script>
<script src="3rd-party/jquery35/jquery-3.5.1.min.js"></script>
<script src="3rd-party/geodesy11/latlon-spherical.min.js"></script>
<script src="3rd-party/lzstring14/lz-string.min.js"></script>
<script src="3rd-party/filesaver20/FileSaver.min.js"></script>
<script src="critical-snake/bikemap.js"></script>
<script src="critical-snake/critical-snake.js"></script>
<script>
function parseUrlParams(url) {
const regex = /[?&]([^=#]+)=([^&#]*)/g;
let params = {};
let match;
while(match = regex.exec(url)) {
params[match[1]] = match[2];
}
return params;
}
const params = parseUrlParams(window.location.href);
const bikeMap = createBikeMap(L);
bikeMap.browseGroup.show();
bikeMap.loadingGroup.hide();
bikeMap.playbackGroup.hide();
bikeMap.statsLabel.hide();
let playbackFrameIdx = 0;
let playbackDataset = null;
bikeMap.playbackButton.click(() => {
if (playbackDataset) {
if (isRunning())
pause();
else
resume();
}
});
bikeMap.historySlider.attr({ min: 0, max: 500 });
$(document).on("input", bikeMap.historySlider, () => {
if (playbackDataset) {
playbackFrameIdx = parseInt(bikeMap.historySlider.val());
refreshView(playbackFrameIdx);
}
});
let playbackFPS = 15;
$(document).on("change", bikeMap.fpsInput, () => {
playbackFPS = parseInt(bikeMap.fpsInput.val());
console.log("FPS changed to", playbackFPS);
});
let playbackRecording = null;
bikeMap.browseButton.change(function() {
// Validate selection and set visual indication for the loading progress.
bikeMap.browseGroup.hide();
bikeMap.loadingGroup.show();
if (this.files.length == 0)
return;
if (this.files.length > 1)
console.warn("Can only playback one file at a time:", this.files[0].name);
// Load and parse the actual file content.
const reader = new FileReader();
$(reader).on('load', (event) => {
try {
loadRecording(event.target.result);
playbackRecording = this.files[0].name;
bikeMap.playbackGroup.show();
bikeMap.statsLabel.show();
}
catch (ex) {
bikeMap.browseGroup.show();
console.error("JSON parsing for file", this.files[0].name,
"failed with", ex);
}
bikeMap.loadingGroup.hide();
});
reader.readAsText(this.files[0]);
});
bikeMap.downloadButton.click(function() {
bikeMap.playbackGroup.hide();
bikeMap.loadingGroup.show();
// Give the UI a chance to refresh and show the loading state.
setTimeout(() => {
const baseName = playbackRecording.endsWith(".json")
? playbackRecording.slice(0, -5)
: playbackRecording;
downloadReplay(baseName + ".replay", {
begin: playbackDataset.begin,
end: playbackDataset.end,
dataPoints: playbackDataset.dataPoints,
circles: playbackDataset.circles,
segments: playbackDataset.segments,
});
bikeMap.loadingGroup.hide();
bikeMap.playbackGroup.show();
}, 10);
});
// ----------------------------------------------------
function loadRecording(compressedDataSet) {
const PostProcessor = new CriticalSnake.PostProcessor();
const kilobyte = (str) => Math.round((str.length * 2) / 1024);
const decompressionBegin = Date.now();
const rawDataSet = LZString.decompressFromUTF16(compressedDataSet);
console.log("Compressed size is:", kilobyte(compressedDataSet), "KB");
console.log("Decompressed size is:", kilobyte(rawDataSet), "KB");
console.log("Decompression took:", Date.now() - decompressionBegin, "ms");
const analyzeTracksBegin = Date.now();
const [ tracks, dataPoints ] = PostProcessor.analyzeTracks(JSON.parse(rawDataSet));
console.log("Data-points:", dataPoints);
console.log("Analyzing tracks took:", Date.now() - analyzeTracksBegin, "ms");
const detectCirclesBegin = Date.now();
const circles = PostProcessor.detectCircles(dataPoints);
console.log("Circles:", circles);
console.log("Populating circles took:", Date.now() - detectCirclesBegin, "ms");
const startTime = 1598638200000; // 2020-08-28, 20:10
const associateSnakesBegin = Date.now();
const snakes = PostProcessor.associateSnakes(dataPoints, circles, { startTime: startTime });
console.log("Snakes detected by origin:", snakes);
console.log("Associating snakes took:", Date.now() - associateSnakesBegin, "ms");
const populateTrackSegmentsBegin = Date.now();
const segments = PostProcessor.populateTrackSegments(dataPoints, tracks, circles);
console.log("Segments:", segments);
console.log("Populating track segments took:", Date.now() - populateTrackSegmentsBegin, "ms");
const minute = 60 * 1000;
const timeRange = PostProcessor.getTimeRange(circles);
console.log("Data covers time range\nfrom:", timeRange.begin, "\nto:", timeRange.end);
playbackDataset = {
dataPoints: dataPoints,
circles: circles,
tracks: tracks,
segments: segments,
begin: timeRange.begin.getTime() - 5 * minute,
end: timeRange.end.getTime(),
};
playbackFrameIdx = 0;
refreshView(playbackFrameIdx);
}
function downloadReplay(filename, json) {
const kilobyte = (str) => Math.round((str.length * 2) / 1024);
const text = JSON.stringify(json);
console.log("Raw size is:", kilobyte(text), "KB");
const compressed = LZString.compressToUTF16(text);
console.log("Compressed size is:", kilobyte(compressed), "KB");
const blob = new Blob([compressed], {type: "text/plain;charset=utf-16"});
saveAs(blob, filename);
}
function refreshView(frameIdx) {
const refreshViewBegin = Date.now();
bikeMap.historySlider.val(frameIdx);
const duration = playbackDataset.end - playbackDataset.begin;
const offset = duration * (frameIdx / 500);
const timestamp = playbackDataset.begin + offset;
const bikeCount = drawTracks(playbackDataset, timestamp);
// Adds a leading "0" for single digit values.
const pad2 = (val) => (val < 10 ? "0" : "") + val;
const d = new Date(timestamp);
bikeMap.statsLabel.text(
`π
${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ` +
`π ${pad2(d.getHours())}:${pad2(d.getMinutes())} ` +
`ππ² ${bikeCount}`);
const diff = Date.now() - refreshViewBegin;
console.log("Rendering frame took:", Math.round(diff / 10) * 10, "ms");
}
// ----------------------------------------------------
let rotatingCollisionCircles = 0;
const drawFrameAction = () => {
rotatingCollisionCircles += playbackFPS;
switch (playbackFrameIdx) {
case 0:
refreshView(playbackFrameIdx);
playbackFrameIdx += 1;
break;
case 500:
refreshView(playbackFrameIdx);
bikeMap.playbackButton.val("βΆ");
playbackFrameIdx = 0;
break;
default:
refreshView(playbackFrameIdx);
playbackFrameIdx += 1;
break;
}
};
function resume() {
console.log("Rendering", playbackFPS, "FPS (", 1000 / playbackFPS, "ms per frame)");
bikeMap.playbackButton.val("||");
const nextFrameAction = () => {
drawFrameAction();
if (isRunning())
setTimeout(nextFrameAction, 1000 / playbackFPS);
};
setTimeout(nextFrameAction, 1000 / playbackFPS);
}
function pause() {
bikeMap.playbackButton.val("βΆ");
}
function isRunning() {
return bikeMap.playbackButton.val() != "βΆ";
}
// ----------------------------------------------------
let trackHeads = L.layerGroup([], { pane: "markerPane" });
let trackShadows = L.layerGroup([], { pane: "shadowPane" });
function drawTracks(dataset, stamp) {
bikeMap.removeLayer(trackHeads);
bikeMap.removeLayer(trackShadows);
if (L.Browser.mobile) {
// At this point we better avoid drawing track shadows on mobile,
// because it's too resource intense for most devices.
}
else {
trackShadows.clearLayers();
drawShadows(trackShadows, dataset.dataPoints, dataset.segments, stamp);
trackShadows.addTo(bikeMap);
}
trackHeads.clearLayers();
const visibleBikes = drawCircles(trackHeads, dataset.dataPoints,
dataset.circles, stamp);
trackHeads.addTo(bikeMap);
return visibleBikes;
}
function colors(snakeIdx) {
if (snakeIdx == null)
return "#888";
const snakeColors = [
"#c90002", // red
"#1b3d9f", // blue
"#ff0099", // pink
"#005214", // green
"#8b00ff", // violett
];
if (snakeIdx >= 0 && snakeIdx < snakeColors.length)
return snakeColors[snakeIdx];
return "#000";
}
function drawShadows(canvas, dataPoints, segments, stamp) {
const startedAlready = (seg) => seg.first_stamp <= stamp;
const didNotStartYet = (idx) => !startedAlready(dataPoints[idx]);
const findEndIndex = (seg) => {
if (seg.last_stamp <= stamp)
return -1;
return seg.dataPointIdxs.findIndex(idx => didNotStartYet(idx));
};
for (const segment of segments.filter(startedAlready)) {
// Draw non-associated track segments?
//if (segment.snakeIdxs.length == 0)
// continue;
// Draw segment entirely or only the first number of data-points.
const end = findEndIndex(segment);
const coordIdxs = end < 0 ? segment.dataPointIdxs
: segment.dataPointIdxs.slice(0, end);
for (const snakeIdx of segment.snakeIdxs) {
canvas.addLayer(
L.polyline(coordIdxs.map(idx => dataPoints[idx]), {
color: colors(snakeIdx),
opacity: 0.05
}));
}
}
}
function drawCircles(canvas, dataPoints, circles, stamp) {
const fullCircle = (c, idx) => L.circle(c, {
color: colors(idx),
fillOpacity: 0.75,
radius: 10 * Math.log2(c.dataPointIdxs.length),
stroke: false,
});
const semiCircle = (c, idx, from, to) => L.semiCircle(c, {
color: colors(idx),
fillOpacity: 0.75,
radius: 10 * Math.log2(c.dataPointIdxs.length),
startAngle: from,
stopAngle: to,
stroke: false,
});
const inTime = (c) => c.first_stamp <= stamp && c.last_stamp >= stamp;
const trackIdxs = new Set();
for (const circle of circles.filter(c => inTime(c))) {
circle.dataPointIdxs.forEach(idx => trackIdxs.add(dataPoints[idx].trackIdx));
switch (circle.snakeIdxs.length) {
case 0:
canvas.addLayer(fullCircle(circle, null));
break;
case 1:
canvas.addLayer(fullCircle(circle, circle.snakeIdxs[0]));
break;
default:
let angle = rotatingCollisionCircles;
const arcSize = 360 / circle.snakeIdxs.length;
for (const idx of circle.snakeIdxs) {
canvas.addLayer(semiCircle(circle, idx, angle, angle + arcSize));
angle += arcSize;
}
break;
}
}
return trackIdxs.size;
}
</script>
</body>
</html>