Repository navigation
Expand file tree
/
Copy pathpet.cpp
More file actions
2000 lines (1874 loc) · 81.5 KB
/
Copy pathpet.cpp
File metadata and controls
2000 lines (1874 loc) · 81.5 KB
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 "pet.h"
#include "avatars.h"
#include "dex.h"
#include "moves.h"
#include "noart.h" // speciesHasArt(): the egg pool skips what cannot be drawn
#include "audio.h"
#include "ckpt.h" // the alternating CRC-checked record format, shared with party.cpp
#include <stddef.h>
// Reads a blob that may be LONGER than the array we are reading it into.
//
// Preferences::getBytes reads the stored length FIRST and, if it exceeds the
// caller's buffer, logs and returns 0 WITHOUT COPYING ANYTHING:
//
// if (len > maxLen) { log_e("not enough space in buffer"); return 0; }
//
// Growing the dex was always safe -- a short blob lands in the front of a bigger
// array and the rest keeps its zero initialiser, which is what every migration
// here relies on. SHRINKING was not: flashing a build with a smaller DEX_COUNT,
// GYM_REGIONS or REGION_COUNT over a newer save left dexReg, dexShinyReg, the
// badge arrays and eggByRegion entirely ZERO. The creature survived, being all
// scalars, while the Pokedex and every badge past Kanto quietly vanished --
// which from the player's side is their game rolling back.
//
// The PREFIX is the right thing to keep: dex bit n means the same species
// whatever the table grew to afterwards, and region n is the same region.
// Only the tail we have no room for is dropped, which is data about content
// this build does not have anyway.
//
// The emulator's Preferences stub used to truncate rather than refuse, so no
// test could see any of this -- see tools/emu/Preferences.h.
static void loadBlob(Preferences &p, const char *key, void *dst, size_t n) {
size_t have = p.getBytesLength(key);
if (!have) return; // absent: keep the initialiser
if (have <= n) { p.getBytes(key, dst, n); return; }
uint8_t *tmp = (uint8_t *)malloc(have);
if (!tmp) return; // rather no read than a half one
if (p.getBytes(key, tmp, have) == have) memcpy(dst, tmp, n);
free(tmp);
}
// --- the creature ----------------------------------------------------------
static constexpr uint32_t PET_CORE_MAGIC = 0x31504B54UL; // "TKP1"
// v2 appended the pending party handover; see PET_TAIL_* below. v1 records
// still read -- they simply have no tail, which is exactly "nothing waiting for
// a party slot", the right default.
static constexpr uint16_t PET_CORE_VERSION = 2;
// Generous enough to read a record from a later build; see ckptRead().
static constexpr size_t PET_CORE_CAP = 192;
// The fixed part of the record: byte-for-byte the v1 body, which is why a
// checkpoint already on a device still validates. PetCoreSnapshot below is
// exactly this prefix, and only PET_FIXED bytes of it are ever copied -- the
// struct's own sizeof is rounded up by its 4-byte alignment and those trailing
// bytes are not part of the format.
static constexpr size_t PET_FIXED = 70;
struct PetCoreSnapshot {
uint32_t magic;
uint16_t version;
uint16_t size;
uint32_t generation;
uint32_t ageMinutes;
uint32_t lastSeenEpoch;
int16_t speciesId;
int16_t eggTarget;
uint16_t medals;
uint8_t fullness, joy, energy, hygiene, poops, weight;
uint8_t ivAtk, ivDef, ivSpe, ivHp;
uint8_t trAtk, trDef, trSpe;
uint8_t moves[MOVE_SLOTS];
uint8_t lastLearnLevel;
uint8_t berryKnown, shiny, eggShiny, starterPick;
uint8_t evoPen, sleepAuto, retirePending, eggTaps;
uint8_t careMistakes, sleeping, lastEnd, frozen, bond;
char nick[12];
// v1 had one byte of tail padding here, before its trailing crc. Named rather
// than left implicit so the struct has no bytes the compiler chose and the
// append point is unambiguous: a new SCALAR goes here, taking this byte, and
// the record's version and PET_FIXED both move.
uint8_t pad0;
};
// EXACT, not "< 256". PET_FIXED is on-disk format -- it is what the crc covers
// and what a v1 blob's `size` implies -- so a field added above changes what
// every device already holds. Failing this assert is the reminder to read the
// append-only rule at the top of this section, then move the number
// deliberately and bump PET_CORE_VERSION.
static_assert(offsetof(PetCoreSnapshot, pad0) == PET_FIXED - 1,
"pet checkpoint fixed layout changed");
static_assert(sizeof(PetCoreSnapshot) >= PET_FIXED, "PET_FIXED overruns the struct");
// The v2 tail: the creature a finished ceremony handed over, still waiting for a
// party slot.
//
// It lives INSIDE the creature's own record rather than under a key of its own,
// and that is the entire point. update() calls snapshotForParty() and then
// newEgg(), which saves the new egg immediately -- but the handover itself was
// only ever in RAM (Pet::endedMon), and the party write does not happen until
// the player accepts a slot, which may be a banner or a whole chooser screen
// later. Power off in between and the creature was gone, with the save that
// erased it already committed. A 4-second hold on the power key at exactly that
// moment is an ordinary thing for a player to do.
//
// Two keys with a generation threshold cannot fix that without a two-phase
// commit: whichever order they are written in, there is a window where the
// handover is durable but the egg is not, or the reverse, and the recovery rule
// then has to distinguish "the egg never landed" from "this was consumed ages
// ago" -- which it cannot do from a generation number alone without eventually
// resurrecting a creature that is still alive. Putting it in the same blob as
// the egg means they commit together or not at all, and there is no window and
// no rule to get wrong.
//
// The PartyMon goes LAST because it grows: it has gained moves[] and then a
// whole care block, and Party::begin() migrates the party blob by length for
// that reason. Its stored length travels with it so the same prefix rule
// applies here.
static constexpr size_t PET_TAIL_KIND = PET_FIXED; // u8 ceremony kind
static constexpr size_t PET_TAIL_RSVD = PET_FIXED + 1; // u8 reserved, 2-byte aligns the next
static constexpr size_t PET_TAIL_MONLEN = PET_FIXED + 2; // u16 stored sizeof(PartyMon)
static constexpr size_t PET_TAIL_MON = PET_FIXED + 4; // the record itself
static constexpr size_t PET_BODY = PET_TAIL_MON + sizeof(PartyMon);
static_assert(PET_BODY + CKPT_CRC <= PET_CORE_CAP, "raise PET_CORE_CAP");
// Takes a validated blob and copies whatever body prefix the stored record and
// this build have in common. Anything this build has that the record did not
// keeps its zero initialiser, and anything the record has that this build does
// not is dropped -- the append-only rule is what makes both directions safe.
static void petCoreFromBytes(const uint8_t *buf, uint16_t n,
PetCoreSnapshot &snapshot) {
size_t body = n - CKPT_CRC;
if (body > PET_FIXED) body = PET_FIXED;
snapshot = PetCoreSnapshot();
memcpy(&snapshot, buf, body);
}
static bool readPetCore(Preferences &prefs, const char *key,
PetCoreSnapshot &snapshot) {
uint8_t buf[PET_CORE_CAP];
uint16_t n = ckptRead(prefs, key, PET_CORE_MAGIC, buf, sizeof(buf));
if (!n) return false;
petCoreFromBytes(buf, n, snapshot);
return true;
}
// --- the player ------------------------------------------------------------
// Everything in a save that OUTLIVES the creature: the trainer, the Pokedex,
// the badges, the daily streak, the medal total and the minigame records. That
// was ~25 more keys written one after another, so a cut between them could
// leave a badge won without the dex entry that came with it, or a medal counted
// on the creature but not in the lifetime total. The same fault as issue #3,
// one layer out, and it survived the first fix because that fix only covered
// the creature.
//
// Unlike the creature's, this record CANNOT be a struct. dexReg is sized by
// DEX_COUNT, eggByRegion by REGION_COUNT and the badge arrays by GYM_REGIONS,
// and this project grows all three -- the dex has gone 151 -> 386 -> 1025. A
// struct would move every field after whichever array grew, and that is the one
// thing the append-only rule cannot absorb.
//
// So the DIMENSIONS TRAVEL IN THE HEADER and each array is copied by its own
// prefix rule: a stored array shorter than this build's lands at the front and
// the tail keeps its zero initialiser, a longer one is truncated. That is
// exactly what loadBlob() does per key -- dex bit n means the same species
// however big the table got -- applied inside one atomic blob instead of across
// twenty-five separate writes.
static constexpr uint32_t PLAYER_MAGIC = 0x31594B54UL; // "TKY1"
static constexpr uint16_t PLAYER_VERSION = 2; // v2 appended memoHi; see below
// Header + every scalar, before the arrays begin.
//
// THIS LENGTH NOW TRAVELS IN THE RECORD, at buf[19], for exactly the reason the
// array dimensions already do. Appending a scalar moves where the arrays start,
// and loadPlayerSnapshot() validates `need` against the stored body length -- so
// simply raising this number would make every EXISTING record fail that check and
// fall back to the legacy keys, which is the torn-write path the checkpoint exists
// to replace. A v1 record has a reserved ZERO there, which is the sentinel for
// "the fixed block was 42", so nothing already on a device needs to know.
//
// So a future scalar goes at the end of the block, this number moves, and both
// directions keep working. No magic bump, no version check.
static constexpr size_t PLAYER_FIXED_V1 = 42;
static constexpr size_t PLAYER_FIXED = 44; // v2: + memoHi at offset 42
static constexpr size_t PLAYER_CAP = 512;
static constexpr size_t PLAYER_DEX_BYTES = (DEX_COUNT + 7) / 8;
// DERIVED from the tables, never restated: CLAUDE.md § "sizeof(PartyMon) is
// load-bearing in four places" is what a literal here costs. Failing this is
// the signal to raise PLAYER_CAP, not to trim the record.
static constexpr size_t PLAYER_MAX =
PLAYER_FIXED + 2 * PLAYER_DEX_BYTES + 4 * (GYM_REGIONS - 1) +
2 * REGION_COUNT + 12 /* trainerName */ + CKPT_CRC;
static_assert(PLAYER_MAX <= PLAYER_CAP, "raise PLAYER_CAP for the player record");
// A bounds-checked cursor over the variable tail of a blob. Overrunning sets
// `bad` rather than running off the end of the buffer.
bool Pet::savePlayerSnapshot() {
const uint32_t nextGen = playerGeneration + 1;
uint8_t buf[PLAYER_CAP] = {};
ckptWr16(buf + 12, (uint16_t)sizeof(dexReg)); // u16: a dex byte count outgrew 255 long ago
buf[14] = REGION_COUNT;
buf[15] = GYM_REGIONS - 1; // the length of badgesX / badgesHardX
buf[16] = (uint8_t)sizeof(trainerName);
buf[17] = avatar;
buf[18] = region;
// The length of the scalar block, i.e. where the arrays start. Was a reserved
// zero, which is precisely what makes it usable: every record already written
// reads 0 here and 0 means PLAYER_FIXED_V1.
buf[19] = (uint8_t)PLAYER_FIXED;
ckptWr16(buf + 20, badges);
ckptWr16(buf + 22, badgesHard);
ckptWr16(buf + 24, streak);
ckptWr16(buf + 26, bestStreak);
ckptWr32(buf + 28, lastCareDay);
ckptWr16(buf + 32, totalMedals);
ckptWr16(buf + 34, lastMilestone);
ckptWr16(buf + 36, gameHi);
ckptWr16(buf + 38, strHi);
ckptWr16(buf + 40, spdHi);
ckptWr16(buf + 42, memoHi); // v2
CkptCursor cur{ buf, PLAYER_FIXED, sizeof(buf) - CKPT_CRC };
cur.put(dexReg, sizeof(dexReg));
cur.put(dexShinyReg, sizeof(dexShinyReg));
cur.put(badgesX, sizeof(badgesX));
cur.put(badgesHardX, sizeof(badgesHardX));
cur.put(eggByRegion, sizeof(eggByRegion));
cur.put(trainerName, sizeof(trainerName));
if (cur.bad) { // PLAYER_MAX static_asserts this cannot happen; say so if it does
Serial.println("save: player record does not fit PLAYER_CAP");
return false;
}
uint16_t total = ckptSeal(buf, cur.at, PLAYER_MAGIC, PLAYER_VERSION, nextGen);
const char *key = ckptSlot(nextGen, "plyA", "plyB");
const size_t written = prefs.putBytes(key, buf, total);
if (written != total) {
Serial.printf("save: %s wrote %u/%u bytes\n", key, (unsigned)written, (unsigned)total);
return false;
}
// Read back into the same buffer and re-check, exactly as the creature's does.
uint16_t n = ckptRead(prefs, key, PLAYER_MAGIC, buf, sizeof(buf));
if (n != total || ckptRd32(buf + 8) != nextGen) {
Serial.printf("save: %s read-back failed (%u/%u bytes)\n", key, (unsigned)n, (unsigned)total);
return false;
}
playerGeneration = nextGen;
return true;
}
bool Pet::loadPlayerSnapshot() {
uint8_t buf[PLAYER_CAP];
uint16_t n = ckptReadNewest(prefs, "plyA", "plyB", PLAYER_MAGIC, buf, sizeof(buf));
if (!n) return false;
const size_t dexBytes = ckptRd16(buf + 12);
const size_t regionN = buf[14];
const size_t badgeN = buf[15];
const size_t nameN = buf[16];
// Check the dimensions BEFORE copying a single byte. A record that disagrees
// with its own length is rejected whole rather than half-applied over the
// legacy values already loaded -- half-applied is the very mixture this
// record exists to prevent. A body LONGER than the dimensions describe is
// fine and ignored: that is a later build's appended field.
const size_t body = n - CKPT_CRC;
// Where the arrays start, according to the RECORD rather than this build. A
// reserved zero means v1's 42; see the note above PLAYER_FIXED. Clamped, so a
// corrupt byte here cannot walk the cursor off into the arrays.
size_t fixed = buf[19] ? (size_t)buf[19] : PLAYER_FIXED_V1;
if (fixed < PLAYER_FIXED_V1 || fixed > body) {
Serial.println("save: player checkpoint scalar block length is not believable");
return false;
}
const size_t need = fixed + 2 * dexBytes + 4 * badgeN + 2 * regionN + nameN;
if (!regionN || need > body) {
Serial.println("save: player checkpoint dimensions do not match its length");
return false;
}
playerGeneration = ckptRd32(buf + 8);
avatar = buf[17];
region = buf[18];
badges = ckptRd16(buf + 20);
badgesHard = ckptRd16(buf + 22);
streak = ckptRd16(buf + 24);
bestStreak = ckptRd16(buf + 26);
lastCareDay = ckptRd32(buf + 28);
totalMedals = ckptRd16(buf + 32);
lastMilestone = ckptRd16(buf + 34);
gameHi = ckptRd16(buf + 36);
strHi = ckptRd16(buf + 38);
spdHi = ckptRd16(buf + 40);
// Only if the record actually HAS it. A v1 record's offset 42 is the first byte
// of the Pokedex bitmap, so reading it unconditionally would invent a memory
// record out of dex bits.
if (fixed >= PLAYER_FIXED) memoHi = ckptRd16(buf + 42);
CkptCursor cur{ buf, fixed, body };
cur.take(dexReg, sizeof(dexReg), dexBytes);
cur.take(dexShinyReg, sizeof(dexShinyReg), dexBytes);
cur.take(badgesX, sizeof(badgesX), badgeN * 2);
cur.take(badgesHardX, sizeof(badgesHardX), badgeN * 2);
cur.take(eggByRegion, sizeof(eggByRegion), regionN * 2);
cur.take(trainerName, sizeof(trainerName), nameN);
trainerName[sizeof(trainerName) - 1] = 0;
// REGION_ALL is the LAST entry of the table and is stored RAW, so a save from
// a build with fewer regions has a number that now means somebody else --
// with Galar and Paldea appended, ALL moved 7 -> 9 and a stored 7 became a
// region with no sprite pack. The record carries the table size it was
// written with so that cannot happen; this is the same rule as the "regn"
// key, asked of the record that is actually being believed.
if (regionN != REGION_COUNT && region >= (uint8_t)(regionN - 1)) region = REGION_ALL;
if (region >= REGION_COUNT) region = REGION_ALL;
if (avatar >= AVATAR_COUNT) avatar = 0; // a save from when there were four
return true;
}
void Pet::begin() {
// CHECKED. This used to set opened = true regardless, so a namespace that
// would not open left every write failing forever with nothing to show for it
// -- getBool("init") returns its default, the player is handed a fresh egg,
// and saving silently does nothing for as long as they keep playing. It is
// still a fresh egg now, because there is nothing to load, but saveHealthy()
// is false and the panel says so.
opened = prefs.begin("tamapoke", false);
if (!opened)
Serial.println("save: NVS namespace would not open -- NOTHING WILL BE SAVED");
saveGeneration = 0;
playerGeneration = 0;
// Zeroed BEFORE the branch below, not inside load(): getBytes() leaves its
// destination untouched when the key is missing, and the fresh-install path
// returns without ever calling load(). Without this a begin() after a factory
// reset keeps the old Pokedex alive in RAM -- the firmware reboots on WIPE so
// it never showed there, but anything calling begin() twice would see it, and
// Party::begin() already guards the same way for the same reason.
memset(badgesX, 0, sizeof(badgesX));
memset(badgesHardX, 0, sizeof(badgesHardX));
memset(dexReg, 0, sizeof(dexReg));
memset(dexShinyReg, 0, sizeof(dexShinyReg));
for (int i = 0; i < REGION_COUNT; i++) eggByRegion[i] = 0;
if (!prefs.getBool("init", false)) {
prefs.putBool("init", true);
newEgg();
} else {
load();
}
lastTick = millis();
}
void Pet::newEgg() {
ceremony = CER_NONE;
neglectTicks = 0;
weight = 0;
speciesId = -1;
prevSpeciesId = -1;
for (int i = 0; i < REGION_COUNT; i++) eggByRegion[i] = 0;
eggTarget = pickEggSpecies(); // especie oculta segun rareza y pokedex
eggByRegion[region % REGION_COUNT] = eggTarget;
starterPick = (registeredCount() == 0); // primera partida: el jugador elige inicial
// sorteo shiny: 1/48 base, mejor con despedida y con racha/vinculo altos
int shinyBase = (lastEnd == CER_FAREWELL ? 24 : 48) - careBonus();
if (shinyBase < 8) shinyBase = 8;
eggShiny = (random(shinyBase) == 0);
// The debt lands on the creature about to hatch, and is spent doing so --
// it is a one-day penalty, not a running total that compounds each retire.
evoPen = retirePending ? EVO_PENALTY_LEVELS : 0;
retirePending = false;
eggTaps = 0;
fullness = 80;
joy = 80;
energy = 80;
hygiene = 100;
poops = 0;
ageMinutes = 0;
careMistakes = 0;
mistakeCooldown = 0;
sleeping = false;
frozen = false;
save();
}
// progresion offline: el tiempo paso aunque estuviera apagado, pero con
// piedad — las barras bajan con suelo en 15 (vuelve hambriento, no muerto),
// sin descuidos ni escapadas en ausencia
static uint8_t dropTo(uint8_t v, uint8_t d, uint8_t fl) {
if (v <= fl) return v;
return (v - fl > d) ? v - d : fl;
}
// See the essay above ClockVerdict in pet.h for why each of these is a refusal
// rather than a clamp.
ClockVerdict clockVerdict(uint32_t seen, uint32_t now, uint32_t *minsOut) {
if (minsOut) *minsOut = 0;
// Not a time. The old code assigned this to lastSeenEpoch before testing it,
// which is how an unreadable RTC permanently lost the reference.
if (now == 0) return CLK_REJECT;
if (now < CLOCK_EPOCH_FLOOR) return CLK_REJECT;
if (!seen) return CLK_REBASE; // first ever reading: adopt it
if (now + CLOCK_BACK_SLACK_SECS < seen) return CLK_REBASE; // went backwards
if (now <= seen) return CLK_REBASE; // inside the drift slack
const uint32_t mins = (now - seen) / 60;
if (mins < 2) return CLK_REBASE; // nothing worth applying
if (mins > CLOCK_MAX_OFFLINE_MINS) return CLK_REBASE; // a fault, not a holiday
if (minsOut) *minsOut = mins;
return CLK_APPLY;
}
// An explicit set: the player typing a time in SETTINGS, or a host sending TIME.
// It deliberately does NOT judge plausibility -- somebody said so on purpose --
// but it still will not adopt a non-time, because doing so is pure loss: the old
// reference is discarded and nothing is stored in its place.
void Pet::setClock(uint32_t nowEpoch) {
if (!nowEpoch) return;
lastSeenEpoch = nowEpoch;
save(); // persiste ya: un corte de luz no pierde la referencia
}
void Pet::syncClock(uint32_t nowEpoch) {
uint32_t mins = 0;
const ClockVerdict verdict = clockVerdict(lastSeenEpoch, nowEpoch, &mins);
if (verdict == CLK_REJECT) {
// KEEP the reference. Nothing is written, so the next boot with a working
// clock measures from when the device was really last seen.
Serial.printf("clock: reading %u refused, keeping %u\n",
(unsigned)nowEpoch, (unsigned)lastSeenEpoch);
return;
}
lastSeenEpoch = nowEpoch;
if (verdict == CLK_REBASE) {
// A real time, but not a measurable absence: adopt it and age NOTHING. This
// is where an implausible jump lands, and it costs the player nothing -- age,
// bond, training and medals are all untouched.
if (mins == 0) Serial.printf("clock: rebased to %u\n", (unsigned)nowEpoch);
save();
return;
}
if (ceremony != CER_NONE || starterPick) {
save(); // sin tiempo que aplicar o aun eligiendo inicial
return;
}
for (uint32_t i = 0; i < mins; i++) {
ageMinutes++;
if (isEgg()) {
if (ageMinutes >= 3) hatch(); // eclosiona en tu ausencia
continue;
}
if (sleeping) { // descanso: baja lento y con suelo, igual que en vivo
energy = clamp100(energy + 6);
if (ageMinutes % 2 == 0) {
fullness = dropTo(fullness, 1, 30);
joy = dropTo(joy, 1, 35);
}
if (ageMinutes % 3 == 0) hygiene = dropTo(hygiene, 1, 45);
continue;
}
fullness = dropTo(fullness, 2, 15);
energy = dropTo(energy, 1, 15);
hygiene = dropTo(hygiene, 1, 15);
joy = dropTo(joy, 1, 15);
}
if (!isEgg()) {
if (!sleeping) { // durmiendo no ensucia
uint8_t p = poops + mins / 240;
poops = p > 3 ? 3 : p;
}
// la evolucion NO se aplica offline: queda lista y la dispara el usuario
// tocando al bicho cuando vuelve (para que vea la transformacion)
}
Serial.printf("offline: %u min aplicados (nv.%u)\n", mins, level());
save();
}
void Pet::update(uint32_t nowMs) {
// fin de ceremonia: la criatura se va y queda un huevo nuevo
if (ceremony != CER_NONE && millis() > ceremonyUntil) {
snapshotForParty(); // hand it over BEFORE newEgg() erases everything
newEgg();
return;
}
while (nowMs - lastTick >= PET_TICK_MS) {
lastTick += PET_TICK_MS;
tick();
}
}
void Pet::tick() {
if (ceremony != CER_NONE) return; // el tiempo se detiene en la despedida
if (starterPick) return; // la partida no empieza hasta elegir inicial: si el
// tiempo corriera aqui, el huevo eclosionaria solo a
// los 3 min con la especie sorteada y se perderia la
// eleccion del jugador
if (!frozen) ageMinutes++; // a revived companion does not age
if (isEgg()) {
if (ageMinutes >= 3) hatch(); // si no lo tocas, eclosiona solo a los 3 min
return;
}
applyAutoSleep(); // put down at 21:00 still goes to bed at 22:00
// el sueño es descanso: la energia se recupera y las necesidades bajan MUCHO
// mas lento que despierto y con suelo (amanece pidiendo algo de mimo, no a
// cero, sin descuidos ni escapadas). despierto: comida -2/min, hig/joy -1/min.
// El peso aun se quema y el descanso cuenta para la DEF (ver defTick).
if (sleeping) {
energy = clamp100(energy + 6);
if (weight > 0 && ageMinutes % 3 == 0) weight--;
if (ageMinutes % 2 == 0) { // ~4x mas lento que despierto
fullness = dropTo(fullness, 1, 30);
joy = dropTo(joy, 1, 35);
}
if (ageMinutes % 3 == 0) hygiene = dropTo(hygiene, 1, 45);
defTick(true); // descansar tambien es bienestar: cuenta para la DEF
checkMedals(); // aun puede cruzar un nivel por edad mientras duerme
if (++ticksSinceSave >= 5) pendingSave = true;
return;
}
if (ageMinutes % MINUTES_PER_LEVEL == 0) sfxPlay(SFX_LEVEL); // subio de nivel (despierto)
fullness = clamp100(fullness - 2);
energy = clamp100(energy - 1);
if (fullness > 40 && poops < 3 && random(100) < 15) poops++;
hygiene = clamp100(hygiene - 1 - 4 * poops);
// el sobrepeso da pereza: la energia cae el doble
if (weight > 50) energy = clamp100(energy - 1);
if (weight > 0 && ageMinutes % 3 == 0) weight--;
defTick(false); // la calma forja la defensa
int dJoy = -1;
if (fullness < 30) dJoy -= 2;
if (hygiene < 30) dJoy -= 2;
joy = clamp100(joy + dJoy);
// Descuido: dejar una estadistica por los suelos cuenta como error de
// cuidado (con enfriamiento para no contar el mismo descuido cada minuto)
if (mistakeCooldown > 0) mistakeCooldown--;
if (lowestStat() <= 10 && mistakeCooldown == 0) {
careMistakes++;
mistakeCooldown = 60;
if (bond > 1) bond--; // el descuido enfria el vinculo, pero sin arrasarlo:
// a -3 cada 30 min se perdia mucho mas de lo que se
// podia ganar en todo un dia y el vinculo se atascaba
}
checkMedals(); // la evolucion la dispara el usuario (canEvolveNow + tap), no el tick
checkLearnGates();
// abandono total: con TODO a cero durante una hora queda lista para escaparse;
// NO se va sola, la dispara el usuario con el boton (final triste, lo presencia)
if (inTotalNeglect()) {
if (neglectTicks < RUNAWAY_TICKS) neglectTicks++;
} else {
neglectTicks = 0; // un solo cuidado la salva
}
// ciclo completo (forma final + 7 dias): la despedida NO salta sola; queda
// lista (canFarewellNow) y la dispara el usuario con el boton, para que la vea
// autoguardado periodico: NO escribir a flash aqui (corre dentro del loop,
// mientras se anima); solo marcar y dejar que el loop lo vuelque al atenuar
if (++ticksSinceSave >= 5) pendingSave = true;
}
// Copies the creature into endedMon so it can be offered a party slot, since
// newEgg() is about to wipe every field. Only the two endings the player CHOSE
// qualify: a runaway ran off after an hour of total neglect, and letting it
// come back on the team would remove the cost from the one ending that has any.
// Brings a banked creature back as the live pet, frozen.
void Pet::reviveFrom(const PartyMon &m) {
if (m.empty()) return;
ceremony = CER_NONE;
neglectTicks = 0;
speciesId = m.dex;
prevSpeciesId = -1;
eggTaps = 0;
starterPick = false;
shiny = m.shiny != 0;
ivAtk = m.ivAtk; ivDef = m.ivDef; ivSpe = m.ivSpe; ivHp = m.ivHp;
trAtk = m.trAtk; trDef = m.trDef; trSpe = m.trSpe;
for (int i = 0; i < MOVE_SLOTS; i++) moves[i] = m.moves[i];
// its banked level expressed as an age, so level() needs no special case
ageMinutes = (uint32_t)(m.level ? m.level - 1 : 0) * MINUTES_PER_LEVEL;
lastLearnLevel = level(); // do not replay every gate it already passed
learnQCount = 0;
medals = m.medals;
careMistakes = 0;
mistakeCooldown = 0;
sleeping = false;
bond = 0;
bondToday = 0;
berryKnown = false;
weight = 0;
fullness = joy = energy = 80;
hygiene = 100;
poops = 0;
frozen = true;
strncpy(nick, m.nick, sizeof(nick) - 1);
nick[sizeof(nick) - 1] = 0;
registerSpecies(speciesId);
save();
}
// THE single place a live pet becomes a stored record. The farewell, a focus
// swap and a wild capture all end up here; three callers each keeping their own
// copy of this is the exact shape of CLAUDE.md § "A rule enforced in one path
// but not its twin", and a field forgotten in one of them would silently blank
// that field for whichever creature took that route.
PartyMon Pet::toPartyMon() const {
PartyMon m;
m.dex = speciesId;
m.level = level();
m.medals = medals;
m.ivAtk = ivAtk;
m.ivDef = ivDef;
m.ivSpe = ivSpe;
m.ivHp = ivHp;
m.trAtk = trAtk;
m.trDef = trDef;
m.trSpe = trSpe;
m.shiny = shiny ? 1 : 0;
for (int i = 0; i < MOVE_SLOTS; i++) m.moves[i] = moves[i];
strncpy(m.nick, nick, sizeof(m.nick) - 1);
m.nick[sizeof(m.nick) - 1] = 0;
m.stateVersion = 1;
m.fullness = fullness;
m.joy = joy;
m.energy = energy;
m.hygiene = hygiene;
m.poops = poops;
m.weight = weight;
m.bond = bond;
m.berryKnown = berryKnown ? 1 : 0;
m.careMistakes = careMistakes;
m.evoDeclinedLv = evoDeclinedLv;
m.lastLearnLevel = lastLearnLevel;
m.ageMinutes = ageMinutes;
return m;
}
// Make a stored creature the focused one. reviveFrom()'s twin, and the two are
// deliberately different: that one hands back a frozen companion, this one
// hands back a creature that carries on living.
void Pet::switchTo(const PartyMon &m) {
if (m.empty()) return;
ceremony = CER_NONE;
neglectTicks = 0;
speciesId = m.dex;
prevSpeciesId = -1;
eggTaps = 0;
starterPick = false;
shiny = m.shiny != 0;
ivAtk = m.ivAtk; ivDef = m.ivDef; ivSpe = m.ivSpe; ivHp = m.ivHp;
trAtk = m.trAtk; trDef = m.trDef; trSpe = m.trSpe;
for (int i = 0; i < MOVE_SLOTS; i++) moves[i] = m.moves[i];
medals = m.medals;
mistakeCooldown = 0;
sleeping = false;
sleepAuto = SLEEP_NONE;
bondToday = 0;
learnQCount = 0;
frozen = false; // the whole point: it ages and levels again
if (m.hasCareState()) {
ageMinutes = m.ageMinutes;
fullness = m.fullness;
joy = m.joy;
energy = m.energy;
hygiene = m.hygiene;
poops = m.poops;
weight = m.weight;
bond = m.bond;
berryKnown = m.berryKnown != 0;
careMistakes = m.careMistakes;
evoDeclinedLv = m.evoDeclinedLv;
lastLearnLevel = m.lastLearnLevel;
} else {
// Banked before care state was stored, so its banked level is all there is.
// Starting it fresh is the only honest reading -- inventing a care history
// would be worse than admitting the save never had one.
ageMinutes = (uint32_t)(m.level ? m.level - 1 : 0) * MINUTES_PER_LEVEL;
fullness = joy = energy = 80;
hygiene = 100;
poops = 0;
weight = 0;
bond = 0;
berryKnown = false;
careMistakes = 0;
evoDeclinedLv = 0;
lastLearnLevel = level(); // do not replay every gate it already passed
}
strncpy(nick, m.nick, sizeof(nick) - 1);
nick[sizeof(nick) - 1] = 0;
registerSpecies(speciesId);
save();
}
void Pet::snapshotForParty() {
endedKind = CER_NONE;
if (isEgg()) return;
if (ceremony != CER_FAREWELL && ceremony != CER_RELEASE) return;
// An EARLY retire gives the creature up for good -- it is not banked at all.
// Retiring one that has EARNED its farewell still banks it, because that is
// simply the farewell reached by another button. retirePending is still set
// here: update() snapshots before newEgg() spends it, and that ordering is
// what this depends on, so retire_test drives the real update() rather than
// calling the two halves by hand.
if (retireIsEarly()) return;
endedMon = toPartyMon();
endedKind = ceremony;
// Deliberately NOT saved here. update() calls this and then newEgg(), whose
// save() writes the handover into the same checkpoint blob as the new egg --
// so the creature being banked and the creature replacing it commit together.
// Saving here as well would only add a write that could tear against that one.
}
// vuelca el guardado periodico pendiente (lo llama el loop en un momento sin
// animacion para que el paron de la escritura a flash no se vea)
void Pet::saveNow() { save(); }
void Pet::flushSave() {
if (pendingSave) save();
}
// La calma forja la defensa: cada hora de bienestar (descansando, o despierto
// con todo >= 40) da +1 de DEF, hasta el tope que permita el IV.
//
// Antes pedia 12 h SEGUIDAS y CUALQUIER desliz ponia el contador a cero, ademas
// de no contar el sueno. Simulando una vida entera (3 dias) eso daba 1 punto al
// jugador teoricamente perfecto (uno que actue cada minuto durante 72 h) y 0 a
// todos los demas, incluido uno que atienda cada 15 min: la comida cae 2/min,
// asi que quien no pase por el bicho cada media hora esta SIEMPRE por debajo de
// 40 y el contador no arrancaba nunca. La DEF era, en la practica, inentrenable.
// Ahora acumula en vez de resetear: un descuido cuesta los minutos malos, no
// todo el progreso.
void Pet::defTick(bool resting) {
if (!resting && lowestStat() < 40) return;
if (++goodTicks < DEF_TRAIN_TICKS) return;
goodTicks = 0;
if (trDef < trMaxDef()) trDef++;
}
// quedan miembros sin registrar en la linea evolutiva de esta base?
bool Pet::lineHasUnregistered(int16_t base) const {
int16_t cur = base;
for (int guard = 0; cur >= 1 && cur <= DEX_COUNT && guard < 6; guard++) {
if (!isRegistered(cur)) return true;
if (cur == DEX_EEVEE) {
int16_t opts[EEVEE_EVO_COUNT];
uint8_t n = eeveeOptions(opts);
for (uint8_t i = 0; i < n; i++)
if (!isRegistered(opts[i])) return true;
return false;
}
cur = DEX_TBL[cur].evolvesTo;
}
return false;
}
uint8_t Pet::eeveeOptions(int16_t *out) const {
uint8_t n = 0;
for (uint8_t i = 0; i < EEVEE_EVO_COUNT; i++) {
int16_t b = EEVEE_EVOS[i];
if (b < 1 || b > DEX_COUNT) continue;
if (!speciesHasArt(b)) continue; // no art anywhere
if (!regionAvailable(regionOfDex(b))) continue; // pack not on the card
out[n++] = b;
}
return n;
}
uint8_t Pet::eggRarity() const {
return (eggTarget >= 1 && eggTarget <= DEX_COUNT) ? DEX_TBL[eggTarget].rarity : R_COMUN;
}
// elige la especie del huevo: tirada de rareza (mejorada por una despedida
// completa, castigada por una escapada) y sesgo hacia lineas incompletas
// Room for the candidate list. A whole rarity tier of a 386-species dex is far
// more than the 80 the Kanto-only build needed.
#define CAND_MAX 260
uint16_t gRegionArt = 0xFFFF; // everything, until the SD narrows it
bool regionAvailable(uint8_t r) {
if (r >= REGION_COUNT) return false;
if (r == REGION_ALL) { // the mixed pool: any pack will do
for (uint8_t i = 0; i < REGION_COUNT; i++)
if (i != REGION_ALL && (gRegionArt & (uint16_t)(1u << i))) return true;
return false;
}
return (gRegionArt & (uint16_t)(1u << r)) != 0;
}
// THE single answer to "can this player be shown this species". The egg pool
// and every evolution ask it; having two opinions is how EEVEE's branch was
// filtered for years while the linear path was not.
bool speciesShowable(int16_t d) {
return d >= 1 && d <= DEX_COUNT && speciesHasArt(d) &&
regionAvailable(regionOfDex(d));
}
uint8_t regionOfDex(int16_t d) {
for (uint8_t i = 0; i < REGION_COUNT; i++) {
if (i == REGION_ALL) continue;
if (d >= REGIONS[i].lo && d <= REGIONS[i].hi) return i;
}
return REGION_ALL;
}
int16_t regionArtProbe(uint8_t region, uint8_t slot) {
if (region >= REGION_COUNT || region == REGION_ALL || slot > 2) return 0;
const RegionInfo &info = REGIONS[region];
int16_t target = slot == 0 ? info.lo : slot == 1 ? (int16_t)((info.lo + info.hi) / 2)
: info.hi;
int16_t span = info.hi - info.lo;
for (int16_t distance = 0; distance <= span; distance++) {
int16_t lower = target - distance;
if (lower >= info.lo && speciesHasArt(lower)) return lower;
int16_t upper = target + distance;
if (distance && upper <= info.hi && speciesHasArt(upper)) return upper;
}
return 0;
}
uint8_t nextAvailableRegion(uint8_t from) {
for (uint8_t i = 1; i <= REGION_COUNT; i++) {
uint8_t r = (uint8_t)((from + i) % REGION_COUNT);
if (regionAvailable(r)) return r;
}
return from; // nothing available anywhere: stay put
}
// The region to actually hatch from. Normally the player's own, but a card can
// be swapped under a save: rather than rewrite their choice (which would lose
// it silently the moment they put the right card back), the CHOICE is kept and
// only the roll falls through to somewhere playable.
static uint8_t eggRegionFallback(uint8_t want) {
if (regionAvailable(want)) return want;
for (uint8_t i = 0; i < REGION_COUNT; i++)
if (i != REGION_ALL && regionAvailable(i)) return i;
return want; // no art anywhere: behave as we always did
}
int16_t Pet::pickEggSpecies() {
const uint8_t use = eggRegionFallback(region % REGION_COUNT);
const RegionInfo &rg = REGIONS[use];
// primera partida: inicial clasico -- del region elegida, so a Johto run
// starts with a Johto starter rather than a Kanto one
if (registeredCount() == 0) {
return rg.starters[random(rg.starterCount)];
}
uint8_t tier = R_COMUN;
if (lastEnd != CER_RUNAWAY) {
bool blessed = (lastEnd == CER_FAREWELL);
int rare = (blessed ? 45 : 27) + careBonus();
int leg = (registeredCount() >= 25) ? (blessed ? 10 : 3) + careBonus() / 3 : 0;
int r = random(100);
if (r < leg) tier = R_LEGENDARIO;
else if (r < leg + rare) tier = R_RARO;
}
// candidatos del tier con linea incompleta; si no hay, baja de tier;
// si la pokedex del tier esta completa, vale cualquiera del tier
for (int pass = 0; pass < 2; pass++) {
for (int t = tier; t >= R_COMUN; t--) {
int16_t cand[CAND_MAX];
int n = 0;
for (int16_t d = rg.lo; d <= rg.hi && n < CAND_MAX; d++) {
if (DEX_TBL[d].rarity != t) continue;
if (pass == 0 && !lineHasUnregistered(d)) continue;
// ALL spans every region, so filter per species: a missing Sinnoh pack
// must not put a Sinnoh creature in a mixed egg.
if (!regionAvailable(regionOfDex(d))) continue;
// And a species with no art ANYWHERE never hatches, pack or no pack --
// it would be a creature that can only ever draw as a number. It keeps
// its dex slot; it is simply not something an egg can contain.
if (!speciesHasArt(d)) continue;
cand[n++] = d;
}
if (n > 0) return cand[random(n)];
}
}
return rg.starters[random(rg.starterCount)]; // inalcanzable, por si acaso
}
// Rolls a species of a GIVEN tier inside a region. Used when the player changes
// region while an egg is waiting: the rarity they were granted is kept and only
// the region changes, so switching cannot be farmed for a legendary.
int16_t Pet::rollInRegion(uint8_t r, uint8_t tier) {
const RegionInfo &rg = REGIONS[eggRegionFallback(r % REGION_COUNT)];
for (int t = tier; t >= R_COMUN; t--) {
int16_t cand[CAND_MAX];
int n = 0;
for (int16_t d = rg.lo; d <= rg.hi && n < CAND_MAX; d++)
if (DEX_TBL[d].rarity == t && regionAvailable(regionOfDex(d)) &&
speciesHasArt(d)) cand[n++] = d;
if (n) return cand[random(n)];
}
return rg.starters[0]; // a region with nothing in it cannot happen
}
// Changing region swaps the WAITING egg to that region's creature.
//
// Without this the setting would look broken: you would pick Johto and still
// hatch a Rattata, because the species is rolled when the egg appears and not
// when it cracks. Two rules stop it becoming a re-roll button:
//
// 1. The rarity tier is kept. Only which species of that tier changes, so
// toggling can never be farmed for a legendary.
// 2. Each region's answer is REMEMBERED for this egg. Switching back shows
// the same creature again, so there is nothing to gain by flipping.
//
// A hatched creature is untouched -- this only ever moves an egg.
void Pet::setRegion(uint8_t r) {
r %= REGION_COUNT;
// The sprite pack is a real gate, not a hint: without it the region is not
// selectable at all. The chooser still SHOWS it, greyed and with a reason --
// hiding it outright is how Johto and Hoenn once came to look absent when
// they were built and reachable all along.
if (!regionAvailable(r)) return;
if (r == region) return;
uint8_t old = region;
region = r;
if (isEgg() && eggTarget >= 1) {
if (old < REGION_COUNT) eggByRegion[old] = eggTarget;
int16_t known = eggByRegion[r];
eggTarget = known >= 1 ? known : rollInRegion(r, eggRarity());
eggByRegion[r] = eggTarget;
}
save();
}
void Pet::registerSpecies(int16_t dex) {
if (dex < 1 || dex > DEX_COUNT) return;
dexReg[(dex - 1) >> 3] |= (1 << ((dex - 1) & 7));
if (shiny) dexShinyReg[(dex - 1) >> 3] |= (1 << ((dex - 1) & 7));
}
// la racha y el vinculo mejoran el sorteo del huevo (0..~14)
int Pet::careBonus() const {
int s = streak > 30 ? 30 : streak;
return s / 3 + bond / 25;
}
// primer cuidado del dia: avanza la racha y afianza el vinculo
void Pet::registerCare() {
if (isEgg() || ceremony != CER_NONE) return;
uint32_t d = today();
if (d == 0 || d == lastCareDay) return; // sin reloj, o ya conto hoy
if (lastCareDay == 0 || d == lastCareDay + 1) {
streak++;
} else {
streak = 1; // hubo un hueco de dias
lastMilestone = 0;
}
lastCareDay = d;
bondToday = 0;
if (streak > bestStreak) bestStreak = streak;
bond = clamp100(bond + 4);
uint16_t ms = (streak >= 100) ? 100 : (streak >= 30) ? 30
: (streak >= 7) ? 7 : (streak >= 3) ? 3 : 0;
if (ms > lastMilestone) {
lastMilestone = ms;
milestoneUntil = millis() + 4500;
}
checkMedals();
save();
}
void Pet::addBond(uint8_t amt) {
if (bondToday >= 20) return; // tope diario: el vinculo no se farmea
bond = clamp100(bond + amt);
bondToday += amt;
}
void Pet::checkMedals() {
if (isEgg()) return;
uint16_t before = medals;
if (level() >= 10) medals |= MED_LV10;
if (level() >= 25) medals |= MED_LV25;
if (level() >= 50) medals |= MED_LV50;
if (berryKnown) medals |= MED_BERRY;
if (streak >= 7) medals |= MED_STREAK7;
if (bond >= 100) medals |= MED_BOND;
if (DEX_TBL[speciesId].evolvesTo == 0) medals |= MED_FINAL;
if (weight == 0 && level() >= 5 && careMistakes == 0) medals |= MED_FIT;
uint16_t gained = medals & ~before;
if (gained) {
for (uint16_t m = gained; m; m &= (m - 1)) totalMedals++;
newMedal = gained;
medalUntil = millis() + 4000;
if (!sleeping) sfxPlay(SFX_MEDAL);
save();
}
}