Files @ 4778889395e8
Branch filter:

Location: ATITD-Tools/Desert-Paint-Codex/Models/ReactionTest.cs

Jason Maltzen
Change the displayed permeutation count to display using locale-specific number formatting (with comma / dot separators). Fix a crash when starting a new round of recipe generation after recipe generation completed during a previous run.
  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
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using DesertPaintCodex.Services;
using JetBrains.Annotations;

namespace DesertPaintCodex.Models
{
    public class ReactionTest : INotifyPropertyChanged, IProgress<float>, IComparable<ReactionTest>
    {
        public enum TestState
        {
            Unset = -1,
            Untested,
            Scanning,
            LabNotFound,
            ClippedResult,
            GoodResult,
            Saved
        }

        public Reagent Reagent1 { get; }
        public Reagent Reagent2 { get; }

        private Reagent? _bufferReagentFirst;
        public Reagent? BufferReagentFirst
        {
            get => _bufferReagentFirst;
            set
            {
                if (_bufferReagentFirst == value) return;
                _bufferReagentFirst = value;
                
                UpdateRecipe();
                
                NotifyPropertyChanged(nameof(BufferReagentFirst));
                NotifyPropertyChanged(nameof(CanScan));
            }
        }
        
        private Reagent? _bufferReagentLast;
        public Reagent? BufferReagentLast
        {
            get => _bufferReagentLast;
            set
            {
                if (_bufferReagentLast == value) return;
                _bufferReagentLast = value;

                UpdateRecipe();

                NotifyPropertyChanged(nameof(BufferReagentLast));
                NotifyPropertyChanged(nameof(CanScan));
            }
        }

        private bool _useFirstBuffer;

        public bool UseFirstBuffer
        {
            get => _useFirstBuffer;
            set
            {
                _useFirstBuffer = value;
                UpdateRecipe();
                NotifyPropertyChanged(nameof(UseFirstBuffer));
                NotifyPropertyChanged(nameof(CanScan));
                NotifyPropertyChanged(nameof(ShowFirstBuffer));
                NotifyPropertyChanged(nameof(ShowLastBuffer));
            }
        }

        private ClipType _clipType;
        public ClipType Clipped {
            get => _clipType;
            set
            {
                _clipType = value;
                NotifyPropertyChanged(nameof(Clipped));
            }
        }

        public bool IsAllCatalysts { get; }

        private Reaction? _reaction;
        public Reaction? Reaction { get => _reaction; set { _reaction = value; NotifyPropertyChanged(nameof(Reaction)); } }

        private Reaction? _badReaction;
        public Reaction? BadReaction { get => _badReaction; set { _badReaction = value; NotifyPropertyChanged(nameof(BadReaction)); } }

        private int _scanProgress;
        public int ScanProgress { get => _scanProgress; set { _scanProgress = value; NotifyPropertyChanged(nameof(ScanProgress)); } }
        
        
        private TestState _state;

        public TestState State
        {
            get => _state;
            set
            {
                _state = value;
                NotifyPropertyChanged(nameof(State));
                NotifyPropertyChanged(nameof(Requires3Way));
                NotifyPropertyChanged(nameof(CanScan));
                NotifyPropertyChanged(nameof(IsScanning));
                NotifyPropertyChanged(nameof(HasResults));
                NotifyPropertyChanged(nameof(HasReaction));
                NotifyPropertyChanged(nameof(CanClear));
                NotifyPropertyChanged(nameof(CanSave));
                NotifyPropertyChanged(nameof(NoLab));
                NotifyPropertyChanged(nameof(CanPickBuffer));
                NotifyPropertyChanged(nameof(ShowFirstBuffer));
                NotifyPropertyChanged(nameof(ShowLastBuffer));
            }
        }

        public bool Requires3Way =>
            (State == TestState.ClippedResult) || IsAllCatalysts;

        public bool CanScan => (State is TestState.Untested or TestState.LabNotFound) || ((State == TestState.ClippedResult) && BufferIsSelected);
        
        public bool IsScanning => State == TestState.Scanning;

        public bool HasResults => (ObservedColor != null) && (State is TestState.ClippedResult or TestState.GoodResult or TestState.LabNotFound);

        public bool HasReaction => State is TestState.ClippedResult or TestState.GoodResult or TestState.Saved;
        
        public bool CanClear => State is TestState.ClippedResult or TestState.GoodResult or TestState.Saved;
        
        public bool CanSave => State == TestState.GoodResult;

        public bool NoLab => State == TestState.LabNotFound;

        public bool CanPickBuffer => (State == TestState.ClippedResult) || IsAllCatalysts;

