forked from fribbels/hsr-optimizer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.js
811 lines (687 loc) · 26.2 KB
/
db.js
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
import { create } from 'zustand'
import objectHash from 'object-hash'
import { OptimizerTabController } from 'lib/optimizerTabController'
import { RelicAugmenter } from 'lib/relicAugmenter'
import { Constants, DEFAULT_STAT_DISPLAY, RelicSetFilterOptions } from 'lib/constants.ts'
import { getDefaultForm } from 'lib/defaultForm'
import { Utils } from 'lib/utils'
import { SaveState } from 'lib/saveState'
import { Message } from 'lib/message'
import { OptimizerMenuIds } from 'components/optimizerTab/FormRow.tsx'
const state = {
relics: [],
characters: [],
metadata: {}, // generated, not saved
relicsById: {},
globals: {},
scorerId: undefined,
}
// This string is replaced by /dreary-quibbles by github actions, don't change
const BASE_PATH = '/hsr-optimizer'
export const AppPages = {
OPTIMIZER: 'OPTIMIZER',
CHARACTERS: 'CHARACTERS',
RELICS: 'RELICS',
IMPORT: 'IMPORT',
GETTING_STARTED: 'GETTING_STARTED',
CHANGELOG: 'CHANGELOG',
RELIC_SCORER: 'RELIC_SCORER',
}
export const PageToRoute = {
[AppPages.OPTIMIZER]: BASE_PATH,
[AppPages.RELIC_SCORER]: BASE_PATH + '#scorer',
[AppPages.CHANGELOG]: BASE_PATH + '#changelog',
[AppPages.GETTING_STARTED]: BASE_PATH + '#getting-started',
}
export const RouteToPage = {
[PageToRoute[AppPages.OPTIMIZER]]: AppPages.OPTIMIZER,
[PageToRoute[AppPages.RELIC_SCORER]]: AppPages.RELIC_SCORER,
[PageToRoute[AppPages.CHANGELOG]]: AppPages.CHANGELOG,
[PageToRoute[AppPages.GETTING_STARTED]]: AppPages.GETTING_STARTED,
}
// React usage
// let characterTabBlur = store(s => s.characterTabBlur);
// let setCharacterTabBlur = store(s => s.setCharacterTabBlur);
// Nonreactive usage
// store.getState().setRelicsById(relicsById)
window.store = create((set) => ({
optimizerGrid: undefined,
optimizerTabFocusCharacter: undefined,
characterTabFocusCharacter: undefined,
scoringAlgorithmFocusCharacter: undefined,
activeKey: RouteToPage[Utils.stripTrailingSlashes(window.location.pathname)] ? RouteToPage[Utils.stripTrailingSlashes(window.location.pathname) + window.location.hash] : AppPages.OPTIMIZER,
characters: [],
charactersById: {},
characterTabBlur: false,
conditionalSetEffectsDrawerOpen: false,
permutations: 0,
permutationsResults: 0,
permutationsSearched: 0,
relicsById: {},
scorerId: undefined,
scoringMetadataOverrides: {},
statDisplay: DEFAULT_STAT_DISPLAY,
optimizationInProgress: false,
optimizationId: undefined,
teammateCount: 0,
zeroPermutationModalOpen: false,
optimizerFormCharacterEidolon: 0,
optimizerFormSelectedLightCone: null,
optimizerFormSelectedLightConeSuperimposition: 1,
permutationDetails: {
Head: 0,
Hands: 0,
Body: 0,
Feet: 0,
PlanarSphere: 0,
LinkRope: 0,
HeadTotal: 0,
HandsTotal: 0,
BodyTotal: 0,
FeetTotal: 0,
PlanarSphereTotal: 0,
LinkRopeTotal: 0,
},
relicTabFilters: {
set: [],
part: [],
enhance: [],
mainStats: [],
subStats: [],
grade: [],
verified: [],
},
optimizerMenuState: {
[OptimizerMenuIds.characterOptions]: true,
[OptimizerMenuIds.relicAndStatFilters]: true,
[OptimizerMenuIds.teammates]: true,
},
setActiveKey: (x) => set(() => ({ activeKey: x })),
setCharacters: (x) => set(() => ({ characters: x })),
setCharactersById: (x) => set(() => ({ charactersById: x })),
setCharacterTabBlur: (x) => set(() => ({ characterTabBlur: x })),
setConditionalSetEffectsDrawerOpen: (x) => set(() => ({ conditionalSetEffectsDrawerOpen: x })),
setOptimizerTabFocusCharacter: (characterId) => set(() => ({ optimizerTabFocusCharacter: characterId })),
setCharacterTabFocusCharacter: (characterId) => set(() => ({ characterTabFocusCharacter: characterId })),
setScoringAlgorithmFocusCharacter: (characterId) => set(() => ({ scoringAlgorithmFocusCharacter: characterId })),
setPermutationDetails: (x) => set(() => ({ permutationDetails: x })),
setPermutations: (x) => set(() => ({ permutations: x })),
setPermutationsResults: (x) => set(() => ({ permutationsResults: x })),
setPermutationsSearched: (x) => set(() => ({ permutationsSearched: x })),
setRelicsById: (x) => set(() => ({ relicsById: x })),
setRelicTabFilters: (x) => set(() => ({ relicTabFilters: x })),
setScorerId: (x) => set(() => ({ scorerId: x })),
setScoringMetadataOverrides: (x) => set(() => ({ scoringMetadataOverrides: x })),
setStatDisplay: (x) => set(() => ({ statDisplay: x })),
setOptimizerMenuState: (x) => set(() => ({ optimizerMenuState: x })),
setOptimizationInProgress: (x) => set(() => ({ optimizationInProgress: x })),
setOptimizationId: (x) => set(() => ({ optimizationId: x })),
setTeammateCount: (x) => set(() => ({ teammateCount: x })),
setOptimizerFormCharacterEidolon: (x) => set(() => ({ optimizerFormCharacterEidolon: x })),
setOptimizerFormSelectedLightCone: (x) => set(() => ({ optimizerFormSelectedLightCone: x })),
setOptimizerFormSelectedLightConeSuperimposition: (x) => set(() => ({ optimizerFormSelectedLightConeSuperimposition: x })),
setZeroPermutationsModalOpen: (x) => set(() => ({ zeroPermutationModalOpen: x })),
}))
export const DB = {
getGlobals: () => state.globals,
getMetadata: () => state.metadata,
setMetadata: (x) => state.metadata = x,
getCharacters: () => window.store.getState().characters,
getCharacterById: (id) => window.store.getState().charactersById[id],
setCharacters: (x) => {
const charactersById = {}
for (const character of x) {
charactersById[character.id] = character
}
assignRanks(x)
const newCharacterArray = [...x]
window.store.getState().setCharacters(newCharacterArray)
window.store.getState().setCharactersById(charactersById)
},
setCharacter: (x) => {
const charactersById = window.store.getState().charactersById
charactersById[x.id] = x
window.store.getState().setCharactersById(charactersById)
},
addCharacter: (x) => {
const characters = DB.getCharacters()
characters.push(x)
DB.setCharacters(characters)
},
insertCharacter: (id, index) => {
console.log('insert', id, index)
const characters = DB.getCharacters()
if (index < 0) {
index = characters.length
}
const matchingCharacter = DB.getCharacterById(id)
if (!matchingCharacter) return console.warn('No matching character to insert', id, index)
const removed = characters.splice(matchingCharacter.rank, 1)
characters.splice(index, 0, removed[0])
DB.setCharacters(characters)
},
refreshCharacters: () => {
if (window.setCharacterRows) {
window.setCharacterRows(DB.getCharacters())
}
},
getRelics: () => Object.values(window.store.getState().relicsById),
getRelicsById: () => window.store.getState().relicsById,
setRelics: (x) => {
const relicsById = {}
for (const relic of x) {
relicsById[relic.id] = relic
}
window.store.getState().setRelicsById(relicsById)
},
getRelicById: (id) => window.store.getState().relicsById[id],
setRelic: (relic) => {
if (!relic.id) return console.warn('No matching relic', relic)
const relicsById = window.store.getState().relicsById
relicsById[relic.id] = relic
window.store.getState().setRelicsById(relicsById)
},
refreshRelics: () => {
if (window.setRelicRows) window.setRelicRows(DB.getRelics())
},
// Mostly for debugging
getState: () => window.store.getState(),
getScoringMetadata: (id) => {
const defaultScoringMetadata = DB.getMetadata().characters[id].scoringMetadata
const scoringMetadataOverrides = window.store.getState().scoringMetadataOverrides[id]
const returnScoringMetadata = scoringMetadataOverrides || defaultScoringMetadata
for (const key of Object.keys(returnScoringMetadata.stats)) {
if (returnScoringMetadata.stats[key] == null) {
returnScoringMetadata.stats[key] = 0
}
}
return returnScoringMetadata
},
updateCharacterScoreOverrides: (id, updated) => {
const overrides = window.store.getState().scoringMetadataOverrides
overrides[id] = updated
window.store.getState().setScoringMetadataOverrides(overrides)
SaveState.save()
},
setStore: (x) => {
const charactersById = {}
const dbCharacters = DB.getMetadata().characters
const dbLightCones = DB.getMetadata().lightCones
for (const character of x.characters) {
character.equipped = {}
charactersById[character.id] = character
// Previously the relic sets were different than what they are now, delete the deprecated options for users with old save files
const relicSetsOptions = character.form.relicSets || []
for (let i = relicSetsOptions.length - 1; i >= 0; i--) {
if (!relicSetsOptions[i] || !Object.values(RelicSetFilterOptions).includes(relicSetsOptions[i][0])) {
character.form.relicSets.splice(i, 1)
}
}
// Unset light cone fields for mismatched light cone path
const dbLightCone = dbLightCones[character.form?.lightCone] || {}
const dbCharacter = dbCharacters[character.id]
if (dbLightCone.path != dbCharacter.path) {
character.form.lightCone = undefined
character.form.lightConeLevel = 80
character.form.lightConeSuperimposition = 1
character.form.lightConeConditionals = {}
}
// Deduplicate main stat filter values
for (const part of Object.keys(Constants.Parts)) {
character.form['main' + part] = deduplicateArray(character.form['main' + part])
}
}
for (const character of Object.values(dbCharacters)) {
// Deduplicate scoring optimal main stat
for (const part of Object.keys(Constants.Parts)) {
character.scoringMetadata.parts[part] = deduplicateArray(character.scoringMetadata.parts[part])
}
}
for (const relic of x.relics) {
RelicAugmenter.augment(relic)
const char = charactersById[relic.equippedBy]
if (char && !char.equipped[relic.part]) {
char.equipped[relic.part] = relic.id
} else {
relic.equippedBy = undefined
}
}
window.store.getState().setScorerId(x.scorerId)
window.store.getState().setScoringMetadataOverrides(x.scoringMetadataOverrides || {})
if (x.optimizerMenuState) {
const menuState = window.store.getState().optimizerMenuState
for (const key of Object.values(OptimizerMenuIds)) {
if (x.optimizerMenuState[key] != null) {
menuState[key] = x.optimizerMenuState[key]
}
}
window.store.getState().setOptimizerMenuState(menuState)
}
assignRanks(x.characters)
DB.setRelics(x.relics)
DB.setCharacters(x.characters)
DB.refreshCharacters()
DB.refreshRelics()
SaveState.save()
},
resetStore: () => {
DB.setStore({
relics: [],
characters: [],
})
},
addFromForm: (form) => {
const characters = DB.getCharacters()
let found = DB.getCharacterById(form.characterId)
if (found) {
found.form = {
...found.form,
...form,
}
DB.setCharacters(characters)
} else {
const defaultForm = getDefaultForm({ id: form.characterId })
found = {
id: form.characterId,
form: { ...defaultForm, ...form },
equipped: {},
}
DB.addCharacter(found)
}
console.log('Updated db characters', characters)
/*
* TODO: after render optimization, window.characterGrid is possibly undefined
* Since the grid resets the rows, we have to re-select the grid node and inform the character tab
*/
if (window.characterGrid?.current?.api) {
window.characterGrid.current.api.updateGridOptions({ rowData: characters })
window.characterGrid.current.api.forEachNode((node) => node.data.id == found.id ? node.setSelected(true) : 0)
window.store.getState().setCharacterTabFocusCharacter(found.id)
}
SaveState.save()
return found
},
saveCharacterPortrait: (characterId, portrait) => {
const character = DB.getCharacterById(characterId)
if (!character) {
console.warn('No character selected')
return
}
character.portrait = portrait
DB.setCharacter(character)
console.log('Saved portrait', DB.getState())
},
deleteCharacterPortrait: (characterId) => {
const character = DB.getCharacterById(characterId)
if (!character) {
console.warn('No character selected')
return
}
delete character.portrait
DB.setCharacter(character)
console.log('Deleted portrait', DB.getState())
},
saveCharacterBuild: (name, characterId, score) => {
const character = DB.getCharacterById(characterId)
if (!character) {
console.warn('No character selected')
return
}
const build = character.builds?.find((x) => x.name == name)
if (build) {
const errorMessage = `Build name [${name}] already exists`
console.warn(errorMessage)
return { error: errorMessage }
} else {
if (!character.builds) character.builds = []
character.builds.push({
name: name,
build: [...Object.values(character.equipped)],
score: score,
})
DB.setCharacter(character)
console.log('Saved build', DB.getState())
}
},
deleteCharacterBuild: (characterId, name) => {
const character = DB.getCharacterById(characterId)
if (!character) return console.warn('No character to delete build for')
character.builds = character.builds.filter((x) => x.name != name)
DB.setCharacter(character)
},
clearCharacterBuilds: (characterId) => {
const character = DB.getCharacterById(characterId)
if (!character) return console.warn('No character to clear builds for')
character.builds = []
DB.setCharacter(character)
},
unequipCharacter: (id) => {
const character = DB.getCharacterById(id)
if (!character) return console.warn('No character to unequip')
console.log('Unequipping character', id, character)
for (const part of Object.values(Constants.Parts)) {
const equippedId = character.equipped[part]
if (!equippedId) continue
const relicMatch = DB.getRelicById(equippedId)
character.equipped[part] = undefined
if (relicMatch) {
relicMatch.equippedBy = undefined
DB.setRelic(relicMatch)
}
}
DB.setCharacter(character)
},
removeCharacter: (characterId) => {
DB.unequipCharacter(characterId)
let characters = DB.getCharacters()
characters = characters.filter((x) => x.id != characterId)
DB.setCharacters(characters)
},
unequipRelicById: (id) => {
if (!id) return console.warn('No relic')
const relic = DB.getRelicById(id)
console.log('UNEQUIP RELIC')
const characters = DB.getCharacters()
for (const character of characters) {
if (character.equipped && character.equipped[relic.part] && character.equipped[relic.part] == relic.id) {
character.equipped[relic.part] = undefined
}
}
DB.setCharacters(characters)
relic.equippedBy = undefined
DB.setRelic(relic)
},
equipRelic: (relic, characterId) => {
if (!relic || !relic.id) return console.warn('No relic')
if (!characterId) return console.warn('No character')
relic = DB.getRelicById(relic.id)
const prevOwnerId = relic.equippedBy
const character = DB.getCharacters().find((x) => x.id == characterId)
const prevCharacter = DB.getCharacters().find((x) => x.id == prevOwnerId)
const prevRelic = DB.getRelicById(character.equipped[relic.part])
if (prevRelic) {
DB.unequipRelicById(prevRelic.id)
}
if (prevRelic && prevCharacter) {
prevCharacter.equipped[relic.part] = prevRelic.id
prevRelic.equippedBy = prevCharacter.id
DB.setCharacter(prevCharacter)
DB.setRelic(prevRelic)
} else if (prevCharacter) {
prevCharacter.equipped[relic.part] = undefined
DB.setCharacter(prevCharacter)
}
character.equipped[relic.part] = relic.id
relic.equippedBy = character.id
DB.setCharacter(character)
DB.setRelic(relic)
},
equipRelicIdsToCharacter: (relicIds, characterId) => {
if (!characterId) return console.warn('No characterId to equip to')
console.log('Equipping relics to character', relicIds, characterId)
for (const relicId of relicIds) {
DB.equipRelic({ id: relicId }, characterId)
}
},
switchRelics: (fromCharacterId, toCharacterId) => {
if (!fromCharacterId) return console.warn('No characterId to equip from')
if (!toCharacterId) return console.warn('No characterId to equip to')
console.log(`Switching relics from character ${fromCharacterId} to character ${toCharacterId}`)
const fromCharacter = DB.getCharacterById(fromCharacterId)
DB.equipRelicIdsToCharacter(Object.values(fromCharacter.equipped), toCharacterId)
},
deleteRelic: (id) => {
if (!id) return Message.error('Unable to delete relic')
DB.unequipRelicById(id)
const relicsById = window.store.getState().relicsById
delete relicsById[id]
window.store.getState().setRelicsById(relicsById)
// This refreshes the grid for the character equipped relics color coding
if (window.characterGrid?.current?.api) {
window.characterGrid.current.api.redrawRows()
}
},
// These relics are missing speed decimals from OCR importer
// We overwrite any existing relics with imported ones
mergeRelicsWithState: (newRelics, newCharacters) => {
const oldRelics = DB.getRelics()
newRelics = Utils.clone(newRelics) || []
newCharacters = Utils.clone(newCharacters) || []
console.log('Merging relics', newRelics, newCharacters)
// Add new characters
if (newCharacters) {
for (const character of newCharacters) {
DB.addFromForm(character)
}
}
const characters = DB.getCharacters()
// Generate a hash of existing relics for easy lookup
const oldRelicHashes = {}
for (const oldRelic of oldRelics) {
const hash = hashRelic(oldRelic)
oldRelicHashes[hash] = oldRelic
}
let replacementRelics = []
// In case the user tries to import a characters only file, we do this
if (newRelics.length == 0) {
replacementRelics = oldRelics
}
for (let newRelic of newRelics) {
const hash = hashRelic(newRelic)
// Compare new relic hashes to old relic hashes
const found = oldRelicHashes[hash]
let stableRelicId
if (found) {
if (newRelic.verified) {
// Inherit the new verified speed stats
found.verified = true
found.substats = newRelic.substats
found.augmentedStats = newRelic.augmentedStats
}
if (newRelic.equippedBy && newCharacters) {
// Update the owner of the existing relic with the newly imported owner
found.equippedBy = newRelic.equippedBy
newRelic = found
}
// Save the old relic because it may have edited speed values, delete the hash to prevent duplicates
replacementRelics.push(found)
stableRelicId = found.id
delete oldRelicHashes[hash]
} else {
// No match found - save the new relic
stableRelicId = newRelic.id
replacementRelics.push(newRelic)
}
// Update the character's equipped inventory
if (newRelic.equippedBy && newCharacters) {
const character = characters.find((x) => x.id == newRelic.equippedBy)
if (character) {
character.equipped[newRelic.part] = stableRelicId
} else {
console.log('No character to equip relic to', newRelic)
}
}
}
console.log('Replacement relics', replacementRelics)
DB.setRelics(replacementRelics)
// Clean up any deleted relic ids that are still equipped
for (const character of characters) {
for (const part of Object.values(Constants.Parts)) {
if (character.equipped && character.equipped[part] && !DB.getRelicById(character.equipped[part])) {
character.equipped[part] = undefined
}
}
}
// Clean up relics that are double equipped
for (const relic of DB.getRelics()) {
if (!relic.equippedBy) continue
const character = DB.getCharacterById(relic.equippedBy)
if (!character || character.equipped[relic.part] != relic.id) {
relic.equippedBy = undefined
}
}
// Clean up characters who have relics equipped by someone else, or characters that dont exist ingame yet
for (const character of DB.getCharacters()) {
for (const part of Object.keys(character.equipped)) {
const relicId = character.equipped[part]
if (relicId) {
const relic = DB.getRelicById(relicId)
if (relic.equippedBy != character.id) {
character.equipped[part] = undefined
}
}
}
}
DB.setRelics(replacementRelics)
DB.setCharacters(characters)
// only valid when on relics tab
if (window.relicsGrid?.current?.api) {
window.relicsGrid.current.api.updateGridOptions({ rowData: replacementRelics })
}
// only valid when on character tab
if (window.characterGrid?.current?.api) {
window.characterGrid.current.api.redrawRows()
}
// TODO this probably shouldn't be in this file
const fieldValues = OptimizerTabController.getForm()
window.onOptimizerFormValuesChange({}, fieldValues)
window.refreshRelicsScore()
},
/*
* These relics have accurate speed values from relic scorer import
* We keep the existing set of relics and only overwrite ones that match the ones that match an imported one
*/
mergeVerifiedRelicsWithState: (newRelics) => {
const oldRelics = Utils.clone(DB.getRelics()) || []
newRelics = Utils.clone(newRelics) || []
// part set grade mainstat substatStats
const oldRelicPartialHashes = {}
for (const oldRelic of oldRelics) {
const hash = partialHashRelic(oldRelic)
if (!oldRelicPartialHashes[hash]) oldRelicPartialHashes[hash] = []
oldRelicPartialHashes[hash].push(oldRelic)
}
// Tracking these for debug / messaging
const updatedOldRelics = []
const addedNewRelics = []
for (const newRelic of newRelics) {
newRelic.equippedBy = undefined
const partialHash = partialHashRelic(newRelic)
const partialMatches = oldRelicPartialHashes[partialHash] || []
let match
for (const partialMatch of partialMatches) {
if (newRelic.enhance < partialMatch.enhance) continue
if (newRelic.substats.length < partialMatch.substats.length) continue
let exit = false
let upgrades = 0
for (let i = 0; i < partialMatch.substats.length; i++) {
const matchSubstat = partialMatch.substats[i]
const newSubstat = newRelic.substats.find((x) => x.stat == matchSubstat.stat)
// Different substats mean different relics - break
if (!newSubstat) { exit = true; break }
if (matchSubstat.stat != newSubstat.stat) { exit = true; break }
if (compareSameTypeSubstat(matchSubstat, newSubstat) == -1) { exit = true; break }
// Track if the number of stat increases make sense
if (compareSameTypeSubstat(matchSubstat, newSubstat) == 1) {
upgrades++
}
}
if (exit) continue
const possibleUpgrades = Math.round((Math.floor(newRelic.enhance / 3) * 3 - Math.floor(partialMatch.enhance / 3) * 3) / 3)
if (upgrades > possibleUpgrades) continue
// If it passes all the tests, keep it
match = partialMatch
break
}
if (match) {
match.substats = newRelic.substats
match.main = newRelic.main
match.enhance = newRelic.enhance
match.verified = true
updatedOldRelics.push(match)
} else {
oldRelics.push(newRelic)
newRelic.verified = true
addedNewRelics.push(newRelic)
}
}
console.warn('addedNewRelics', addedNewRelics)
console.warn('updatedOldRelics', updatedOldRelics)
oldRelics.map((x) => RelicAugmenter.augment(x))
DB.setRelics(oldRelics)
DB.refreshRelics()
window.refreshRelicsScore()
if (window.characterGrid?.current?.api) {
window.characterGrid.current.api.redrawRows()
}
if (updatedOldRelics.length) Message.success(`Updated stats for ${updatedOldRelics.length} existing relics`, 8)
if (addedNewRelics.length) Message.success(`Added ${addedNewRelics.length} new relics`, 8)
},
}
export default DB
function assignRanks(characters) {
for (let i = 0; i < characters.length; i++) {
characters[i].rank = i
}
// This sets the rank for the current optimizer character because shuffling ranks will desync the Priority filter selector
const optimizerMatchingCharacter = DB.getCharacterById(window.store.getState().optimizerTabFocusCharacter)
if (optimizerMatchingCharacter) {
window.optimizerForm.setFieldValue('rank', optimizerMatchingCharacter.rank)
}
return characters
}
function hashRelic(relic) {
const substatValues = []
const substatStats = []
for (const substat of relic.substats) {
if (Utils.isFlat(substat.stat)) {
// Flat atk/def/hp/spd values we floor to an int
substatValues.push(Math.floor(substat.value))
} else {
// Other values we match to 1 decimal point due to OCR
substatValues.push(Utils.precisionRound(Utils.truncate10ths(substat.value)))
}
substatStats.push(substat.stat)
}
const hashObject = {
part: relic.part,
set: relic.set,
grade: relic.grade,
enhance: relic.enhance,
mainstat: relic.main.stat,
mainvalue: Math.floor(relic.main.value),
substatValues: substatValues, // Match to 1 decimal point
substatStats: substatStats,
}
return objectHash(hashObject)
}
// -1: old > new, 0: old == new, 1, new > old
function compareSameTypeSubstat(oldSubstat, newSubstat) {
let oldValue
let newValue
if (Utils.isFlat(oldSubstat.stat)) {
// Flat atk/def/hp/spd values we floor to an int
oldValue = Math.floor(oldSubstat.value)
newValue = Math.floor(newSubstat.value)
} else {
// Other values we match to 1 decimal point due to OCR
oldValue = Utils.precisionRound(Utils.truncate10ths(oldSubstat.value))
newValue = Utils.precisionRound(Utils.truncate10ths(newSubstat.value))
}
if (oldValue == newValue) return 0
if (oldValue < newValue) return 1
return -1
}
function partialHashRelic(relic) {
const hashObject = {
part: relic.part,
set: relic.set,
grade: relic.grade,
mainstat: relic.main.stat,
}
return objectHash(hashObject)
}
function deduplicateArray(arr) {
if (arr == null) return arr
return [...new Set(arr)]
}