bevy_flowfield_tiles_plugin 0.14.0

An implementation of FlowField (vector field) pathfinding as a plugin to the Bevy game engine
Documentation
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
//! A Portal indicates a pathable area from one Sector to another. Each side of a Sector can
//! have multiple portals if a side is 'split' due to an impassable value in the
//! [CostField]. A side that sits along the edge of the map
//! itself cannot have a portal. For example here is a representation of a
//! [CostField] in the top-left corner of a map with the portal [FieldCell]
//! positions labeled with a `P`:
//!
//! ```text
//!  ___________________________________________________________
//! |     |     |     |     |     |     |     |     |     |     |
//! |  1  |  1  |  1  |  1  |  1  |  1  |  1  |  1  |  1  |  1  P
//! |_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|
//! |     |     |     |     |     |     |     |     |     |     |
//! |  1  |  1  |  1  |  1  |  1  | 255 | 255 | 255 | 255 | 255 |
//! |_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|
//! |     |     |     |     |     |     |     |     |     |     |
//! |  1  |  1  |  1  |  1  |  1  |  1  |  1  | 255 | 255 |  1  |
//! |_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|
//! |     |     |     |     |     |     |     |     |     |     |
//! |  1  |  1  |  1  |  1  |  1  |  1  |  1  |  1  |  1  |  1  |
//! |_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|
//! |     |     |     |     |     |     |     |     |     |     |
//! |  1  |  1  |  1  |  1  |  1  |  1  |  1  |  1  |  1  |  1  |
//! |_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|
//! |     |     |     |     |     |     |     |     |     |     |
//! |  1  |  1  |  1  |  1  |  1  |  1  |  1  |  1  |  1  |  1  |
//! |_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|
//! |     |     |     |     |     |     |     |     |     |     |
//! |  1  |  1  |  1  |  1  | 255 |  1  |  1  |  1  |  1  |  1  P
//! |_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|
//! |     |     |     |     |     |     |     |     |     |     |
//! |  1  |  1  |  1  |  1  | 255 |  1  |  1  |  1  |  1  |  1  |
//! |_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|
//! |     |     |     |     |     |     |     |     |     |     |
//! |  1  |  1  |  1  |  1  | 255 | 255 |  1  |  1  |  1  |  1  |
//! |_____|_____|_____|_____|_____|_____|_____|_____|_____|_____|
//! |     |     |     |     |     |     |     |     |     |     |
//! |  1  |  1  |  1  |  1  | 255 | 255 | 255 |  1  |  1  |  1  |
//! |_____|__P__|_____|_____|_____|_____|_____|_____|__P__|_____|
//! ```
//!
//! When an agent needs to path somewhere it is initially given a path based on moving from one portal
//! to another portal/end sector. This ensures responsiveness so when a player issues a movement order
//! the agent can immediately starts pathing. In the background the other components of the Flowfields can
//! calcualte a perfect path which can then supersede using portals to path when it's ready

use bevy::reflect::Reflect;

use crate::prelude::*;

/// Portals contains a list for each side of a Sector of which [FieldCell]s have a Portal
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[derive(Default, Debug, Clone, Reflect)]
pub struct Portals {
	/// Portals along the northern side of a sector
	north: Vec<FieldCell>,
	/// Portals along the eastern side of a sector
	east: Vec<FieldCell>,
	/// Portals along the southern side of a sector
	south: Vec<FieldCell>,
	/// Portals along the western side of a sector
	west: Vec<FieldCell>,
}