        public bool ShowFirstBuffer => Requires3Way && UseFirstBuffer;

        public bool ShowLastBuffer => Requires3Way && !UseFirstBuffer;


        private PaintColor? _hypotheticalColor;
        public PaintColor? HypotheticalColor { get => _hypotheticalColor; set { _hypotheticalColor = value; NotifyPropertyChanged(nameof(HypotheticalColor)); } }

        private PaintColor? _observedColor;
        public PaintColor? ObservedColor { get => _observedColor; set { _observedColor = value; NotifyPropertyChanged(nameof(ObservedColor)); } }

        private readonly PaintRecipe _recipe = new();

        public bool IsStub { get; }


        public ReactionTest(Reagent reagent1, Reagent reagent2, Reaction? reaction, ClipType clipType, bool isStub = false)
        {
            Reagent1 = reagent1;
            Reagent2 = reagent2;
            UseFirstBuffer = true;
            IsAllCatalysts = reagent1.IsCatalyst && reagent2.IsCatalyst;
            Clipped = clipType;
            Reaction = reaction;
            State = (reaction != null) ? TestState.Saved :
                (clipType == ClipType.None) ? TestState.Untested : TestState.ClippedResult;
            _recipe.AddReagent(reagent1.Name);
            _recipe.AddReagent(reagent2.Name);
            IsStub = isStub;
            UpdateHypotheticalColor();
        }

        
        #region Actions
        public async Task StartScan()
        {
            Clipped = ClipType.None;
            ScanProgress = 0;
            Reaction = null;
            BadReaction = null;
            State = TestState.Scanning;
            bool testing3Way = Requires3Way && BufferIsSelected;
            bool foundLab = await ReactionScannerService.Instance.CaptureReactionAsync(this);
            if (foundLab)
            {
                ObservedColor = ReactionScannerService.Instance.RecordedColor;
                if (_observedColor != null)
                {
                    Clipped = _observedColor.Red switch
                        {
                            0   => ClipType.RedLow,
                            255 => ClipType.RedHigh,
                            _   => ClipType.None
                        }
                        | _observedColor.Green switch
                        {
                            0   => ClipType.GreenLow,
                            255 => ClipType.GreenHigh,
                            _   => ClipType.None
                        }
                        | _observedColor.Blue switch
                        {
                            0   => ClipType.BlueLow,
                            255 => ClipType.BlueHigh,
                            _   => ClipType.None
                        };

                    if (Clipped == ClipType.None)
                    {
                        State = TestState.GoodResult;
                        Reaction = CalculateReaction();
                    }
                    else
                    {
                        Reaction? reaction = CalculateReaction();
                        bool extrapolated = false;
                        
                        // SPECIAL CASE:
                        // Check to see if we've got a white-shift reaction that's partially clipped, where we can
                        // still extrapolate the reaction, based on the available information.
                        if (!testing3Way && (reaction != null))
                        {
                            PaintColor baseColor = _recipe.BaseColor;
                            if ((reaction.Red < baseColor.Red) &&
                                (reaction.Green < baseColor.Green) &&
                                (reaction.Blue < baseColor.Blue))
                            {
                                // White-shift down clip.
                                extrapolated               = ExtrapolateWhiteFromOneChannel(_observedColor.Red,   0, reaction.Red);
                                if (!extrapolated) extrapolated = ExtrapolateWhiteFromOneChannel(_observedColor.Green, 0, reaction.Green);
                                if (!extrapolated)                ExtrapolateWhiteFromOneChannel(_observedColor.Blue,  0, reaction.Blue);
                            }
                            else if ((reaction.Red > baseColor.Red) &&
                                (reaction.Green > baseColor.Green) &&
                                (reaction.Blue > baseColor.Blue))
                            {
                                // White-shift up clip.
                                extrapolated               = ExtrapolateWhiteFromOneChannel(_observedColor.Red,   255, reaction.Red);
                                if (!extrapolated) extrapolated = ExtrapolateWhiteFromOneChannel(_observedColor.Green, 255, reaction.Green);
                                if (!extrapolated)                ExtrapolateWhiteFromOneChannel(_observedColor.Blue,  255, reaction.Blue);
                            }
                        }

                        if (!extrapolated)
                        {
                            State       = TestState.ClippedResult;
                            BadReaction = CalculateReaction();
                        }
                    }
                    
                    PlayerProfile? profile = ProfileManager.CurrentProfile;
                    profile?.SetPairClipStatus(Reagent1, Reagent2, Clipped);
                }
            }
            else
            {
                Debug.WriteLine("ERROR: Lab UI not found.");
                State = TestState.LabNotFound;
            }
        }

