forked from SevenChords/CipesAtHome
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator.c
2987 lines (2669 loc) · 117 KB
/
calculator.c
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
#include <stdio.h>
#include <stdlib.h>
#include <libconfig.h>
#include <time.h>
#if AGGRESSIVE_0_ALLOCATING || VERIFYING_SHIFTING_FUNCTIONS
// Pull in the "_s" bounds checking functions
#define __STDC_WANT_LIB_EXT1__ 1
#endif
#include <string.h>
#include <stdbool.h>
#include <limits.h>
#include <assert.h>
#include <omp.h>
#include "base.h"
#include "calculator.h"
#include "FTPManagement.h"
#include "recipes.h"
#include "start.h"
#include "shutdown.h"
#include "logger.h"
#include "rand_replace.h"
#include "absl/base/port.h"
// DON'T TOUCH: These reflect the logic of Paper Mario TTYD itself. Changing these will result in invalid plans.
#define CHOOSE_2ND_INGREDIENT_FRAMES 56 // Penalty for choosing a 2nd item
#define TOSS_FRAMES 32 // Penalty for having to toss an item
#define ALPHA_SORT_FRAMES 38 // Penalty to perform alphabetical ascending sort
#define REVERSE_ALPHA_SORT_FRAMES 40 // Penalty to perform alphabetical descending sort
#define TYPE_SORT_FRAMES 39 // Penalty to perform type ascending sort
#define REVERSE_TYPE_SORT_FRAMES 41 // Penalty to perform type descending sort
#define JUMP_STORAGE_NO_TOSS_FRAMES 5 // Penalty for not tossing the last item (because we need to get Jump Storage)
// User configurable tunables
#define WEAK_PB_FLOOR 4500 // If PB is above this value, consider it a "weak" PB and don't increase iteration limit as much.
// Just so first runs (like from non-existant results dir) don't spend so long trying to "optimize" a "not all that great" branch.
#define WEAK_PB_FLOOR_DIVISIOR 6 // Divide limit increase by this if a "weak" PB.
#define BUFFER_SEARCH_FRAMES 150 // Threshold to try optimizing a roadmap to attempt to beat the current record
#define BUFFER_SEARCH_FRAMES_KIND_OF_CLOSE 3 * BUFFER_SEARCH_FRAMES // Threshold for closeness to the current record to try spending more time on the branch
#define VERBOSE_ITERATION_LOG_RATE 100000 // How many iterations before logging iteration progress verbosely (level 6 logging)
#define DEFAULT_TERATION_LOG_BRANCH_INTERVAL_MAX_BEFORE_SLOWER_SCALING 50 // If the branch rate is above this, then additional values above this will be divided by DEFAULT_TERATION_LOG_BRANCH_RATE_DIVISOR for deciding when to log iteration progress incrementally.
#define DEFAULT_TERATION_LOG_BRANCH_INTERVAL_DIVISOR 4 // How much to divide the branch rate additional value above the DEFAULT_TERATION_LOG_BRANCH_RATE_MAX_BEFORE_SLOWER_SCALING for deciding when to log iteration progress incrementally.
#define DEFAULT_ITERATION_LIMIT 150000l // Cutoff for iterations explored before resetting
#define DEFAULT_ITERATION_LIMIT_SHORT 75000l // Cutoff for iterations explored before resetting when short branches is randomly selected
#define SHORT_ITERATION_LIMIT_CHANCE 40 // Chance (out of 100) for a thread to choose DEFAULT_ITERATION_LIMIT_SHORT instead of DEFAULT_ITERATION_LIMIT when starting a new branch
#define ITERATION_LIMIT_INCREASE 10000000l // Amount to increase the iteration limit by when finding a new PB
// Basically 2.5*ITERATION_LIMIT_INCREASE, but keeps floats out of it so we can static_assert on it
#define ITERATION_LIMIT_INCREASE_FIRST ((ITERATION_LIMIT_INCREASE << 1) + (ITERATION_LIMIT_INCREASE >> 1)) // Amount to increase the iteration limit by when finding a new PB for the first time in this branch
#define ITERATION_LIMIT_MAX (12*ITERATION_LIMIT_INCREASE) // Maxumum iteration limit before increases shrink drastically (a soft maximum)
#define ITERATION_LIMIT_INCREASE_PAST_MAX (ITERATION_LIMIT_INCREASE/500) // Amount to increase the iteration limit by when finding a new record when past the max
#define ITERATION_LIMIT_INCREASE_GETTING_CLOSE ITERATION_LIMIT_INCREASE_FIRST / 4
#define ITERATION_LIMIT_INCREASE_GETTING_KINDOF_CLOSE ITERATION_LIMIT_INCREASE_GETTING_CLOSE / 2
#define SELECT_CHANCE_TO_SKIP_SEEMINGLY_GOOD_MOVE 25 // Chance (out of 100) for the select strategy to skip a seemingly good next move
#define DEFAULT_CAPACITY_FOR_EMPTY 8 // When initializing a dynamically sized array, an empty/NULL array will be initialized to an Array of this size on a new element add
#define CAPACITY_INCREASE_FACTOR 1.5 // When a dynamically sized array is full, increase capacity by this factor
#define CAPACITY_DECREASE_THRESHOLD 0.25 // When a dynamically sized array element count is below this fraction of the capacity, shrink it
#define CAPACITY_DECREASE_FACTOR 0.35 // When a dynamically sized array is shrunk, shrink it below this factor
#define CAPACITY_DECREASE_FLOOR (2*DEFAULT_CAPACITY_FOR_EMPTY) // Never shrink a dynamically sized array below this capacity
#define CHECK_SHUTDOWN_INTERVAL 30000
#define NEW_BRANCH_LOG_LEVEL 3
#define CHECK_SHUTDOWN_INTERVAL 30000
static const int UNSET_INDEX_SIGNED = -99999;
#define INDEX_ITEM_UNDEFINED -1
// Sanity tests for constants.
_CIPES_STATIC_ASSERT(VERBOSE_ITERATION_LOG_RATE > 0, "Log rates must be > 0");
_CIPES_STATIC_ASSERT(BUFFER_SEARCH_FRAMES < BUFFER_SEARCH_FRAMES_KIND_OF_CLOSE, "The 'close to PB' threshold must be <= 'kind of close to PB' threshold");
_CIPES_STATIC_ASSERT(DEFAULT_ITERATION_LIMIT_SHORT <= DEFAULT_ITERATION_LIMIT, "Short iteration limit must be <= then default iteration limit");
_CIPES_STATIC_ASSERT(ITERATION_LIMIT_INCREASE <= ITERATION_LIMIT_MAX, "Default iteration limit must be <= then iteration limit maximum");
_CIPES_STATIC_ASSERT(ITERATION_LIMIT_INCREASE <= ITERATION_LIMIT_MAX, "Iteration limit increase must be <= then iteration limit maximum");
_CIPES_STATIC_ASSERT(SHORT_ITERATION_LIMIT_CHANCE < 100, "Chance to use short iteration limit must be < 100");
_CIPES_STATIC_ASSERT(SHORT_ITERATION_LIMIT_CHANCE >= 0, "Chance to use short iteration limit must be >= 0");
_CIPES_STATIC_ASSERT(ITERATION_LIMIT_INCREASE_FIRST <= ITERATION_LIMIT_MAX, "Iteration limit increase must be <= then iteration limit maximum");
_CIPES_STATIC_ASSERT(ITERATION_LIMIT_INCREASE_PAST_MAX <= ITERATION_LIMIT_MAX, "Iteration limit increase must be <= then iteration limit maximum");
_CIPES_STATIC_ASSERT(ITERATION_LIMIT_INCREASE_PAST_MAX <= ITERATION_LIMIT_INCREASE, "The small Iteration limit (for when past ITERATION_LIMIT_MAX) must be <= the normal iteration limit increase");
_CIPES_STATIC_ASSERT(ITERATION_LIMIT_INCREASE_GETTING_CLOSE <= ITERATION_LIMIT_INCREASE_FIRST, "The 'getting close to PB' iteration limit increase must be less then the first PB increase.");
_CIPES_STATIC_ASSERT(ITERATION_LIMIT_INCREASE_GETTING_CLOSE <= ITERATION_LIMIT_MAX, "The 'getting close to PB' iteration limit increase must be <= then iteration limit maximum");
_CIPES_STATIC_ASSERT(ITERATION_LIMIT_INCREASE_GETTING_KINDOF_CLOSE <= ITERATION_LIMIT_INCREASE_GETTING_CLOSE,
"The 'getting kind of close to PB' iteration limit increase must be <= The 'getting close to PB' iteration limit increase");
_CIPES_STATIC_ASSERT(SELECT_CHANCE_TO_SKIP_SEEMINGLY_GOOD_MOVE < 100, "Chance to skip greedy, seemingly best move must be < 100");
_CIPES_STATIC_ASSERT(SELECT_CHANCE_TO_SKIP_SEEMINGLY_GOOD_MOVE >= 0, "Chance to skip greedy, seemingly best move must be >= 0");
_CIPES_STATIC_ASSERT(CHECK_SHUTDOWN_INTERVAL > 0, "Check for shutdown interval must be > 0");
_CIPES_STATIC_ASSERT(CHECK_SHUTDOWN_INTERVAL < DEFAULT_ITERATION_LIMIT, "Check for shutdown interval must be < the default iteration limit");
// Only GCC can assure that floating point constant expressions can be evaluated at compile time.
#if defined(__GNUC__) && !defined(__clang__)
_CIPES_STATIC_ASSERT(CAPACITY_DECREASE_THRESHOLD <= CAPACITY_DECREASE_FACTOR, "The decrease threshold must be <= the decrease factor");
_CIPES_STATIC_ASSERT(CAPACITY_INCREASE_FACTOR >= 1, "The increase factor must be >= 1");
#endif
_CIPES_STATIC_ASSERT(DEFAULT_CAPACITY_FOR_EMPTY > 0, "The default capacity must be > 0");
_CIPES_STATIC_ASSERT(CAPACITY_DECREASE_FLOOR > 0, "The floor for capacity must be > 0");
#define NOISY_DEBUG_FLAG 0
// Only uncomment the below if you are really using NOISY_DEBUG_FLAG
//#if NOISY_DEBUG_FLAG
//#define NOISY_DEBUG(...) printf(__VA_ARGS__)
//#else
#define NOISY_DEBUG(...) _REQUIRE_SEMICOLON
//#endif
#if VERIFYING_SHIFTING_FUNCTIONS
#define _assert_for_shifting_function(condition) _assert_with_stacktrace(condition)
// #elif defined(FAST_BUT_NO_VERIFY)
#else
#define _assert_for_shifting_function(condition) ABSL_INTERNAL_ASSUME_NO_ASSERT(condition)
// #define _assert_for_shifting_function(condition)
#endif
static const int INT_OUTPUT_ARRAY_SIZE_BYTES = sizeof(outputCreatedArray_t);
static const outputCreatedArray_t EMPTY_RECIPES = {0};
static const struct Cook EMPTY_COOK = {0};
typedef enum Alpha_Sort Alpha_Sort;
typedef enum Type_Sort Type_Sort;
typedef struct MoveDescription MoveDescription;
typedef struct Recipe Recipe;
typedef struct BranchPath BranchPath;
typedef struct CH5 CH5;
typedef struct CH5_Eval CH5_Eval;
typedef struct ItemCombination ItemCombination;
typedef struct Inventory Inventory;
typedef struct Result Result;
typedef struct Cook Cook_s; // See calculator.h on why we can't just call this "Cook".
typedef struct OptimizeResult OptimizeResult;
int **invFrames;
Recipe *recipeList;
ABSL_ATTRIBUTE_UNUSED ABSL_ATTRIBUTE_ALWAYS_INLINE
static inline bool checkShutdownOnIndex(int i) {
return i % CHECK_SHUTDOWN_INTERVAL == 0 && askedToShutdown();
}
ABSL_ATTRIBUTE_UNUSED ABSL_ATTRIBUTE_ALWAYS_INLINE
static inline bool prefetchShutdownOnIndex(int i) {
#if ENABLE_PREFETCHING
if (i % CHECK_SHUTDOWN_INTERVAL == (CHECK_SHUTDOWN_INTERVAL - 1)) {
prefetchShutdown();
return true;
}
#endif
return false;
}
ABSL_ATTRIBUTE_UNUSED ABSL_ATTRIBUTE_ALWAYS_INLINE
static inline bool checkShutdownOnIndexWithPrefetch(int i) {
#if ENABLE_PREFETCHING
int modulo = i % CHECK_SHUTDOWN_INTERVAL;
switch (modulo) {
case 0:
return askedToShutdown();
case (CHECK_SHUTDOWN_INTERVAL - 1):
prefetchShutdown();
return false;
default:
return false;
}
#else
return checkShutdownOnIndex(i);
#endif
}
ABSL_ATTRIBUTE_UNUSED ABSL_ATTRIBUTE_ALWAYS_INLINE
static inline bool checkShutdownOnIndexLong(long i) {
return i % CHECK_SHUTDOWN_INTERVAL == 0 && askedToShutdown();
}
ABSL_ATTRIBUTE_UNUSED ABSL_ATTRIBUTE_ALWAYS_INLINE
static inline bool prefetchShutdownOnIndexLong(long i) {
#if ENABLE_PREFETCHING
if (i % CHECK_SHUTDOWN_INTERVAL == (CHECK_SHUTDOWN_INTERVAL - 1)) {
prefetchShutdown();
return true;
}
#endif
return false;
}
ABSL_ATTRIBUTE_UNUSED ABSL_ATTRIBUTE_ALWAYS_INLINE
static inline bool checkShutdownOnIndexLongWithPrefetch(long i) {
#if ENABLE_PREFETCHING
int modulo = i % CHECK_SHUTDOWN_INTERVAL;
switch (modulo) {
case 0:
return askedToShutdown();
case (CHECK_SHUTDOWN_INTERVAL - 1):
prefetchShutdown();
return false;
default:
return false;
}
#else
return checkShutdownOnIndexLong(i);
#endif
}
/*-------------------------------------------------------------------
* Function : initializeInvFrames
*
* Initializes global variable invFrames, which is used to calculate
* the number of frames it takes to navigate to an item in the menu.
-------------------------------------------------------------------*/
void initializeInvFrames() {
invFrames = getInventoryFrames();
}
/*-------------------------------------------------------------------
* Function : initializeRecipeList
*
* Initializes global variable recipeList, which stores data pertaining
* to each of the 57 recipes, plus a representation of Chapter 5. This
* data consists of recipe outputs, number of different ways to cook the
* recipe, and the items required for each recipe combination.
-------------------------------------------------------------------*/
void initializeRecipeList() {
recipeList = getRecipeList();
}
/*-------------------------------------------------------------------
* Function : applyJumpStorageFramePenalty
* Inputs : BranchPath *node
*
* Looks at the node's Cook data. If the item is autoplaced, then add
* a penalty for not tossing the item. Adjust framesTaken and
* totalFramesTaken to reflect this change.
-------------------------------------------------------------------*/
void applyJumpStorageFramePenalty(BranchPath *node) {
if (((Cook_s *) node->description.data)->handleOutput == Autoplace) {
node->description.framesTaken += JUMP_STORAGE_NO_TOSS_FRAMES;
node->description.totalFramesTaken += JUMP_STORAGE_NO_TOSS_FRAMES;
}
return;
}
/*-------------------------------------------------------------------
* Function : copyOutputsFulfilled
* Inputs : int *destOutputsFulfilled, int *srcOutputsFulfilled
* Outputs :
* A simple memcpy to duplicate srcOutputsFulfilled into destOutputsFulfilled
-------------------------------------------------------------------*/
ABSL_ATTRIBUTE_ALWAYS_INLINE static inline void copyOutputsFulfilled(outputCreatedArray_t destOutputsFulfilled, const outputCreatedArray_t srcOutputsFulfilled) {
memcpy((void *)destOutputsFulfilled, (const void *)srcOutputsFulfilled, INT_OUTPUT_ARRAY_SIZE_BYTES);
}
/*-------------------------------------------------------------------
* Function : createChapter5Struct
* Inputs : int DB_place_index
* int CO_place_index
* int KM_place_index
* int CS_place_index
* int TR_use_index
* int lateSort
* Outputs : CH5 *ch5
*
* Compartmentalization of setting CH5 attributes
* lateSort tracks whether we performed the sort before or after the
* Keel Mango, for printing purposes
-------------------------------------------------------------------*/
ABSL_MUST_USE_RESULT CH5 *createChapter5Struct(CH5_Eval eval, int lateSort) {
CH5 *ch5 = malloc(sizeof(CH5));
checkMallocFailed(ch5);
ch5->indexDriedBouquet = eval.DB_place_index;
ch5->indexCoconut = eval.CO_place_index;
ch5->ch5Sort = eval.sort;
ch5->indexKeelMango = eval.KM_place_index;
ch5->indexCourageShell = eval.CS_place_index;
ch5->indexThunderRage = eval.TR_use_index;
ch5->lateSort = lateSort;
return ch5;
}
/*-------------------------------------------------------------------
* Function : createCookDescription
* Inputs : BranchPath *node
* Recipe recipe
* ItemCombination combo
* enum Type_Sort *tempInventory
* int *tempFrames
* int viableItems
* Outputs : MoveDescription useDescription
*
* Compartmentalization of generating a MoveDescription struct
* based on various parameters dependent on what recip we're cooking
-------------------------------------------------------------------*/
MoveDescription createCookDescription(const BranchPath *node, Recipe recipe, ItemCombination combo, Inventory *tempInventory, int *tempFrames, int viableItems) {
MoveDescription useDescription;
useDescription.action = Cook;
int ingredientLoc[2] = {UNSET_INDEX_SIGNED, UNSET_INDEX_SIGNED};
// Determine the locations of both ingredients
ingredientLoc[0] = indexOfItemInInventory(*tempInventory, combo.item1);
if (combo.numItems == 1) {
createCookDescription1Item(node, recipe, combo, tempInventory, ingredientLoc, tempFrames, viableItems, &useDescription);
}
else {
ingredientLoc[1] = indexOfItemInInventory(*tempInventory, combo.item2);
createCookDescription2Items(node, recipe, combo, tempInventory, ingredientLoc, tempFrames, viableItems, &useDescription);
}
return useDescription;
}
/*-------------------------------------------------------------------
* Function : createCookDescription1Item
* Inputs : BranchPath *node
* Recipe recipe
* ItemCombination combo
* enum Type_Sort *tempInventory
* int *ingredientLoc
* int *ingredientOffset
* int *tempFrames
* int viableItems
MoveDescription *useDescription
*
* Handles inventory management and frame calculation for recipes of
* length 1. Generates Cook structure and points to this structure
* in useDescription.
-------------------------------------------------------------------*/
void createCookDescription1Item(const BranchPath *node, Recipe recipe, ItemCombination combo, Inventory *tempInventory, int *ingredientLoc, int *tempFrames, int viableItems, MoveDescription *useDescription) {
// This is a potentially viable recipe with 1 ingredient
// Determine how many frames will be needed to select that item
*tempFrames = invFrames[viableItems - 1][ingredientLoc[0] - tempInventory->nulls];
// Modify the inventory if the ingredient was in the first 10 slots
if (ingredientLoc[0] < 10) {
// Shift the inventory towards the front of the array to fill the null
*tempInventory = removeItem(*tempInventory, ingredientLoc[0]);
}
generateCook(useDescription, combo, recipe, ingredientLoc, 0);
generateFramesTaken(useDescription, node, *tempFrames);
}
/*-------------------------------------------------------------------
* Function : createCookDescription2Items
* Inputs : BranchPath *node
* Recipe recipe
* ItemCombination combo
* enum Type_Sort *tempInventory
* int *ingredientLoc
* int *ingredientOffset
* int *tempFrames
* int viableItems
MoveDescription *useDescription
*
* Handles inventory management and frame calculation for recipes of
* length 2. Swaps items if it's faster to choose the second item first.
* Generates Cook structure and points to this structure in useDescription.
-------------------------------------------------------------------*/
void createCookDescription2Items(const BranchPath *node, Recipe recipe, ItemCombination combo, Inventory *tempInventory, int *ingredientLoc, int *tempFrames, int viableItems, MoveDescription *useDescription) {
// This is a potentially viable recipe with 2 ingredients
//Baseline frames based on how many times we need to access the menu
*tempFrames = CHOOSE_2ND_INGREDIENT_FRAMES;
// Swap ingredient order if necessary. There are some configurations where
// it is 2 frames faster to pick the ingredients in the reverse order or
// only one order is possible.
int swap = 0;
if (selectSecondItemFirst(ingredientLoc, tempInventory->nulls, viableItems)) {
swapItems(ingredientLoc);
swap = 1;
}
int visibleLoc0 = ingredientLoc[0] - tempInventory->nulls;
int visibleLoc1 = ingredientLoc[1] - tempInventory->nulls;
// Add the frames to choose the first ingredient.
*tempFrames += invFrames[viableItems - 1][visibleLoc0];
// Depending on the first ingredient's position and the state of the
// inventory, it or another item could be hidden during the second
// ingredient selection.
if (ingredientLoc[0] < 10) {
--viableItems;
// If the second ingredient comes after the first, its position will be
// 1 less.
if (ingredientLoc[0] < ingredientLoc[1]) {
--visibleLoc1;
}
}
else if (visibleLoc0 >= 10) {
--viableItems;
// If there are nulls in this case, the wrong item is hidden. If the
// second ingredient comes after the hidden item, its position will be
// 1 less.
if (visibleLoc0 < ingredientLoc[1]) {
--visibleLoc1;
}
}
// Add the frames to choose the second ingredient.
*tempFrames += invFrames[viableItems - 1][visibleLoc1];
// Set each inventory index to null if the item was in the first 10 slots
// To reduce complexity, remove the items in ascending order of index
if (ingredientLoc[0] < ingredientLoc[1]) {
if (ingredientLoc[0] < 10) {
*tempInventory = removeItem(*tempInventory, ingredientLoc[0]);
}
if (ingredientLoc[1] < 10) {
*tempInventory = removeItem(*tempInventory, ingredientLoc[1]);
}
}
else {
if (ingredientLoc[1] < 10) {
*tempInventory = removeItem(*tempInventory, ingredientLoc[1]);
}
if (ingredientLoc[0] < 10) {
*tempInventory = removeItem(*tempInventory, ingredientLoc[0]);
}
}
// Describe what items were used
generateCook(useDescription, combo, recipe, ingredientLoc, swap);
generateFramesTaken(useDescription, node, *tempFrames);
}
/*-------------------------------------------------------------------
* Function : createMoveQuick
*
* Outputs : BranchPath *newMoveNode
*
* Allocates a BranchPath struct on the heap, with the assurance that
* the callee will either initialize the strcut's value to sane values,
* or doesn't care in it's usage case.
*/
static BranchPath *createMoveQuick() {
BranchPath *node = malloc(sizeof(BranchPath));
checkMallocFailed(node);
return node;
}
/*-------------------------------------------------------------------
* Function : createLegalMove
* Inputs : BranchPath *node
* enum Type_Sort *inventory
* MoveDescription description
* int *outputsFulfilled
* int numOutputsFulfilled
* Outputs : BranchPath *newLegalMove
*
* Given the input parameters, allocate and set attributes for a legalMove node
* Note: Although node is never modified by this function, it will be the
* new {return}->prev node of the returned BranchPath, thus it is not const
-------------------------------------------------------------------*/
BranchPath *createLegalMove(BranchPath *mutableNode, Inventory inventory, MoveDescription description, const outputCreatedArray_t outputsFulfilled, int numOutputsFulfilled) {
// Prefer to work with the const version when possible to ensure we really don't modify it.
const BranchPath *node = mutableNode;
BranchPath *newLegalMove = createMoveQuick();
newLegalMove->moves = node->moves + 1;
newLegalMove->inventory = inventory;
newLegalMove->description = description;
newLegalMove->prev = mutableNode;
newLegalMove->next = NULL;
copyOutputsFulfilled(newLegalMove->outputCreated, outputsFulfilled);
newLegalMove->numOutputsCreated = numOutputsFulfilled;
newLegalMove->legalMoves = NULL;
newLegalMove->numLegalMoves = 0;
newLegalMove->capacityLegalMoves = 0;
if (description.action >= Sort_Alpha_Asc && description.action <= Sort_Type_Des) {
newLegalMove->totalSorts = node->totalSorts + 1;
}
else {
newLegalMove->totalSorts = node->totalSorts;
}
return newLegalMove;
}
/*-------------------------------------------------------------------
* Function : createMoveRaw
*
* Outputs : BranchPath *newMoveNode
*
* Allocates a BranchPath struct on the heap, setting some critical values
* to sane initial values.
*/
static BranchPath *createMoveZeroed() {
BranchPath *node = calloc(sizeof(BranchPath), 1);
checkMallocFailed(node);
return node;
}
/*-------------------------------------------------------------------
* Function : filterOut2Ingredients
* Inputs : BranchPath *node
*
* For the first node's legal moves, we cannot cook a recipe which
* contains two items. Thus, we need to remove any legal moves
* which require two ingredients
-------------------------------------------------------------------*/
void filterOut2Ingredients(BranchPath *node) {
for (int i = 0; i < node->numLegalMoves; i++) {
if (node->legalMoves[i]->description.action == Cook) {
Cook_s *cook = node->legalMoves[i]->description.data;
if (cook->numItems == 2) {
freeLegalMove(node, i);
i--; // Update i so we don't skip over the newly moved legalMoves
}
}
}
}
/*-------------------------------------------------------------------
* Function : finalizeChapter5Eval
* Inputs : BranchPath *node
* enum Type_Sort *inventory
* enum Action sort
* CH5 *ch5Data
* int temp_frame_sum
* int *outputsFulfilled
* int numOutputsFulfilled
*
* Given input parameters, construct a new legal move to represent CH5
-------------------------------------------------------------------*/
void finalizeChapter5Eval(BranchPath *node, Inventory inventory, CH5 *ch5Data, int temp_frame_sum, const outputCreatedArray_t outputsFulfilled, int numOutputsFulfilled) {
// Get the index of where to insert this legal move to
int insertIndex = getInsertionIndex(node, temp_frame_sum);
MoveDescription description;
description.action = Ch5;
description.data = ch5Data;
description.framesTaken = temp_frame_sum;
description.totalFramesTaken = node->description.totalFramesTaken + temp_frame_sum;
// Create the legalMove node
BranchPath *legalMove = createLegalMove(node, inventory, description, outputsFulfilled, numOutputsFulfilled);
// Apend the legal move
insertIntoLegalMoves(insertIndex, legalMove, node);
}
/*-------------------------------------------------------------------
* Function : finalizeLegalMove
* Inputs : BranchPath *node
* int tempFrames
* MoveDescription useDescription
* enum Type_Sort *tempInventory
* int *tempOutputsFulfilled
* int numOutputsFulfilled
* enum HandleOutput tossType
* enum Type_Sort toss
* int tossIndex
*
* Given input parameters, construct a new legal move to represent
* a valid recipe move. Also checks to see if the legal move exceeds
* the frame limit
-------------------------------------------------------------------*/
void finalizeLegalMove(BranchPath *node, int tempFrames, MoveDescription useDescription, Inventory tempInventory, const outputCreatedArray_t tempOutputsFulfilled, int numOutputsFulfilled, enum HandleOutput tossType, enum Type_Sort toss, int tossIndex) {
// Determine if the legal move exceeds the frame limit. If so, return out
if (useDescription.totalFramesTaken > getLocalRecord() + BUFFER_SEARCH_FRAMES) {
return;
}
// Determine where to insert this legal move into the list of legal moves (sorted by frames taken)
int insertIndex = getInsertionIndex(node, tempFrames);
Cook_s *cookNew = malloc(sizeof(Cook_s));
checkMallocFailed(cookNew);
*cookNew = *((Cook_s*)useDescription.data);
cookNew->handleOutput = tossType;
cookNew->toss = toss;
cookNew->indexToss = tossIndex;
useDescription.data = cookNew;
// Create the legalMove node
BranchPath *newLegalMove = createLegalMove(node, tempInventory, useDescription, tempOutputsFulfilled, numOutputsFulfilled);
// Insert this new move into the current node's legalMove array
insertIntoLegalMoves(insertIndex, newLegalMove, node);
}
/*-------------------------------------------------------------------
* Function : freeAllNodes
* Inputs : BranchPath *node
*
* We've reached the iteration limit, so free all nodes in the roadmap
* We additionally need to delete node from the previous node's list of
* legalMoves to prevent a double-free
-------------------------------------------------------------------*/
void freeAllNodes(BranchPath *node) {
BranchPath *prevNode = NULL;
do {
prevNode = node->prev;
freeNode(node);
// Delete node in nextNode's list of legal moves to prevent a double free
if (prevNode != NULL && prevNode->legalMoves != NULL) {
if (prevNode->capacityLegalMoves > 0) {
prevNode->legalMoves[0] = NULL;
}
prevNode->numLegalMoves--;
shiftUpLegalMoves(prevNode, 1);
}
// Traverse to the previous node
node = prevNode;
} while (node != NULL);
}
/*-------------------------------------------------------------------
* Function : freeLegalMoveOnly
* Inputs : BranchPath *node
* int index
*
* Free the legal move at index in the node's array of legal moves,
* but unlike freeLegalMove(), this does NOT shift the existing legal
* moves to fill the gap. This is useful in cases where where the
* caller can assure such consistency is not needed (For example,
* freeing the last legal move or freeing all legal moves).
-------------------------------------------------------------------*/
static void freeLegalMoveOnly(BranchPath *node, int index) {
freeNode(node->legalMoves[index]);
node->legalMoves[index] = NULL;
node->numLegalMoves--;
node->next = NULL;
_assert_with_stacktrace(node->numLegalMoves >= 0);
}
/*-------------------------------------------------------------------
* Function : freeLegalMove
* Inputs : BranchPath *node
* int index
*
* Free the legal move at index in the node's array of legal moves
-------------------------------------------------------------------*/
void freeLegalMove(BranchPath *node, int index) {
_assert_with_stacktrace(index < node->capacityLegalMoves);
_assert_with_stacktrace(index < node->numLegalMoves);
_assert_for_shifting_function(node->numLegalMoves <= node->capacityLegalMoves);
freeLegalMoveOnly(node, index);
// Shift up the rest of the legal moves
shiftUpLegalMoves(node, index + 1);
}
/*-------------------------------------------------------------------
* Function : freeNode
* Inputs : BranchPath *node
*
* Free the current node and all legal moves within the node
-------------------------------------------------------------------*/
void freeNode(BranchPath *node) {
if (node == NULL) {
return;
}
if (node->description.data != NULL) {
free(node->description.data);
}
if (node->legalMoves != NULL) {
const int max = node->numLegalMoves;
int i = 0;
while (i < max) {
// Don't need to worry about shifting up when we do this.
// Or resetting slots to NULL.
// We are blowing it all away anyways.
freeLegalMoveOnly(node, i++);
}
free(node->legalMoves);
}
free(node);
}
/*-------------------------------------------------------------------
* Function : fulfillChapter5
* Inputs : BranchPath *curNode
*
* A preliminary step to determine Dried Bouquet and Coconut placement
* before calling handleChapter5Eval
-------------------------------------------------------------------*/
void fulfillChapter5(BranchPath *curNode) {
// Create an outputs chart but with the Dried Bouquet collected
// to ensure that the produced inventory can fulfill all remaining recipes
outputCreatedArray_t tempOutputsFulfilled;
copyOutputsFulfilled(tempOutputsFulfilled, curNode->outputCreated);
tempOutputsFulfilled[getIndexOfRecipe(Dried_Bouquet)] = true;
int numOutputsFulfilled = curNode->numOutputsCreated + 1;
Inventory newInventory = curNode->inventory;
int mousse_cake_index = indexOfItemInInventory(newInventory, Mousse_Cake);
// Create the CH5 eval struct
CH5_Eval eval;
// Explicit int casts are to prevent intermediary underflows from the uint_8 math.
int viableItems = (int)newInventory.length - newInventory.nulls - min((int)newInventory.length - 10, newInventory.nulls);
// Calculate frames it takes the navigate to the Mousse Cake and the Hot Dog for the trade
eval.frames_HD = 2 * invFrames[viableItems - 1][indexOfItemInInventory(newInventory, Hot_Dog) - newInventory.nulls];
eval.frames_MC = invFrames[viableItems - 1][mousse_cake_index - newInventory.nulls];
// If the Mousse Cake is in the first 10 slots, change it to NULL
if (mousse_cake_index < 10) {
newInventory = removeItem(newInventory, mousse_cake_index);
}
// Handle allocation of the first 2 CH5 items (Dried Bouquet and Coconut)
switch (newInventory.nulls) {
case 0 :
handleDBCOAllocation0Nulls(curNode, newInventory, tempOutputsFulfilled, numOutputsFulfilled, eval);
break;
case 1 :
handleDBCOAllocation1Null(curNode, newInventory, tempOutputsFulfilled, numOutputsFulfilled, eval);
break;
default :
handleDBCOAllocation2Nulls(curNode, newInventory, tempOutputsFulfilled, numOutputsFulfilled, eval);
}
// We know tempOutputsFulfilled does not escape this scope, so safe to be unallocated on return.
}
/*-------------------------------------------------------------------
* Function : fulfillRecipes
* Inputs : BranchPath *curNode
* int recipeIndex
*
* Iterate through all possible combinations of cooking different
* recipes and create legal moves for them
-------------------------------------------------------------------*/
void fulfillRecipes(BranchPath *curNode) {
// For debugging stacktraces
/*if (omp_get_thread_num() == 0) {
_assert_with_stacktrace(false);
// checkMallocFailed(NULL);
}*/
// Only evaluate the 57th recipe (Mistake) when it's the last recipe to fulfill
// This is because it is relatively easy to craft this output with many of the previous outputs, and will take minimal frames
int upperOutputLimit = (curNode->numOutputsCreated == NUM_RECIPES - 1) ? NUM_RECIPES : (NUM_RECIPES - 1);
// Iterate through all recipe ingredient combos
for (int recipeIndex = 0; recipeIndex < upperOutputLimit; recipeIndex++) {
// Only want recipes that haven't been fulfilled
if (curNode->outputCreated[recipeIndex]) {
continue;
}
// Dried Bouquet (Recipe index 56) represents the Chapter 5 intermission
// Don't actually use the specified recipe, as it is handled later
if (recipeIndex == getIndexOfRecipe(Dried_Bouquet)) {
continue;
}
// Only want ingredient combos that can be fulfilled right now!
Recipe recipe = recipeList[recipeIndex];
ItemCombination *combos = recipe.combos;
for (int comboIndex = 0; comboIndex < recipe.countCombos; comboIndex++) {
ItemCombination combo = combos[comboIndex];
if (!itemComboInInventory(combo, curNode->inventory)) {
continue;
}
// This is a recipe that can be fulfilled right now!
// Copy the inventory
Inventory newInventory = curNode->inventory;
// Mark that this output has been fulfilled for viability determination
outputCreatedArray_t tempOutputsFulfilled;
copyOutputsFulfilled(tempOutputsFulfilled, curNode->outputCreated);
tempOutputsFulfilled[recipeIndex] = true;
int numOutputsFulfilled = curNode->numOutputsCreated + 1;
// How many items there are to choose from (Not NULL or hidden)
int viableItems = newInventory.length - newInventory.nulls - min(newInventory.length - 10, newInventory.nulls);
int tempFrames;
MoveDescription useDescription = createCookDescription(curNode, recipe, combo, &newInventory, &tempFrames, viableItems);
// Store the base useDescription's cook pointer to be freed later
Cook_s *cookBase = (Cook_s *)useDescription.data;
// Handle allocation of the output
handleRecipeOutput(curNode, newInventory, tempFrames, useDescription, tempOutputsFulfilled, numOutputsFulfilled, recipe.output, viableItems);
free(cookBase);
// We know tempOutputsFulfilled does not escape this scope, so safe to be unallocated on return.
}
}
}
/*-------------------------------------------------------------------
* Function : generateCook
* Inputs : MoveDescription *description
* ItemCombination combo
* Recipe recipe
* int *ingredientLoc
* int swap
*
* Given input parameters, generate Cook structure
-------------------------------------------------------------------*/
void generateCook(MoveDescription *description, const ItemCombination combo, const Recipe recipe, const int *ingredientLoc, int swap) {
Cook_s *cook = malloc(sizeof(Cook_s));
checkMallocFailed(cook);
description->action = Cook;
cook->numItems = combo.numItems;
if (swap) {
cook->item1 = combo.item2;
cook->item2 = combo.item1;
}
else {
cook->item1 = combo.item1;
cook->item2 = combo.item2;
}
cook->itemIndex1 = ingredientLoc[0];
cook->itemIndex2 = ingredientLoc[1];
cook->output = recipe.output;
description->data = cook;
}
/*-------------------------------------------------------------------
* Function : generateFramesTaken
* Inputs : MoveDescription *description
* BranchPath *node
* int framesTaken
*
* Assign frame duration to description structure and reference the
* previous node to find the total frame duration for the roadmap thus far
-------------------------------------------------------------------*/
void generateFramesTaken(MoveDescription *description, const BranchPath *node, int framesTaken) {
description->framesTaken = framesTaken;
description->totalFramesTaken = node->description.totalFramesTaken + framesTaken;
}
/*-------------------------------------------------------------------
* Function : getInsertionIndex
* Inputs : BranchPath *curNode
* int frames
*
* Based on the frames it takes to complete a new legal move, find out
* where to insert it in the current node's array of legal moves, which
* is ordered based on frame count ascending
-------------------------------------------------------------------*/
int getInsertionIndex(const BranchPath *curNode, int frames) {
if (curNode->legalMoves == NULL) {
return 0;
}
int tempIndex = 0;
while (tempIndex < curNode->numLegalMoves && frames > curNode->legalMoves[tempIndex]->description.framesTaken) {
tempIndex++;
}
return tempIndex;
}
/*-------------------------------------------------------------------
* Function : getSortFrames
* Inputs : enum Action action
* Outputs : int frames
*
* Depending on the type of sort, return the corresponding frame cost.
-------------------------------------------------------------------*/
int getSortFrames(enum Action action) {
switch (action) {
case Sort_Alpha_Asc:
return ALPHA_SORT_FRAMES;
case Sort_Alpha_Des:
return REVERSE_ALPHA_SORT_FRAMES;
case Sort_Type_Asc:
return TYPE_SORT_FRAMES;
case Sort_Type_Des:
return REVERSE_TYPE_SORT_FRAMES;
default:
// Critical error if we reach this point...
// action should be some type of sort
exit(-2);
}
}
/*-------------------------------------------------------------------
* Function : handleChapter5EarlySortEndItems
* Inputs : BranchPath *node
* enum Type_Sort *inventory
* int *outputsFulfilled
* int numOutputsFulfilled
* int sort_frames
* enum Action sort
* int frames_DB
* int frames_CO
* int DB_place_index
* int CO_place_index
*
* Evaluate Chapter 5 such that a sort occurs between grabbing the
* Coconut and the Keel Mango. Place the Keel Mango and Courage Shell
* in various inventory locations. Determine if the move is legal.
-------------------------------------------------------------------*/
void handleChapter5EarlySortEndItems(BranchPath *node, Inventory inventory, const outputCreatedArray_t outputsFulfilled, int numOutputsFulfilled, CH5_Eval eval) {
for (eval.KM_place_index = 0; eval.KM_place_index < 10; eval.KM_place_index++) {
// Don't allow current move to remove Thunder Rage or previously
// obtained items
if (inventory.inventory[eval.KM_place_index] == Thunder_Rage
|| inventory.inventory[eval.KM_place_index] == Dried_Bouquet) {
continue;
}
// Replace the chosen item with the Keel Mango
Inventory km_temp_inventory = replaceItem(inventory, eval.KM_place_index, Keel_Mango);
// Calculate the frames for this action
eval.frames_KM = TOSS_FRAMES + invFrames[inventory.length][eval.KM_place_index + 1];
for (eval.CS_place_index = 1; eval.CS_place_index < 10; eval.CS_place_index++) {
// Don't allow current move to remove Thunder Rage or previously
// obtained items
if (eval.CS_place_index == eval.KM_place_index
|| km_temp_inventory.inventory[eval.CS_place_index] == Thunder_Rage
|| inventory.inventory[eval.KM_place_index] == Dried_Bouquet) {
continue;
}
// Replace the chosen item with the Courage Shell
Inventory kmcs_temp_inventory = replaceItem(km_temp_inventory, eval.CS_place_index, Courage_Shell);
// Calculate the frames for this action
eval.frames_CS = TOSS_FRAMES + invFrames[kmcs_temp_inventory.length][eval.CS_place_index + 1];
// The next event is using the Thunder Rage item before resuming the 2nd session of recipe fulfillment
eval.TR_use_index = indexOfItemInInventory(kmcs_temp_inventory, Thunder_Rage);
if (eval.TR_use_index < 10) {
kmcs_temp_inventory = removeItem(kmcs_temp_inventory, eval.TR_use_index);
}
// Calculate the frames for this action
eval.frames_TR = invFrames[kmcs_temp_inventory.length - 1][eval.TR_use_index];
// Calculate the frames of all actions done
int temp_frame_sum = eval.frames_DB + eval.frames_CO + eval.frames_KM + eval.frames_CS + eval.frames_TR + eval.frames_HD + eval.frames_MC + eval.sort_frames;
// Determine if the remaining inventory is sufficient to fulfill all remaining recipes
if (stateOK(kmcs_temp_inventory, outputsFulfilled, recipeList)) {
CH5 *ch5Data = createChapter5Struct(eval, 0);
finalizeChapter5Eval(node, kmcs_temp_inventory, ch5Data, temp_frame_sum, outputsFulfilled, numOutputsFulfilled);
}
}
}
}
/*-------------------------------------------------------------------
* Function : handleChapter5Eval
* Inputs : BranchPath *node
* enum Type_Sort *inventory
* int *outputsFulfilled
* int numOutputsFulfilled
* int frames_DB
* int frames_CO
* int DB_place_index
* int CO_place_index
*
* Main Chapter 5 evaluation function. After allocating Dried Bouquet
* and Coconut in the caller function, try performing a sort before
* grabbing the Keel Mango and evaluate legal moves. Afterwards, try
* placing the Keel Mango by tossing various inventory items and
* evaluate legal moves.
-------------------------------------------------------------------*/
void handleChapter5Eval(BranchPath *node, Inventory inventory, const outputCreatedArray_t outputsFulfilled, int numOutputsFulfilled, CH5_Eval eval) {
// Evaluate sorting before the Keel Mango
// Use -1 to identify that we are not collecting the Keel Mango until after the sort
eval.frames_KM = -1;
eval.KM_place_index = -1;
handleChapter5Sorts(node, inventory, outputsFulfilled, numOutputsFulfilled, eval);
// Place the Keel Mango in a null spot if one is available.
if (inventory.nulls >= 1) {
// Making a copy of the temp inventory for what it looks like after the allocation of the KM
Inventory km_temp_inventory = addItem(inventory, Keel_Mango);
eval.frames_KM = 0;
eval.KM_place_index = 0;
// Perform all sorts
handleChapter5Sorts(node, km_temp_inventory, outputsFulfilled, numOutputsFulfilled, eval);
}
else {
// Place the Keel Mango starting after the other placed items.
for (eval.KM_place_index = 2; eval.KM_place_index < 10; eval.KM_place_index++) {
// Don't allow current move to remove Thunder Rage
if (inventory.inventory[eval.KM_place_index] == Thunder_Rage) {
continue;
}
// Making a copy of the temp inventory for what it looks like after the allocation of the KM