impl Portals {
	/// Get a reference the Portals along a partiuclar side of a sector
	#[cfg(not(tarpaulin_include))]
	pub fn get(&self, ordinal: &Ordinal) -> &Vec<FieldCell> {
		match ordinal {
			Ordinal::North => &self.north,
			Ordinal::East => &self.east,
			Ordinal::South => &self.south,
			Ordinal::West => &self.west,
			_ => panic!("Ordinal {:?} is invalid when looking up portals", ordinal),
		}
	}
	/// Get a mutable reference to the array list of [FieldCell]
	#[cfg(not(tarpaulin_include))]
	pub fn get_mut(&mut self, ordinal: &Ordinal) -> &mut Vec<FieldCell> {
		match ordinal {
			Ordinal::North => &mut self.north,
			Ordinal::East => &mut self.east,
			Ordinal::South => &mut self.south,
			Ordinal::West => &mut self.west,
			_ => panic!("Ordinal {:?} is invalid when looking up portals", ordinal),
		}
	}
	/// Remove the [FieldCell] of Portals for the `ordinal` side of a sector
	fn clear(&mut self, ordinal: Ordinal) {
		match ordinal {
			Ordinal::North => self.north.clear(),
			Ordinal::East => self.east.clear(),
			Ordinal::South => self.south.clear(),
			Ordinal::West => self.west.clear(),
			_ => panic!(
				"Ordinal {:?} is invalid when clearing a portal side",
				ordinal
			),
		}
	}
	/// Remove all [FieldCell] elements from the lists of [FieldCell]
	fn clear_all(&mut self) {
		let ords = [Ordinal::North, Ordinal::South, Ordinal::West, Ordinal::East];
		for ord in ords {
			self.clear(ord);
		}
	}
	/// When a sectors [CostField] is updated the portal [FieldCell]s of the sector and
	/// its neighbours may no longer be valid so they should be recalculated.
	///
	/// Special care must be taken when a neighbouring [CostField] has
	/// impassable values of `255` along the boundary edge as these will create multiple [Portals]
	/// within the neighbour. When building [Portals] we inspect the sector neighbours to ensure that
	/// the [Portals] between neighbours are positioned equally and each sector has the same number of
	/// them alonog the boundary.
	///
	/// In this example the left sector has two cost fields denoted `x` meaning impassable 255. When
	/// calculating the [Portals] of the middle sector rather than creating one
	/// central portal [FieldCell]
	/// along that boundary we instead need to create two portal [FieldCell]s to match the layout of the
	/// adjacent sector
	/// ```text
	/// _______________________________
	/// |         P         |         |
	/// |        x|         |         |
	/// |        x|         |         |
	/// |         P         |         |
	/// |_________|_________|_________|
	/// ```
	pub fn recalculate_portals(
		&mut self,
		sector_cost_fields: &SectorCostFields,
		sector_id: &SectorID,
		map_dimensions: &MapDimensions,
	) {
		self.clear_all();
		// there are up to 4 lists of [FieldCell]s for a given sector, in case this sector being
		// updated is on a boundary we need to determine the valid elements of [Portals] that
		// should be updated
		let valid_ordinals_for_this_sector: Vec<(Ordinal, SectorID)> =
			map_dimensions.get_ordinal_and_ids_of_neighbouring_sectors(sector_id);
		// moving in a clockwise fashion around the valid ordinals of the boundary sector movement
		// we inspect the [CostField] values to calculate the portals along each valid sector side
		let cost_field = sector_cost_fields
			.get_scaled()
			.get(sector_id)
			.expect("Invalid sector id");
		for (ord, adjoining_sector_id) in valid_ordinals_for_this_sector.iter() {
			match ord {
				Ordinal::North => {
					let portal_nodes = self.get_mut(ord);
					let column_range = 0..FIELD_RESOLUTION;
					let fixed_row = 0;
					let adjoining_cost_field = sector_cost_fields
						.get_scaled()
						.get(adjoining_sector_id)
						.unwrap();
					// walk along the side of the field
					let mut neighbouring_pathable = Vec::new();
					for i in column_range {
						let field_cost =
							cost_field.get_field_cell_value(FieldCell::new(i, fixed_row));
						let adjacent_field_cost = adjoining_cost_field
							.get_field_cell_value(FieldCell::new(i, FIELD_RESOLUTION - 1));
						if field_cost != 255 && adjacent_field_cost != 255 {
							// a pathable point along the edge so we record it to be
							// published later as a FieldCell
							neighbouring_pathable.push((i, fixed_row));
						} else {
							// if a length along the edge was previously calculated then publish
							// it as FieldCell
							if !neighbouring_pathable.is_empty() {
								// find the most centre like cell for this portal window
								let mut column_index_sum = 0;
								for (m, _) in neighbouring_pathable.iter() {
									column_index_sum += m;
								}
								let portal_midpoint_column =
									column_index_sum / neighbouring_pathable.len();
								portal_nodes
									.push(FieldCell::new(portal_midpoint_column, fixed_row));
								// clear the recording list so any other portals along the side can be built
								neighbouring_pathable.clear();
							}
						}
					}
					// if the side doesn't end with a cost field of 255 then there's one more portal window that needs to be published after iterating over the side
					if !neighbouring_pathable.is_empty() {
						// find the most centre like cell for this portal window
						let mut column_index_sum = 0;
						for (i, _) in neighbouring_pathable.iter() {
							column_index_sum += i;
						}
						let portal_midpoint_column = column_index_sum / neighbouring_pathable.len();
						portal_nodes.push(FieldCell::new(portal_midpoint_column, fixed_row));
						// clear the recording list so any other portals along the side can be built
						neighbouring_pathable.clear();
					}
				}
				Ordinal::East => {
					let portal_nodes = self.get_mut(ord);
					let fixed_column = FIELD_RESOLUTION - 1;
					let row_range = 0..FIELD_RESOLUTION;
					let adjoining_cost_field = sector_cost_fields
						.get_scaled()
						.get(adjoining_sector_id)
						.unwrap();
					// walk along the side of the field
					let mut neighbouring_pathable = Vec::new();
					for j in row_range {
						let field_cost =
							cost_field.get_field_cell_value(FieldCell::new(fixed_column, j));
						let adjacent_field_cost =
							adjoining_cost_field.get_field_cell_value(FieldCell::new(0, j));
						if field_cost != 255 && adjacent_field_cost != 255 {
							// a pathable point along the edge so we record it to be
							// published later as a FieldCell
							neighbouring_pathable.push((fixed_column, j));
						} else {
							// if a length along the edge was previously calculated then publish
							// it as FieldCell
							if !neighbouring_pathable.is_empty() {
								// find the most centre like cell for this portal window
								let mut row_index_sum = 0;
								for (_, n) in neighbouring_pathable.iter() {
									row_index_sum += n;
								}
								let portal_midpoint_row =
									row_index_sum / neighbouring_pathable.len();
								portal_nodes
									.push(FieldCell::new(fixed_column, portal_midpoint_row));
								// clear the recording list so any other portals along the side can be built
								neighbouring_pathable.clear();
							}
						}
					}
					// if the side doesn't end with a cost field of 255 then there's one more portal window that needs to be published after iterating over the side
					if !neighbouring_pathable.is_empty() {
						// find the most centre like cell for this portal window
						let mut row_index_sum = 0;
						for (_, n) in neighbouring_pathable.iter() {
							row_index_sum += n;
						}
						let portal_midpoint_row = row_index_sum / neighbouring_pathable.len();
						portal_nodes.push(FieldCell::new(fixed_column, portal_midpoint_row));
						// clear the recording list so any other portals along the side can be built
						neighbouring_pathable.clear();
					}
				}
				Ordinal::South => {
					let portal_nodes = self.get_mut(ord);
					let column_range = 0..FIELD_RESOLUTION;
					let fixed_row = FIELD_RESOLUTION - 1;
					let adjoining_cost_field = sector_cost_fields
						.get_scaled()
						.get(adjoining_sector_id)
						.unwrap();
					// walk along the side of the field
					let mut neighbouring_pathable = Vec::new();
					for i in column_range {
						let field_cost =
							cost_field.get_field_cell_value(FieldCell::new(i, fixed_row));
						let adjacent_field_cost =
							adjoining_cost_field.get_field_cell_value(FieldCell::new(i, 0));
						if field_cost != 255 && adjacent_field_cost != 255 {
							// a pathable point along the edge so we record it to be
							// published later as a FieldCell
							neighbouring_pathable.push((i, fixed_row));
						} else {
							// if a length along the edge was previously calculated then publish
							// it as FieldCell
							if !neighbouring_pathable.is_empty() {
								// find the most centre like cell for this portal window
								let mut column_index_sum = 0;
								for (m, _) in neighbouring_pathable.iter() {
									column_index_sum += m;
								}
								let portal_midpoint_column =
									column_index_sum / neighbouring_pathable.len();
								portal_nodes
									.push(FieldCell::new(portal_midpoint_column, fixed_row));
								// clear the recording list so any other portals along the side can be built
								neighbouring_pathable.clear();
							}
						}
					}
					// if the side doesn't end with a cost field of 255 then there's one more portal window that needs to be published after iterating over the side
					if !neighbouring_pathable.is_empty() {
						// find the most centre like cell for this portal window
						let mut column_index_sum = 0;
						for (i, _) in neighbouring_pathable.iter() {
							column_index_sum += i;
						}
						let portal_midpoint_column = column_index_sum / neighbouring_pathable.len();
						portal_nodes.push(FieldCell::new(portal_midpoint_column, fixed_row));
						// clear the recording list so any other portals along the side can be built
						neighbouring_pathable.clear();
					}
				}
				Ordinal::West => {
					let portal_nodes = self.get_mut(ord);
					let fixed_column = 0;
					let row_range = 0..FIELD_RESOLUTION;
					let adjoining_cost_field = sector_cost_fields
						.get_scaled()
						.get(adjoining_sector_id)
						.unwrap();
					// walk along the side of the field
					let mut neighbouring_pathable = Vec::new();
					for j in row_range {
						let field_cost =
							cost_field.get_field_cell_value(FieldCell::new(fixed_column, j));
						let adjacent_field_cost = adjoining_cost_field
							.get_field_cell_value(FieldCell::new(FIELD_RESOLUTION - 1, j));
						if field_cost != 255 && adjacent_field_cost != 255 {
							// a pathable point along the edge so we record it to be
							// published later as a FieldCell
							neighbouring_pathable.push((fixed_column, j));
						} else {
							// if a length along the edge was previously calculated then publish
							// it as FieldCell
							if !neighbouring_pathable.is_empty() {
								// find the most centre like cell for this portal window
								let mut row_index_sum = 0;
								for (_, n) in neighbouring_pathable.iter() {
									row_index_sum += n;
								}
								let portal_midpoint_row =
									row_index_sum / neighbouring_pathable.len();
								portal_nodes
									.push(FieldCell::new(fixed_column, portal_midpoint_row));
								// clear the recording list so any other portals along the side can be built
								neighbouring_pathable.clear();
							}
						}
					}
					// if the side doesn't end with a cost field of 255 then there's one more portal window that needs to be published after iterating over the side
					if !neighbouring_pathable.is_empty() {
						// find the most centre like cell for this portal window
						let mut row_index_sum = 0;
						for (_, n) in neighbouring_pathable.iter() {
							row_index_sum += n;
						}
						let portal_midpoint_row = row_index_sum / neighbouring_pathable.len();
						portal_nodes.push(FieldCell::new(fixed_column, portal_midpoint_row));
						// clear the recording list so any other portals along the side can be built
						neighbouring_pathable.clear();
					}
				}
				_ => panic!(
					"Portal ordinals can only be North, East, South or West. Asked for {:?}",
					ord
				),
			};
		}
	}
	/// A [FieldCell] represents the midpoint of a segment along a boundary, for smooth pathfinding any field cell along the segemnt should be a viable goal node when calculating an [IntegrationField]. This takes inspects the `portal_id` within the given `sector_id` and build a list of field cells which comprise the true dimension of the portal
	pub fn expand_portal_into_goals(
		&self,
		sector_cost_fields: &SectorCostFields,
		sector_id: &SectorID,
		portal_id: &FieldCell,
		neighbour_sector_id: &SectorID,
		map_dimensions: &MapDimensions,
	) -> Vec<FieldCell> {
		// find the bounudary the portal sit along
		let mut boundary_ordinals = portal_id.get_boundary_ordinal_from_field_cell();
		// if it's in a corner then it could apply to two boundaries, narrow it down so we know which boundary to walk
		if boundary_ordinals.len() > 1 {
			let valid_ordinals_for_this_sector: Vec<(Ordinal, SectorID)> =
				map_dimensions.get_ordinal_and_ids_of_neighbouring_sectors(sector_id);
			'outer: for (ordinal, id) in valid_ordinals_for_this_sector.iter() {
				if id == neighbour_sector_id {
					boundary_ordinals.retain(|o| o == ordinal);
					break 'outer;
				}
			}
			if boundary_ordinals.len() > 1 {
				panic!("Sector {:?} does not have a neighbour at {:?} while inspecting portal {:?}. This suggests that a portal exists on a sector boundary where it shouldn't, i.e this sector is along an edge of the world and the portal is on a boundary leading to nowhere", sector_id, neighbour_sector_id, portal_id);
			}
		}
		let boundary_ordinal = boundary_ordinals.first().unwrap();
		let mut goals: Vec<FieldCell> = Vec::new();
		// the portal itself is a goal
		goals.push(*portal_id);
		// from the portal walk either left/right or up/down depending on the ordinal
		// until an impassable cost field value is found
		let this_cost_field = sector_cost_fields.get_scaled().get(sector_id).unwrap();
		let adjoining_cost_field = sector_cost_fields
			.get_scaled()
			.get(neighbour_sector_id)
			.unwrap();
		match boundary_ordinal {
			Ordinal::North => {
				// walk left from the portal
				let mut step = 1;
				'left: while portal_id.get_column().checked_sub(step).is_some() {
					let left = FieldCell::new(portal_id.get_column() - step, portal_id.get_row());
					// check whether cell or adjoining cell is impassable
					let left_cost = this_cost_field
						.get_field_cell_value(FieldCell::new(left.get_column(), left.get_row()));
					let neighbour_cost = adjoining_cost_field.get_field_cell_value(FieldCell::new(
						left.get_column(),
						FIELD_RESOLUTION - 1,
					));
					if left_cost != 255 && neighbour_cost != 255 {
						goals.push(left);
						step += 1;
					} else {
						// portal length cannot go any further
						break 'left;
					}
				}
				// walk right from the portal
				let mut step = 1;
				'right: while portal_id.get_column() + step < FIELD_RESOLUTION {
					let right = FieldCell::new(portal_id.get_column() + step, portal_id.get_row());
					// check whether cell or adjoining cell is impassable
					let right_cost = this_cost_field.get_field_cell_value(right);
					let neighbour_cost = adjoining_cost_field.get_field_cell_value(FieldCell::new(
						right.get_column(),
						FIELD_RESOLUTION - 1,
					));
					if right_cost != 255 && neighbour_cost != 255 {
						goals.push(right);
						step += 1;
					} else {
						// portal length cannot go any further
						break 'right;
					}
				}
			}
			Ordinal::East => {
				// walk up from the portal
				let mut step = 1;
				'up: while portal_id.get_row().checked_sub(step).is_some() {
					let up = FieldCell::new(portal_id.get_column(), portal_id.get_row() - step);
					// check whether cell or adjoining cell is impassable
					let up_cost = this_cost_field.get_field_cell_value(up);
					let neighbour_cost =
						adjoining_cost_field.get_field_cell_value(FieldCell::new(0, up.get_row()));
					if up_cost != 255 && neighbour_cost != 255 {
						goals.push(up);
						step += 1;
					} else {
						// portal length cannot go any further
						break 'up;
					}
				}
				// walk down from the portal
				let mut step = 1;
				'down: while portal_id.get_row() + step < FIELD_RESOLUTION {
					let down = FieldCell::new(portal_id.get_column(), portal_id.get_row() + step);
					// check whether cell or adjoining cell is impassable
					let right_cost = this_cost_field.get_field_cell_value(down);
					let neighbour_cost = adjoining_cost_field
						.get_field_cell_value(FieldCell::new(0, down.get_row()));
					if right_cost != 255 && neighbour_cost != 255 {
						goals.push(down);
						step += 1;
					} else {
						// portal length cannot go any further
						break 'down;
					}
				}
			}
			Ordinal::South => {
				// walk left from the portal
				let mut step = 1;
				'left: while portal_id.get_column().checked_sub(step).is_some() {
					let left = FieldCell::new(portal_id.get_column() - step, portal_id.get_row());
					// check whether cell or adjoining cell is impassable
					let left_cost = this_cost_field.get_field_cell_value(left);
					let neighbour_cost = adjoining_cost_field
						.get_field_cell_value(FieldCell::new(left.get_column(), 0));
					if left_cost != 255 && neighbour_cost != 255 {
						goals.push(left);
						step += 1;
					} else {
						// portal length cannot go any further
						break 'left;
					}
				}
				// walk right from the portal
				let mut step = 1;
				'right: while portal_id.get_column() + step < FIELD_RESOLUTION {
					let right = FieldCell::new(portal_id.get_column() + step, portal_id.get_row());
					// check whether cell or adjoining cell is impassable
					let right_cost = this_cost_field.get_field_cell_value(right);
					let neighbour_cost = adjoining_cost_field
						.get_field_cell_value(FieldCell::new(right.get_column(), 0));
					if right_cost != 255 && neighbour_cost != 255 {
						goals.push(right);
						step += 1;
					} else {
						// portal length cannot go any further
						break 'right;
					}
				}
			}
			Ordinal::West => {
				// walk up from the portal
				let mut step = 1;
				'up: while portal_id.get_row().checked_sub(step).is_some() {
					let up = FieldCell::new(portal_id.get_column(), portal_id.get_row() - step);
					// check whether cell or adjoining cell is impassable
					let up_cost = this_cost_field.get_field_cell_value(up);
					let neighbour_cost = adjoining_cost_field
						.get_field_cell_value(FieldCell::new(FIELD_RESOLUTION - 1, up.get_row()));
					if up_cost != 255 && neighbour_cost != 255 {
						goals.push(up);
						step += 1;
					} else {
						// portal length cannot go any further
						break 'up;
					}
				}
				// walk down from the portal
				let mut step = 1;
				'down: while portal_id.get_row() + step < FIELD_RESOLUTION {
					let down = FieldCell::new(portal_id.get_column(), portal_id.get_row() + step);
					// check whether cell or adjoining cell is impassable
					let right_cost = this_cost_field.get_field_cell_value(down);
					let neighbour_cost = adjoining_cost_field
						.get_field_cell_value(FieldCell::new(FIELD_RESOLUTION - 1, down.get_row()));
					if right_cost != 255 && neighbour_cost != 255 {
						goals.push(down);
						step += 1;
					} else {
						// portal length cannot go any further
						break 'down;
					}
				}
			}
			_ => panic!(
				"Invalid Ordinal {:?} for boundary walking",
				boundary_ordinal
			),
		}
		goals
	}
}