        private bool ExtrapolateWhiteFromOneChannel(int result, int clipBound, int reaction)
        {
            if (result == clipBound) return false;
            
            State = TestState.GoodResult;
            Reaction = new Reaction(reaction, reaction, reaction);

            return true;
        }


        public void CancelScan()
        {
            ReactionScannerService.Instance.CancelScan();
            State = TestState.Untested;
        }

        public void MarkInert()
        {
            Reaction = new Reaction(0, 0, 0);
            State = TestState.GoodResult;
        }

        public void ClearReaction()
        {
            PlayerProfile? profile = ProfileManager.CurrentProfile;
            if (profile == null) return;
            profile.Reactions.Remove(Reagent1, Reagent2);
            profile.SetPairClipStatus(Reagent1, Reagent2, ClipType.None);
            if (State == TestState.Saved)
            {
                profile.Save();
            }
            
            Reaction = null;
            BadReaction = null;
            Clipped = ClipType.None;
            State = TestState.Untested;
        }

        public void SaveReaction()
        {
            PlayerProfile? profile = ProfileManager.CurrentProfile;
            if (profile == null) return;
            profile.Reactions.Set(Reagent1, Reagent2, Reaction);
            profile.Save();
            State = TestState.Saved;
        }

        #endregion
        
        #region Internals

        private Reaction? CalculateReaction()
        {
            if (ProfileManager.CurrentProfile == null) return null;
            if (HypotheticalColor == null) return null;
            if (ObservedColor == null) return null;

            if (_useFirstBuffer)
            {
                if (BufferReagentFirst != null)
                {
                    return ReactionScannerService.Calculate3WayReaction(ProfileManager.CurrentProfile, HypotheticalColor,
                        ObservedColor, BufferReagentFirst, Reagent1, Reagent2, true);
                }
            }
            else
            {
                if (BufferReagentLast != null)
                {
                    return ReactionScannerService.Calculate3WayReaction(ProfileManager.CurrentProfile, HypotheticalColor,
                        ObservedColor, Reagent1, Reagent2, BufferReagentLast, false);
                }
            }
            
            return ReactionScannerService.CalculateReaction(HypotheticalColor, ObservedColor);
        }


        private void UpdateHypotheticalColor()
        {
            HypotheticalColor = null;
            HypotheticalColor = (IsAllCatalysts && !BufferIsSelected) ? null : _recipe.BaseColor;
        }

        private bool BufferIsSelected => UseFirstBuffer ? (BufferReagentFirst != null) : (BufferReagentLast != null);


        private void UpdateRecipe()
        {
            _recipe.Clear();
            if (_useFirstBuffer)
            {
                if (_bufferReagentFirst == null)
                {
                    _recipe.AddReagent(Reagent1.Name);
                    _recipe.AddReagent(Reagent2.Name);
                }
                else
                {
                    _recipe.AddReagent(_bufferReagentFirst.Name);
                    _recipe.AddReagent(Reagent1.Name);
                    _recipe.AddReagent(Reagent2.Name);
                } 
            }
            else
            {
                if (_bufferReagentLast == null)
                {
                    _recipe.AddReagent(Reagent1.Name);
                    _recipe.AddReagent(Reagent2.Name);
                }
                else
                {
                    _recipe.AddReagent(Reagent1.Name);
                    _recipe.AddReagent(Reagent2.Name);
                    _recipe.AddReagent(_bufferReagentLast.Name);
                }                
            }
            
            UpdateHypotheticalColor();
        }
        
        #endregion
        
        

        #region Interface Implementations
        
        public event PropertyChangedEventHandler? PropertyChanged;

        [NotifyPropertyChangedInvocator]
        private void NotifyPropertyChanged([CallerMemberName] string? propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public void Report(float value)
        {
            ScanProgress = (int)Math.Round(value * 100);
        }
        
        #endregion

        public int CompareTo(ReactionTest? other)
        {
            if (other == null) return 1;
            
            if (Clipped == ClipType.None)
            {
                if (other.Clipped != ClipType.None) return -1;
            }
            else if (other.Clipped == ClipType.None) return 1;

            if (IsAllCatalysts)
            {
                if (!other.IsAllCatalysts) return 1;
            }
            else if (other.IsAllCatalysts) return -1;
            
            return string.CompareOrdinal(Reagent1.Name, other.Reagent1.Name) switch
            {
                < 0 => -1,
                > 0 => 1,
                _   => string.CompareOrdinal(Reagent2.Name, other.Reagent2.Name)
            };
        }
    }
}