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
use serde::{Deserialize, Serialize};
use geom::{Distance, LonLat, PolyLine, Pt2D, Ring};
use map_gui::render::DrawOptions;
use map_gui::tools::{ChooseSomething, PromptInput};
use widgetry::mapspace::{ObjectID, World, WorldOutcome};
use widgetry::{
lctrl, Choice, Color, DrawBaselayer, EventCtx, GeomBatch, GfxCtx, HorizontalAlignment, Key,
Line, Outcome, Panel, SimpleState, State, Text, TextBox, VerticalAlignment, Widget,
};
use crate::app::{App, ShowEverything, Transition};
pub struct StoryMapEditor {
panel: Panel,
story: StoryMap,
world: World<MarkerID>,
dirty: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
struct MarkerID(usize);
impl ObjectID for MarkerID {}
impl StoryMapEditor {
pub fn new_state(ctx: &mut EventCtx, app: &App) -> Box<dyn State<App>> {
Self::from_story(ctx, app, StoryMap::new())
}
fn from_story(ctx: &mut EventCtx, app: &App, story: StoryMap) -> Box<dyn State<App>> {
let mut state = StoryMapEditor {
panel: Panel::empty(ctx),
story,
world: World::unbounded(),
dirty: false,
};
state.rebuild_panel(ctx);
state.rebuild_world(ctx, app);
Box::new(state)
}
fn rebuild_panel(&mut self, ctx: &mut EventCtx) {
self.panel = Panel::new_builder(Widget::col(vec![
Widget::row(vec![
Line("Story map editor").small_heading().into_widget(ctx),
Widget::vert_separator(ctx, 30.0),
ctx.style()
.btn_outline
.popup(&self.story.name)
.hotkey(lctrl(Key::L))
.build_widget(ctx, "load"),
ctx.style()
.btn_plain
.icon("system/assets/tools/save.svg")
.hotkey(lctrl(Key::S))
.disabled(!self.dirty)
.build_widget(ctx, "save"),
ctx.style().btn_close_widget(ctx),
]),
ctx.style()
.btn_plain
.icon_text("system/assets/tools/select.svg", "Draw freehand")
.hotkey(Key::F)
.build_def(ctx),
]))
.aligned(HorizontalAlignment::Center, VerticalAlignment::Top)
.build(ctx);
}
fn rebuild_world(&mut self, ctx: &mut EventCtx, app: &App) {
let mut world = World::bounded(app.primary.map.get_bounds());
for (idx, marker) in self.story.markers.iter().enumerate() {
let mut draw_normal = GeomBatch::new();
let label_center = if marker.pts.len() == 1 {
draw_normal = map_gui::tools::goal_marker(ctx, marker.pts[0], 2.0);
marker.pts[0]
} else {
let poly = Ring::must_new(marker.pts.clone()).into_polygon();
draw_normal.push(Color::RED.alpha(0.8), poly.clone());
if let Ok(o) = poly.to_outline(Distance::meters(1.0)) {
draw_normal.push(Color::RED, o);
}
poly.polylabel()
};
let mut draw_hovered = draw_normal.clone();
draw_normal.append(
Text::from(&marker.label)
.bg(Color::CYAN)
.render_autocropped(ctx)
.scale(0.5)
.centered_on(label_center),
);
let hitbox = draw_normal.unioned_polygon();
draw_hovered.append(
Text::from(&marker.label)
.bg(Color::CYAN)
.render_autocropped(ctx)
.scale(0.75)
.centered_on(label_center),
);
world
.add(MarkerID(idx))
.hitbox(hitbox)
.draw(draw_normal)
.draw_hovered(draw_hovered)
.hotkey(Key::Backspace, "delete")
.clickable()
.draggable()
.build(ctx);
}
world.initialize_hover(ctx);
world.rebuilt_during_drag(&self.world);
self.world = world;
}
}
impl State<App> for StoryMapEditor {
fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition {
match self.world.event(ctx) {
WorldOutcome::ClickedFreeSpace(pt) => {
self.story.markers.push(Marker {
pts: vec![pt],
label: String::new(),
});
self.dirty = true;
self.rebuild_panel(ctx);
self.rebuild_world(ctx, app);
return Transition::Push(EditingMarker::new_state(
ctx,
self.story.markers.len() - 1,
"new marker",
));
}
WorldOutcome::Dragging {
obj: MarkerID(idx),
dx,
dy,
..
} => {
for pt in &mut self.story.markers[idx].pts {
*pt = pt.offset(dx, dy);
}
self.dirty = true;
self.rebuild_panel(ctx);
self.rebuild_world(ctx, app);
}
WorldOutcome::Keypress("delete", MarkerID(idx)) => {
self.story.markers.remove(idx);
self.dirty = true;
self.rebuild_panel(ctx);
self.rebuild_world(ctx, app);
}
WorldOutcome::ClickedObject(MarkerID(idx)) => {
return Transition::Push(EditingMarker::new_state(
ctx,
idx,
&self.story.markers[idx].label,
));
}
_ => {}
}
if let Outcome::Clicked(x) = self.panel.event(ctx) {
match x.as_ref() {
"close" => {
return Transition::Pop;
}
"save" => {
if self.story.name == "new story" {
return Transition::Push(PromptInput::new_state(
ctx,
"Name this story map",
String::new(),
Box::new(|name, _, _| {
Transition::Multi(vec![
Transition::Pop,
Transition::ModifyState(Box::new(move |state, ctx, app| {
let editor =
state.downcast_mut::<StoryMapEditor>().unwrap();
editor.story.name = name;
editor.story.save(app);
editor.dirty = false;
editor.rebuild_panel(ctx);
})),
])
}),
));
} else {
self.story.save(app);
self.dirty = false;
self.rebuild_panel(ctx);
}
}
"load" => {
let mut choices = Vec::new();
for (name, story) in
abstio::load_all_objects::<RecordedStoryMap>(abstio::path_player("stories"))
{
if story.name == self.story.name {
continue;
}
if let Some(s) = StoryMap::load(app, story) {
choices.push(Choice::new(name, s));
}
}
choices.push(Choice::new(
"new story",
StoryMap {
name: "new story".to_string(),
markers: Vec::new(),
},
));
return Transition::Push(ChooseSomething::new_state(
ctx,
"Load story",
choices,
Box::new(|story, ctx, app| {
Transition::Multi(vec![
Transition::Pop,
Transition::Replace(StoryMapEditor::from_story(ctx, app, story)),
])
}),
));
}
"Draw freehand" => {
return Transition::Push(Box::new(DrawFreehand {
lasso: Lasso::new(),
new_idx: self.story.markers.len(),
}));
}
_ => unreachable!(),
}
}
Transition::Keep
}
fn draw_baselayer(&self) -> DrawBaselayer {
DrawBaselayer::Custom
}
fn draw(&self, g: &mut GfxCtx, app: &App) {
let mut opts = DrawOptions::new();
opts.label_buildings = true;
app.draw(g, opts, &ShowEverything::new());
self.panel.draw(g);
self.world.draw(g);
}
}
#[derive(Clone, Serialize, Deserialize)]
struct RecordedStoryMap {
name: String,
markers: Vec<(Vec<LonLat>, String)>,
}
struct StoryMap {
name: String,
markers: Vec<Marker>,
}
struct Marker {
pts: Vec<Pt2D>,
label: String,
}
impl StoryMap {
fn new() -> StoryMap {
StoryMap {
name: "new story".to_string(),
markers: Vec::new(),
}
}
fn load(app: &App, story: RecordedStoryMap) -> Option<StoryMap> {
let mut markers = Vec::new();
for (gps_pts, label) in story.markers {
markers.push(Marker {
pts: app.primary.map.get_gps_bounds().try_convert(&gps_pts)?,
label,
});
}
Some(StoryMap {
name: story.name,
markers,
})
}
fn save(&self, app: &App) {
let story = RecordedStoryMap {
name: self.name.clone(),
markers: self
.markers
.iter()
.map(|m| {
(
app.primary.map.get_gps_bounds().convert_back(&m.pts),
m.label.clone(),
)
})
.collect(),
};
abstio::write_json(
abstio::path_player(format!("stories/{}.json", story.name)),
&story,
);
}
}
struct EditingMarker {
idx: usize,
}
impl EditingMarker {
fn new_state(ctx: &mut EventCtx, idx: usize, label: &str) -> Box<dyn State<App>> {
let panel = Panel::new_builder(Widget::col(vec![
Widget::row(vec![
Line("Editing marker").small_heading().into_widget(ctx),
ctx.style().btn_close_widget(ctx),
]),
ctx.style().btn_outline.text("delete").build_def(ctx),
TextBox::default_widget(ctx, "label", label.to_string()),
ctx.style()
.btn_outline
.text("confirm")
.hotkey(Key::Enter)
.build_def(ctx),
]))
.build(ctx);
<dyn SimpleState<_>>::new_state(panel, Box::new(EditingMarker { idx }))
}
}
impl SimpleState<App> for EditingMarker {
fn on_click(&mut self, _: &mut EventCtx, _: &mut App, x: &str, panel: &Panel) -> Transition {
match x {
"close" => {
return Transition::Pop;
}
"confirm" => {
let idx = self.idx;
let label = panel.text_box("label");
return Transition::Multi(vec![
Transition::Pop,
Transition::ModifyState(Box::new(move |state, ctx, app| {
let editor = state.downcast_mut::<StoryMapEditor>().unwrap();
editor.story.markers[idx].label = label;
editor.dirty = true;
editor.rebuild_panel(ctx);
editor.rebuild_world(ctx, app);
})),
]);
}
"delete" => {
let idx = self.idx;
return Transition::Multi(vec![
Transition::Pop,
Transition::ModifyState(Box::new(move |state, ctx, app| {
let editor = state.downcast_mut::<StoryMapEditor>().unwrap();
editor.story.markers.remove(idx);
editor.dirty = true;
editor.rebuild_panel(ctx);
editor.rebuild_world(ctx, app);
})),
]);
}
_ => unreachable!(),
}
}
fn draw_baselayer(&self) -> DrawBaselayer {
DrawBaselayer::PreviousState
}
}
struct DrawFreehand {
lasso: Lasso,
new_idx: usize,
}
impl State<App> for DrawFreehand {
fn event(&mut self, ctx: &mut EventCtx, _: &mut App) -> Transition {
if let Some(result) = self.lasso.event(ctx) {
let idx = self.new_idx;
return Transition::Multi(vec![
Transition::Pop,
Transition::ModifyState(Box::new(move |state, ctx, app| {
let editor = state.downcast_mut::<StoryMapEditor>().unwrap();
editor.story.markers.push(Marker {
pts: result.into_points(),
label: String::new(),
});
editor.dirty = true;
editor.rebuild_panel(ctx);
editor.rebuild_world(ctx, app);
})),
Transition::Push(EditingMarker::new_state(ctx, idx, "new marker")),
]);
}
Transition::Keep
}
fn draw_baselayer(&self) -> DrawBaselayer {
DrawBaselayer::PreviousState
}
fn draw(&self, g: &mut GfxCtx, _: &App) {
self.lasso.draw(g);
}
}
struct Lasso {
pl: Option<PolyLine>,
}
impl Lasso {
fn new() -> Lasso {
Lasso { pl: None }
}
fn event(&mut self, ctx: &mut EventCtx) -> Option<Ring> {
if self.pl.is_none() {
if let Some(pt) = ctx.canvas.get_cursor_in_map_space() {
if ctx.input.left_mouse_button_pressed() {
self.pl = Some(PolyLine::must_new(vec![pt, pt.offset(0.1, 0.0)]));
}
}
return None;
}
if ctx.input.left_mouse_button_released() {
return Some(simplify(self.pl.take().unwrap().into_points()));
}
let current_pl = self.pl.as_ref().unwrap();
if ctx.redo_mouseover() {
if let Some(pt) = ctx.canvas.get_cursor_in_map_space() {
if let Ok(pl) = PolyLine::new(vec![current_pl.last_pt(), pt]) {
if let Some((hit, _)) = current_pl.intersection(&pl) {
if let Some(slice) = current_pl.get_slice_starting_at(hit) {
return Some(simplify(slice.into_points()));
}
}
let mut pts = current_pl.points().clone();
pts.push(pt);
if let Ok(new) = PolyLine::new(pts) {
self.pl = Some(new);
}
}
}
}
None
}
fn draw(&self, g: &mut GfxCtx) {
if let Some(ref pl) = self.pl {
g.draw_polygon(
Color::RED.alpha(0.8),
pl.make_polygons(Distance::meters(5.0) / g.canvas.cam_zoom),
);
}
}
}
fn simplify(mut raw: Vec<Pt2D>) -> Ring {
if false {
let pts = raw
.into_iter()
.map(|pt| lttb::DataPoint::new(pt.x(), pt.y()))
.collect();
let mut downsampled = Vec::new();
for pt in lttb::lttb(pts, 50) {
downsampled.push(Pt2D::new(pt.x, pt.y));
}
downsampled.push(downsampled[0]);
Ring::must_new(downsampled)
} else {
raw.push(raw[0]);
Ring::must_new(raw)
}
}