#[cfg(test)]
mod tests {
	use crate::flowfields::sectors::sector_portals::SectorPortals;

	use super::*;
	#[test]
	fn portals_top_left_sector() {
		let map_dimensions = MapDimensions::new(30, 30, 10, 0.5);
		let mut sector_cost_fields = SectorCostFields::new(&map_dimensions);
		let sector_id = SectorID::new(0, 0);
		// switch some fields to impassable
		sector_cost_fields.set_field_cell_value(
			sector_id,
			255,
			FieldCell::new(9, 5),
			&map_dimensions,
		);
		sector_cost_fields.set_field_cell_value(
			sector_id,
			255,
			FieldCell::new(0, 9),
			&map_dimensions,
		);
		let mut portals = Portals::default();
		portals.recalculate_portals(&sector_cost_fields, &sector_id, &map_dimensions);
		let northern_side_portal_count = 0;
		let eastern_side_portal_count = 2;
		let southern_side_portal_count = 1;
		let western_side_portal_count = 0;
		assert_eq!(northern_side_portal_count, portals.north.len());
		assert_eq!(eastern_side_portal_count, portals.east.len());
		assert_eq!(southern_side_portal_count, portals.south.len());
		assert_eq!(western_side_portal_count, portals.west.len());
	}
	#[test]
	fn portals_top_middle_sector() {
		let map_dimensions = MapDimensions::new(30, 30, 10, 0.5);
		let mut sector_cost_fields = SectorCostFields::new(&map_dimensions);
		let sector_id = SectorID::new(1, 0);
		// switch some fields to impassable
		sector_cost_fields.set_field_cell_value(
			sector_id,
			255,
			FieldCell::new(9, 5),
			&map_dimensions,
		);
		sector_cost_fields.set_field_cell_value(
			sector_id,
			255,
			FieldCell::new(0, 9),
			&map_dimensions,
		);
		let mut portals = Portals::default();
		portals.recalculate_portals(&sector_cost_fields, &sector_id, &map_dimensions);
		let northern_side_portal_count = 0;
		let eastern_side_portal_count = 2;
		let southern_side_portal_count = 1;
		let western_side_portal_count = 1;
		assert_eq!(northern_side_portal_count, portals.north.len());
		assert_eq!(eastern_side_portal_count, portals.east.len());
		assert_eq!(southern_side_portal_count, portals.south.len());
		assert_eq!(western_side_portal_count, portals.west.len());
	}
	#[test]
	fn portals_centre_sector() {
		let map_dimensions = MapDimensions::new(30, 30, 10, 0.5);
		let mut sector_cost_fields = SectorCostFields::new(&map_dimensions);
		let sector_id = SectorID::new(1, 1);
		// switch some fields to impassable
		sector_cost_fields.set_field_cell_value(
			sector_id,
			255,
			FieldCell::new(9, 5),
			&map_dimensions,
		);
		sector_cost_fields.set_field_cell_value(
			sector_id,
			255,
			FieldCell::new(0, 9),
			&map_dimensions,
		);
		let mut portals = Portals::default();
		portals.recalculate_portals(&sector_cost_fields, &sector_id, &map_dimensions);
		let northern_side_portal_count = 1;
		let eastern_side_portal_count = 2;
		let southern_side_portal_count = 1;
		let western_side_portal_count = 1;
		assert_eq!(northern_side_portal_count, portals.north.len());
		assert_eq!(eastern_side_portal_count, portals.east.len());
		assert_eq!(southern_side_portal_count, portals.south.len());
		assert_eq!(western_side_portal_count, portals.west.len());
	}
	#[test]
	fn portals_bottom_middle_sector() {
		let map_dimensions = MapDimensions::new(30, 30, 10, 0.5);
		let mut sector_cost_fields = SectorCostFields::new(&map_dimensions);
		let sector_id = SectorID::new(1, 2);
		// switch some fields to impassable
		sector_cost_fields.set_field_cell_value(
			sector_id,
			255,
			FieldCell::new(4, 0),
			&map_dimensions,
		);
		sector_cost_fields.set_field_cell_value(
			sector_id,
			255,
			FieldCell::new(6, 0),
			&map_dimensions,
		);
		sector_cost_fields.set_field_cell_value(
			sector_id,
			255,
			FieldCell::new(9, 5),
			&map_dimensions,
		);
		sector_cost_fields.set_field_cell_value(
			sector_id,
			255,
			FieldCell::new(0, 9),
			&map_dimensions,
		);
		let mut portals = Portals::default();
		portals.recalculate_portals(&sector_cost_fields, &sector_id, &map_dimensions);
		let northern_side_portal_count = 3;
		let eastern_side_portal_count = 2;
		let southern_side_portal_count = 0;
		let western_side_portal_count = 1;
		assert_eq!(northern_side_portal_count, portals.north.len());
		assert_eq!(eastern_side_portal_count, portals.east.len());
		assert_eq!(southern_side_portal_count, portals.south.len());
		assert_eq!(western_side_portal_count, portals.west.len());
	}
	#[test]
	fn verify_rebuilding() {
		let map_dimensions = MapDimensions::new(30, 30, 10, 0.5);
		let mut sector_cost_fields = SectorCostFields::new(&map_dimensions);
		let mut sector_portals = SectorPortals::new(
			map_dimensions.get_length(),
			map_dimensions.get_depth(),
			map_dimensions.get_sector_resolution(),
		);
		// build portals
		for (id, portals) in sector_portals.get_mut().iter_mut() {
			portals.recalculate_portals(&sector_cost_fields, id, &map_dimensions)
		}

		// the current portals
		// _______________________________
		// |         |         |         |
		// |         |         |         |
		// |         P         P         |
		// |         |         |         |
		// |____P____|____P____|____P____|
		// |         |         |         |
		// |         |         |         |
		// |         P         P         |
		// |         |         |         |
		// |____P____|____P____|____P____|
		// |         |         |         |
		// |         |         |         |
		// |         P         P         |
		// |         |         |         |
		// |_________|_________|_________|
		let pre_first = sector_portals
			.get_mut()
			.get_mut(&SectorID::new(0, 0))
			.unwrap()
			.clone();
		let pre_second = sector_portals
			.get_mut()
			.get_mut(&SectorID::new(0, 1))
			.unwrap()
			.clone();
		println!("Pre update portals {:?}", pre_first);
		println!("Pre update portals {:?}", pre_second);
		// update the top-left CostFields and calculate new portals
		let mutated_sector_id = SectorID::new(0, 0);
		sector_cost_fields.set_field_cell_value(
			mutated_sector_id,
			255,
			FieldCell::new(4, 9),
			&map_dimensions,
		);
		sector_portals.update_portals(mutated_sector_id, &sector_cost_fields, &map_dimensions);

		let post_first = sector_portals
			.get_mut()
			.get_mut(&mutated_sector_id)
			.unwrap()
			.clone();
		let post_second = sector_portals
			.get_mut()
			.get_mut(&SectorID::new(0, 1))
			.unwrap()
			.clone();
		println!("Updated portals {:?}", post_first);
		println!("Updated portals {:?}", post_second);
		// This produces a new representation with an extra portal, `x` denotes the impassable point
		// just inserted
		// _______________________________
		// |         |         |         |
		// |         |         |         |
		// |         P         P         |
		// |         |         |         |
		// |_P__x_P__|____P____|____P____|
		// |         |         |         |
		// |         |         |         |
		// |         P         P         |
		// |         |         |         |
		// |____P____|____P____|____P____|
		// |         |         |         |
		// |         |         |         |
		// |         P         P         |
		// |         |         |         |
		// |_________|_________|_________|

		// ensure new portals are correct
		let actual_first = vec![FieldCell::new(1, 9), FieldCell::new(7, 9)];
		let actual_second = vec![FieldCell::new(1, 0), FieldCell::new(7, 0)];
		assert_eq!(actual_first, *post_first.get(&Ordinal::South));
		assert_eq!(actual_second, *post_second.get(&Ordinal::North));
	}
	#[test]
	fn expand_portal_goals_north() {
		let map_dimensions = MapDimensions::new(30, 30, 10, 0.5);
		let sector_cost_fields = SectorCostFields::new(&map_dimensions);
		let mut sector_portals = SectorPortals::new(
			map_dimensions.get_length(),
			map_dimensions.get_depth(),
			map_dimensions.get_sector_resolution(),
		);
		// build portals
		for (id, portals) in sector_portals.get_mut().iter_mut() {
			portals.recalculate_portals(&sector_cost_fields, id, &map_dimensions)
		}
		let sector_id = SectorID::new(1, 1);
		let portal_id = FieldCell::new(4, 0);
		let neighbour_sector_id = SectorID::new(1, 0);
		let goals = sector_portals
			.get()
			.get(&sector_id)
			.unwrap()
			.expand_portal_into_goals(
				&sector_cost_fields,
				&sector_id,
				&portal_id,
				&neighbour_sector_id,
				&map_dimensions,
			);

		let actual = vec![
			FieldCell::new(4, 0),
			FieldCell::new(3, 0),
			FieldCell::new(2, 0),
			FieldCell::new(1, 0),
			FieldCell::new(0, 0),
			FieldCell::new(5, 0),
			FieldCell::new(6, 0),
			FieldCell::new(7, 0),
			FieldCell::new(8, 0),
			FieldCell::new(9, 0),
		];
		assert_eq!(actual, goals);
	}
	#[test]
	fn expand_portal_goals_east() {
		let map_dimensions = MapDimensions::new(30, 30, 10, 0.5);
		let sector_cost_fields = SectorCostFields::new(&map_dimensions);
		let mut sector_portals = SectorPortals::new(
			map_dimensions.get_length(),
			map_dimensions.get_depth(),
			map_dimensions.get_sector_resolution(),
		);
		// build portals
		for (id, portals) in sector_portals.get_mut().iter_mut() {
			portals.recalculate_portals(&sector_cost_fields, id, &map_dimensions)
		}
		let sector_id = SectorID::new(1, 1);
		let portal_id = FieldCell::new(9, 4);
		let neighbour_sector_id = SectorID::new(2, 1);
		let goals = sector_portals
			.get()
			.get(&sector_id)
			.unwrap()
			.expand_portal_into_goals(
				&sector_cost_fields,
				&sector_id,
				&portal_id,
				&neighbour_sector_id,
				&map_dimensions,
			);

		let actual = vec![
			FieldCell::new(9, 4),
			FieldCell::new(9, 3),
			FieldCell::new(9, 2),
			FieldCell::new(9, 1),
			FieldCell::new(9, 0),
			FieldCell::new(9, 5),
			FieldCell::new(9, 6),
			FieldCell::new(9, 7),
			FieldCell::new(9, 8),
			FieldCell::new(9, 9),
		];
		assert_eq!(actual, goals);
	}
	#[test]
	fn expand_portal_goals_south() {
		let map_dimensions = MapDimensions::new(30, 30, 10, 0.5);
		let sector_cost_fields = SectorCostFields::new(&map_dimensions);
		let mut sector_portals = SectorPortals::new(
			map_dimensions.get_length(),
			map_dimensions.get_depth(),
			map_dimensions.get_sector_resolution(),
		);
		// build portals
		for (id, portals) in sector_portals.get_mut().iter_mut() {
			portals.recalculate_portals(&sector_cost_fields, id, &map_dimensions)
		}
		let sector_id = SectorID::new(1, 1);
		let portal_id = FieldCell::new(4, 9);
		let neighbour_sector_id = SectorID::new(1, 2);
		let goals = sector_portals
			.get()
			.get(&sector_id)
			.unwrap()
			.expand_portal_into_goals(
				&sector_cost_fields,
				&sector_id,
				&portal_id,
				&neighbour_sector_id,
				&map_dimensions,
			);

		let actual = vec![
			FieldCell::new(4, 9),
			FieldCell::new(3, 9),
			FieldCell::new(2, 9),
			FieldCell::new(1, 9),
			FieldCell::new(0, 9),
			FieldCell::new(5, 9),
			FieldCell::new(6, 9),
			FieldCell::new(7, 9),
			FieldCell::new(8, 9),
			FieldCell::new(9, 9),
		];
		assert_eq!(actual, goals);
	}
	#[test]
	fn expand_portal_goals_west() {
		let map_dimensions = MapDimensions::new(30, 30, 10, 0.5);
		let sector_cost_fields = SectorCostFields::new(&map_dimensions);
		let mut sector_portals = SectorPortals::new(
			map_dimensions.get_length(),
			map_dimensions.get_depth(),
			map_dimensions.get_sector_resolution(),
		);
		// build portals
		for (id, portals) in sector_portals.get_mut().iter_mut() {
			portals.recalculate_portals(&sector_cost_fields, id, &map_dimensions)
		}
		let sector_id = SectorID::new(1, 1);
		let portal_id = FieldCell::new(0, 4);
		let neighbour_sector_id = SectorID::new(0, 1);
		let goals = sector_portals
			.get()
			.get(&sector_id)
			.unwrap()
			.expand_portal_into_goals(
				&sector_cost_fields,
				&sector_id,
				&portal_id,
				&neighbour_sector_id,
				&map_dimensions,
			);

		let actual = vec![
			FieldCell::new(0, 4),
			FieldCell::new(0, 3),
			FieldCell::new(0, 2),
			FieldCell::new(0, 1),
			FieldCell::new(0, 0),
			FieldCell::new(0, 5),
			FieldCell::new(0, 6),
			FieldCell::new(0, 7),
			FieldCell::new(0, 8),
			FieldCell::new(0, 9),
		];
		assert_eq!(actual, goals);
	}
	#[test]
	fn expand_portal_goals_short_local() {
		let map_dimensions = MapDimensions::new(30, 30, 10, 0.5);
		let sector_id = SectorID::new(1, 1);
		let neighbour_sector_id = SectorID::new(1, 0);
		let mut sector_cost_fields = SectorCostFields::new(&map_dimensions);
		sector_cost_fields.set_field_cell_value(
			sector_id,
			255,
			FieldCell::new(3, 0),
			&map_dimensions,
		);

		let mut sector_portals = SectorPortals::new(
			map_dimensions.get_length(),
			map_dimensions.get_depth(),
			map_dimensions.get_sector_resolution(),
		);
		// build portals
		for (id, portals) in sector_portals.get_mut().iter_mut() {
			portals.recalculate_portals(&sector_cost_fields, id, &map_dimensions)
		}

		let portal_id = FieldCell::new(1, 0);
		let goals = sector_portals
			.get()
			.get(&sector_id)
			.unwrap()
			.expand_portal_into_goals(
				&sector_cost_fields,
				&sector_id,
				&portal_id,
				&neighbour_sector_id,
				&map_dimensions,
			);

		let actual = vec![
			FieldCell::new(1, 0),
			FieldCell::new(0, 0),
			FieldCell::new(2, 0),
		];
		assert_eq!(actual, goals);
	}
	#[test]
	fn expand_portal_goals_short_adjacent() {
		let map_dimensions = MapDimensions::new(30, 30, 10, 0.5);
		let sector_id = SectorID::new(1, 1);
		let neighbour_sector_id = SectorID::new(1, 0);
		let mut sector_cost_fields = SectorCostFields::new(&map_dimensions);
		sector_cost_fields.set_field_cell_value(
			neighbour_sector_id,
			255,
			FieldCell::new(3, 9),
			&map_dimensions,
		);

		let mut sector_portals = SectorPortals::new(
			map_dimensions.get_length(),
			map_dimensions.get_depth(),
			map_dimensions.get_sector_resolution(),
		);
		// build portals
		for (id, portals) in sector_portals.get_mut().iter_mut() {
			portals.recalculate_portals(&sector_cost_fields, id, &map_dimensions)
		}

		let portal_id = FieldCell::new(1, 0);
		let goals = sector_portals
			.get()
			.get(&sector_id)
			.unwrap()
			.expand_portal_into_goals(
				&sector_cost_fields,
				&sector_id,
				&portal_id,
				&neighbour_sector_id,
				&map_dimensions,
			);

		let actual = vec![
			FieldCell::new(1, 0),
			FieldCell::new(0, 0),
			FieldCell::new(2, 0),
		];
		assert_eq!(actual, goals);
	}
}