-
Notifications
You must be signed in to change notification settings - Fork 0
/
moon_phase_functions.dart
743 lines (640 loc) · 23.2 KB
/
moon_phase_functions.dart
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
// ignore_for_file: prefer_typing_uninitialized_variables, non_constant_identifier_names, unused_local_variable, duplicate_ignore
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'common_functions.dart';
class SunMoonTime {
DateTime date;
double tz;
double longitude;
double latitude;
SunMoonTime({
required this.date,
required this.tz,
required this.latitude,
required this.longitude,
});
Map moonRiseSet() {
double mjds = mjd();
// ignore: unused_local_variable
var sglong, sglat, date, ym, yz, above, utrise, utset, j;
var yp, nz, rise, sett, hour, z1, z2, iobj, rads = 0.0174532925;
List quadout = [];
var sinho;
Map outstring = {"rise": false, "set": false, "transit": false};
sinho = sin(rads * 8 / 60);
sglat = sin(rads * latitude);
double cglat = cos(rads * latitude);
date = mjds - tz / 24;
rise = false;
sett = false;
above = false;
hour = 1.0;
ym = sin_alt(1, date, hour - 1.0, longitude, cglat, sglat) - sinho;
if (ym > 0.0) above = true;
while (hour < 25 && (sett == false || rise == false)) {
yz = sin_alt(1, date, hour, longitude, cglat, sglat) - sinho;
yp = sin_alt(1, date, hour + 1.0, longitude, cglat, sglat) - sinho;
quadout = quad(ym, yz, yp);
nz = quadout[0];
z1 = quadout[1];
z2 = quadout[2];
double xe = quadout[3];
double ye = quadout[4];
// case when one event is found in the interval
if (nz == 1) {
if (ym < 0.0) {
utrise = hour + z1;
rise = true;
} else {
utset = hour + z1;
sett = true;
}
}
if (nz == 2) {
if (ye < 0.0) {
utrise = hour + z2;
utset = hour + z1;
} else {
utrise = hour + z1;
utset = hour + z2;
}
}
ym = yp;
hour += 2.0;
}
if (rise == true || sett == true) {
if (rise == true) {
String hrsmins = hrsmin(utrise);
Map time = hrsStringToObject(hrsmins);
Map a = {
"hour": time["hour"],
"minute": time["minute"],
"meridian": time["meridian"],
"hrsmin": time["hourMins"],
"milliSecond": time["milliSecond"],
"object": time["object"],
};
outstring["rise"] = a;
}
if (sett == true) {
String hrsmins = hrsmin(utset);
Map time = hrsStringToObject(hrsmins);
Map b = {
"hour": time["hour"],
"minute": time["minute"],
"meridian": time["meridian"],
"hrsmin": time["hourMins"],
"milliSecond": time["milliSecond"],
"object": time["object"],
};
outstring["set"] = b;
}
}
///Moon:
if (rise != false && sett != false) {
var risehrsmin = outstring["rise"]["hrsmin"].split(":");
var sethrsmin = outstring["set"]["hrsmin"].split(":");
final rise = DateTime(this.date.year, this.date.month, this.date.day, int.parse(risehrsmin[0]), int.parse(risehrsmin[1]));
final set = DateTime(this.date.year, this.date.month, this.date.day, int.parse(sethrsmin[0]) + 4, int.parse(sethrsmin[1]));
final transit = rise.add(Duration(milliseconds: (set.millisecondsSinceEpoch - rise.millisecondsSinceEpoch) ~/ 2));
DateTime time = DateTime(this.date.year, this.date.month, this.date.day, transit.hour, transit.minute, 00);
Map c = {
"hour": transit.hour > 12
? transit.hour - 12
: transit.hour == 0
? 12
: transit.hour,
"minute": transit.minute,
"meridian": DateFormat("a").format(transit),
"hrsmin": "${transit.hour}:${transit.minute}",
"milliSecond": time.millisecondsSinceEpoch,
"object": time
};
outstring["transit"] = c;
}
return outstring;
}
sunRiseSet() {
double mjds = mjd();
double cglat, xe, ye;
var sglat, date, ym, yz, above, utrise, utset;
var yp, nz, rise, sett, hour, z1, z2, iobj, rads = 0.0174532925;
List quadout = [];
double sinho;
Map outstring = {"rise": false, "set": false, "transit": false};
sinho = sin(rads * -0.833);
sglat = sin(rads * latitude);
cglat = cos(rads * latitude);
date = mjds - tz / 24;
rise = false;
sett = false;
above = false;
hour = 1.0;
ym = sin_alt(2, date, hour - 1.0, longitude, cglat, sglat) - sinho;
if (ym > 0.0) above = true;
while (hour < 25 && (sett == false || rise == false)) {
yz = sin_alt(2, date, hour, longitude, cglat, sglat) - sinho;
yp = sin_alt(2, date, hour + 1.0, longitude, cglat, sglat) - sinho;
quadout = quad(ym, yz, yp);
nz = quadout[0];
z1 = quadout[1];
z2 = quadout[2];
xe = quadout[3];
ye = quadout[4];
if (nz == 1) {
if (ym < 0.0) {
utrise = hour + z1;
rise = true;
} else {
utset = hour + z1;
sett = true;
}
}
if (nz == 2) {
if (ye < 0.0) {
utrise = hour + z2;
utset = hour + z1;
} else {
utrise = hour + z1;
utset = hour + z2;
}
}
ym = yp;
hour += 2.0;
}
if (rise == true || sett == true) {
if (rise == true) {
String hrsmins = hrsmin(utrise);
Map time = hrsStringToObject(hrsmins);
Map a = {
"hour": time["hour"],
"minute": time["minute"],
"meridian": time["meridian"],
"hrsmin": time["hourMins"],
"milliSecond": time["milliSecond"],
"object": time["object"],
};
outstring["rise"] = a;
}
if (sett == true) {
String hrsmins = hrsmin(utset);
Map time = hrsStringToObject(hrsmins);
Map b = {
"hour": time["hour"],
"minute": time["minute"],
"meridian": time["meridian"],
"hrsmin": time["hourMins"],
"milliSecond": time["milliSecond"],
"object": time["object"],
};
outstring["set"] = b;
}
}
if (rise != false && sett != false) {
var risehrsmin = outstring["rise"]["hrsmin"].split(":");
var sethrsmin = outstring["set"]["hrsmin"].split(":");
var x = int.parse(risehrsmin[0]) * 60 + int.parse(risehrsmin[1]);
var y = int.parse(sethrsmin[0]) * 60 + int.parse(sethrsmin[1]);
var z = ((x + y) / 2).floor();
var d = (z / 60).floor().toString() + (z % 60).toString();
Map time = hrsStringToObject(d.toString());
Map c = {
"hour": time["hour"],
"minute": time["minute"],
"meridian": time["meridian"],
"hrsmin": time["hourMins"],
"milliSecond": time["milliSecond"],
"object": time["object"],
};
outstring["transit"] = c;
}
return outstring;
}
hrsStringToObject(String str) {
Map timeData = {"hour": "00", "minute": "00", "meridian": "AM", "hourMins": "00:00", "milliSecond": "0000000000000", "object": null};
int position = str.length - 2;
String timeString = "${str.substring(0, position)}:${str.substring(position)}";
final dateList = timeString.split(":");
timeData["hourMins"] = timeString;
timeData["hour"] = (int.parse(dateList[0]) > 12)
? (int.parse(dateList[0]) - 12).toString()
: (int.parse(dateList[0]) == 0)
? "12"
: dateList[0];
timeData["minute"] = dateList[1];
timeData["meridian"] = int.parse(dateList[0]) >= 12 ? "PM" : "AM";
DateTime time = DateTime(date.year, date.month, date.day, int.parse(dateList[0]), int.parse(dateList[1]), 0);
timeData["milliSecond"] = time.millisecondsSinceEpoch;
timeData['object'] = time;
return timeData;
}
dateTimeObjectToHrsObject(DateTime dateTime) {
Map timeData = {"hour": "00", "minute": "00", "meridian": "AM", "hourMins": "00:00", "milliSecond": "00", "object": null};
timeData["hourMins"] = "${dateTime.hour}:${dateTime.minute}";
timeData["hour"] = (dateTime.hour > 12)
? (dateTime.hour - 12).toString()
: (dateTime.hour == 0)
? "12"
: dateTime.hour;
timeData["minute"] = dateTime.minute;
timeData["meridian"] = dateTime.hour >= 12 ? "PM" : "AM";
DateTime time = DateTime(date.year, date.month, date.day, dateTime.hour, dateTime.minute, 0);
timeData["milliSecond"] = time.millisecondsSinceEpoch;
timeData['object'] = time;
return timeData;
}
int ipart(x) => (x > 0) ? x.floor() : x.ceil();
double range(x) {
double b = x / 360;
double a = 360 * (b - ipart(b));
if (a < 0) {
a = a + 360;
}
return a;
}
double frac(x) {
double a = x - x.floor();
if (a < 0) a += 1;
return a;
}
double lmst(mjd, glong) {
double d = mjd - 51544.5;
double t = d / 36525.0;
double lst = range(280.46061837 + 360.98564736629 * d + 0.000387933 * t * t - t * t * t / 38710000);
return (lst / 15.0 + glong / 15);
}
List<double> quad(ym, yz, yp) {
//// finds the parabola throuh the three points (-1,ym), (0,yz), (1, yp)// and returns the coordinates of the max/min (if any) xe, ye// the values of x where the parabola crosses zero (roots of the quadratic)// and the number of roots (0, 1 or 2) within the interval [-1, 1]//// well, this routine is producing sensible answers//// results passed as array [nz, z1, z2, xe, ye]// var nz, a, b, c, dis, dx, xe, ye, z1, z2, nz;
List<double> quadout = [];
double? z1, z2;
int nz = 0;
double a = 0.5 * (ym + yp) - yz;
double b = 0.5 * (yp - ym);
double c = yz;
double xe = -b / (2 * a);
double ye = (a * xe + b) * xe + c;
double dis = b * b - 4.0 * a * c;
if (dis > 0) {
double dx = 0.5 * sqrt(dis) / a.abs();
z1 = xe - dx;
z2 = xe + dx;
if (z1.abs() <= 1.0) nz += 1;
if (z2.abs() <= 1.0) nz += 1;
if (z1 < -1.0) z1 = z2;
}
quadout.add(nz.toDouble());
quadout.add(z1!.toDouble());
quadout.add(z2!.toDouble());
quadout.add(xe.toDouble());
quadout.add(ye.toDouble());
return quadout;
}
dynamic hrsmin(hours) {
//// takes decimal hours and returns a string in hhmm format// var hrs, h, m, dum;
double hrs = (hours * 60 + 0.5).floor() / 60.0;
int h = hrs.floor();
int m = (60 * (hrs - h) + 0.5).floor();
int dum = h * 100 + m;
String strDum = dum.toString();
// the jiggery pokery below is to make sure that two minutes past midnight
// comes out as 0002 not 2. Javascript does not appear to have 'format codes' // like C
if (dum < 1000) strDum = "0$strDum";
if (dum < 100) strDum = "0$strDum";
if (dum < 10) strDum = "0$strDum";
return strDum;
}
double sin_alt(iobj, mjd0, hour, glong, cglat, sglat) {
var mjd, t, ra, dec, tau, salt;
double rads = 0.0174532925;
List<dynamic> objpos = [];
mjd = mjd0 + hour / 24.0;
t = (mjd - 51544.5) / 36525.0;
if (iobj == 1) {
objpos = minimoon(t);
} else {
objpos = minisun(t);
}
ra = objpos[1];
dec = objpos[0];
// ra = objpos[2];
// dec = objpos[1];
tau = 15.0 * (lmst(mjd, glong) - ra);
salt = sglat * sin(rads * dec) + cglat * cos(rads * dec) * cos(rads * tau);
return salt;
}
List<dynamic> minimoon(t) {
double p2 = 6.283185307, arc = 206264.8062, coseps = 0.91748, sineps = 0.39778;
double L0, L, LS, F, D, H, S, N, DL, CB, L_moon, B_moon, V, W, X, Y, Z, RHO;
List<dynamic> mooneq = [];
L0 = frac(0.606433 + 1336.855225 * t); // mean longitude of moon
L = p2 * frac(0.374897 + 1325.552410 * t); //mean anomaly of Moon
LS = p2 * frac(0.993133 + 99.997361 * t); //mean anomaly of Sun
D = p2 * frac(0.827361 + 1236.853086 * t); //difference in longitude of moon and sun
F = p2 * frac(0.259086 + 1342.227825 * t); //mean argument of latitude
// corrections to mean longitude in arcsec
DL = 22640 * sin(L);
DL += -4586 * sin(L - 2 * D);
DL += 2370 * sin(2 * D);
DL += 769 * sin(2 * L);
DL += -668 * sin(LS);
DL += -412 * sin(2 * F);
DL += -212 * sin(2 * L - 2 * D);
DL += -206 * sin(L + LS - 2 * D);
DL += 192 * sin(L + 2 * D);
DL += -165 * sin(LS - 2 * D);
DL += -125 * sin(D);
DL += -110 * sin(L + LS);
DL += 148 * sin(L - LS);
DL += -55 * sin(2 * F - 2 * D);
// simplified form of the latitude terms
S = F + (DL + 412 * sin(2 * F) + 541 * sin(LS)) / arc;
H = F - 2 * D;
N = -526 * sin(H);
N += 44 * sin(L + H);
N += -31 * sin(-L + H);
N += -23 * sin(LS + H);
N += 11 * sin(-LS + H);
N += -25 * sin(-2 * L + F);
N += 21 * sin(-L + F);
// ecliptic long and lat of Moon in rads
L_moon = p2 * frac(L0 + DL / 1296000);
B_moon = (18520.0 * sin(S) + N) / arc;
// equatorial coord conversion - note fixed obliquity
CB = cos(B_moon);
X = CB * cos(L_moon);
V = CB * sin(L_moon);
W = sin(B_moon);
Y = coseps * V - sineps * W;
Z = sineps * V + coseps * W;
RHO = sqrt(1.0 - Z * Z);
double dec = (360.0 / p2) * atan(Z / RHO);
double ra = (48.0 / p2) * atan(Y / (X + RHO));
if (ra < 0) ra += 24;
mooneq.add(dec);
mooneq.add(ra);
// mooneq[0] = dec;
// mooneq[1] = ra;
return mooneq;
}
minisun(t) {
var p2 = 6.283185307, coseps = 0.91748, sineps = 0.39778;
var L, M, DL, SL, X, Y, Z, RHO, ra, dec;
List<double> suneq = [];
M = p2 * frac(0.993133 + 99.997361 * t);
DL = 6893.0 * sin(M) + 72.0 * sin(2 * M);
L = p2 * frac(0.7859453 + M / p2 + (6191.2 * t + DL) / 1296000);
SL = sin(L);
X = cos(L);
Y = coseps * SL;
Z = sineps * SL;
RHO = sqrt(1 - Z * Z);
dec = (360.0 / p2) * atan(Z / RHO);
ra = (48.0 / p2) * atan(Y / (X + RHO));
if (ra < 0) ra += 24;
suneq.add(dec);
suneq.add(ra);
return suneq;
}
double mjd() {
double a, b;
int month = date.month;
int year = date.year;
int hour = date.hour;
int day = date.day;
if (month <= 2) {
month = month + 12;
year = year - 1;
}
a = 10000.0 * year + 100.0 * month + day;
if (a <= 15821004.1) {
b = (-2 * ((year + 4716) / 4).floor() - 1179).toDouble();
} else {
b = ((year / 400).floor() - (year / 100).floor() + (year / 4).floor()).toDouble();
}
a = 365.0 * year - 679004.0;
return a + b + (30.6001 * (month + 1)).floor() + day + hour / 24.0;
}
}
class DeerHunting {
DateTime date;
double tz;
double longitude;
double latitude;
DeerHunting({
required this.date,
required this.tz,
required this.latitude,
required this.longitude,
});
getSunMoonTime() {
SunMoonTime? sunMoon = getSunMoonRiseSetTime(
date: DateTime(date.year, date.month, date.day),
latitude: latitude,
longitude: longitude,
tz: tz,
);
return sunMoon;
}
calculateDawnDusk(sunrise, sunset, moonrise, moonset) {
DateTime dawn = DateTime.fromMillisecondsSinceEpoch((sunrise - (sunset - sunrise) / 2).floor());
DateTime dusk = DateTime.fromMillisecondsSinceEpoch((sunset + (sunrise + 24 * 60 * 60 * 1000 - sunset) / 2).floor());
DateTime moonOverhead = DateTime.fromMillisecondsSinceEpoch((moonrise + (moonset - moonrise) / 2).floor());
DateTime moonUnderfoot = DateTime.fromMillisecondsSinceEpoch((moonset + (moonrise + 24 * 60 * 60 * 1000 - moonset) / 2).floor());
Map<String, dynamic> deerFeedingTime = {
"dawn": {
"start": dawn,
"end": DateTime.fromMillisecondsSinceEpoch(dawn.millisecondsSinceEpoch + 2 * 60 * 60 * 1000),
},
"dusk": {
"start": dusk,
"end": DateTime.fromMillisecondsSinceEpoch(dusk.millisecondsSinceEpoch - 2 * 60 * 60 * 1000),
},
"moonOverhead": {
"start": DateTime.fromMillisecondsSinceEpoch(moonOverhead.millisecondsSinceEpoch - 60 * 60 * 1000),
"end": DateTime.fromMillisecondsSinceEpoch(moonOverhead.millisecondsSinceEpoch + 60 * 60 * 1000),
},
"moonUnderfoot": {
"start": DateTime.fromMillisecondsSinceEpoch(moonUnderfoot.millisecondsSinceEpoch - 60 * 60 * 1000),
"end": DateTime.fromMillisecondsSinceEpoch(moonUnderfoot.millisecondsSinceEpoch + 60 * 60 * 1000),
}
};
return deerFeedingTime;
}
getMajorFeedingTime(sunMoonTime) {
Map feedDateTime = calculateDawnDusk(
sunMoonTime.sunRiseSet()["rise"] == false ? 0 : sunMoonTime.sunRiseSet()["rise"]["milliSecond"],
sunMoonTime.sunRiseSet()["set"] == false ? 0 : sunMoonTime.sunRiseSet()["set"]["milliSecond"],
sunMoonTime.moonRiseSet()["rise"] == false ? 0 : sunMoonTime.moonRiseSet()["rise"]["milliSecond"],
sunMoonTime.moonRiseSet()["set"] == false ? 0 : sunMoonTime.moonRiseSet()["set"]["milliSecond"],
);
DateTime moonOverHeadStart = feedDateTime["moonOverhead"]["start"];
DateTime moonOverHeadEnd = feedDateTime["moonOverhead"]["end"];
DateTime moonUnderfootStart = feedDateTime["moonUnderfoot"]["start"];
DateTime moonUnderfootEnd = feedDateTime["moonUnderfoot"]["end"];
Map overHeadStart = sunMoonTime.dateTimeObjectToHrsObject(moonOverHeadStart);
Map overHeadEnd = sunMoonTime.dateTimeObjectToHrsObject(moonOverHeadEnd);
Map overFootStart = sunMoonTime.dateTimeObjectToHrsObject(moonUnderfootStart);
Map overFootEnd = sunMoonTime.dateTimeObjectToHrsObject(moonUnderfootEnd);
var abc = overHeadStart;
var bcd = overFootStart;
if (overHeadStart["meridian"] == "PM") {
abc = overHeadStart;
}
if (overFootStart["meridian"] == "AM") {
bcd = overFootStart;
}
Map moonRTransitStart = sunMoonTime.dateTimeObjectToHrsObject(abc['object'].subtract(const Duration(hours: 1)));
Map moonRTransitEnd = sunMoonTime.dateTimeObjectToHrsObject(abc['object'].add(const Duration(hours: 1)));
Map moonTransitStart = sunMoonTime.dateTimeObjectToHrsObject(bcd['object']);
Map moonTransitEnd = sunMoonTime.dateTimeObjectToHrsObject(bcd['object'].add(const Duration(hours: 2)));
return {
"1": {"start": moonRTransitStart, "end": moonRTransitEnd},
"2": {"start": moonTransitStart, "end": moonTransitEnd},
};
}
getMinorFeedingTime() {
SunMoonTime sunMoonTime = getSunMoonTime();
Map moonRiseStart = sunMoonTime.dateTimeObjectToHrsObject(sunMoonTime.moonRiseSet()["rise"]['object']);
Map moonRiseEnd = sunMoonTime.dateTimeObjectToHrsObject(sunMoonTime.moonRiseSet()["rise"]['object'].add(const Duration(hours: 2)));
Map moonSetStart = sunMoonTime.dateTimeObjectToHrsObject(sunMoonTime.moonRiseSet()["set"]['object']);
Map moonSetEnd = sunMoonTime.dateTimeObjectToHrsObject(sunMoonTime.moonRiseSet()["set"]['object'].add(const Duration(hours: 2)));
return {
"1": {"start": moonRiseStart, "end": moonRiseEnd},
"2": {"start": moonSetStart, "end": moonSetEnd},
};
}
}
class MoonWidget extends StatelessWidget {
///DateTime to show.
///Even hour, minutes, and seconds are calculated for MoonWidget
final DateTime date;
///Decide the container size for the MoonWidget
final double size;
///Resolution will be the moon radius.
///Large resolution needs more math operation makes widget heavy.
///Enter a small number if it is sufficient to mark it small,
///such as an icon or marker.
final double resolution;
///Color of light side of moon
final Color moonColor;
///Color of dark side of moon
final Color earthshineColor;
const MoonWidget({
Key? key,
required this.date,
this.size = 36,
this.resolution = 96,
this.moonColor = Colors.amber,
this.earthshineColor = Colors.black87,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return SizedBox(
width: size,
height: size,
child: Transform.scale(
scale: size / (resolution * 2),
child: CustomPaint(
painter: MoonPainter(moonWidget: this),
),
),
);
}
}
class MoonPainter extends CustomPainter {
MoonWidget moonWidget;
final Paint paintDark = Paint();
final Paint paintLight = Paint();
final MoonPhase moon = MoonPhase();
MoonPainter({required this.moonWidget});
@override
void paint(Canvas canvas, Size size) {
double radius = moonWidget.resolution;
int width = radius.toInt() * 2;
int height = radius.toInt() * 2;
double phaseAngle = moon.getPhaseAngle(moonWidget.date);
double xcenter = 0;
double ycenter = 0;
try {
paintLight.color = moonWidget.moonColor;
//달의 색깔로 전체 원을 그린다
canvas.drawCircle(const Offset(0, 1), radius, paintLight);
} catch (e) {
radius = min(width, height) * 0.4;
paintLight.color = moonWidget.moonColor;
Rect oval = Rect.fromLTRB(xcenter - radius, ycenter - radius, xcenter + radius, ycenter + radius);
canvas.drawOval(oval, paintLight);
}
///위상각은 태양 - 달 - 지구의 각도다.
///따라서 0 = full phase, 180 = new
///우리가 필요한 것은 일출 터미네이터의 위치 각도(태양 - 지구 - 달)다.
///위상각과 반대 방향이기 때문에 변환해야한다.
double positionAngle = pi - phaseAngle;
if (positionAngle < 0.0) {
positionAngle += 2.0 * pi;
}
// myPhaseAngle = phaseAngle;
//이제 어두운 면을 그려야 한다.
paintDark.color = moonWidget.earthshineColor;
double cosTerm = cos(positionAngle);
double rsquared = radius * radius;
double whichQuarter = ((positionAngle * 2.0 / pi) + 4) % 4;
for (int j = 0; j < radius; ++j) {
double rrf = sqrt(rsquared - j * j);
double rr = rrf;
double xx = rrf * cosTerm;
double x1 = xcenter - (whichQuarter < 2 ? rr : xx);
double w = rr + xx;
canvas.drawRect(Rect.fromLTRB(x1, ycenter - j, w + x1, ycenter - j + 2), paintDark);
canvas.drawRect(Rect.fromLTRB(x1, ycenter + j, w + x1, ycenter + j + 2), paintDark);
}
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return false;
}
}
class MoonPhase {
final deg2rad = pi / 180;
// convert degrees to a valid angle:
double angle(double deg) {
while (deg >= 360.0) {
deg -= 360.0;
}
while (deg < 0.0) {
deg += 360.0;
}
return deg * deg2rad;
}
// Return the phase angle for the given date, in RADIANS.
// Equation from Meeus eqn. 46.4.
double getPhaseAngle(DateTime date) {
// Time measured in Julian centuries from epoch J2000.0:
DateTime tEpoch = DateTime(2000, 1, 1, 12);
double t = (decimalYears(date) - decimalYears(tEpoch)) / 100.0;
double t2 = t * t;
double t3 = t2 * t;
double t4 = t3 * t;
// Mean elongation of the moon:
double D = angle(297.8502042 + 445267.1115168 * t - 0.0016300 * t2 + t3 / 545868 + t4 / 113065000);
// Sun's mean anomaly:
double M = angle(357.5291092 + 35999.0502909 * t - 0.0001536 * t2 + t3 / 24490000);
// Moon's mean anomaly:
double mPrime = angle(134.9634114 + 477198.8676313 * t + 0.0089970 * t2 - t3 / 3536000 + t4 / 14712000);
return (angle(180 -
(D / deg2rad) -
6.289 * sin(mPrime) +
2.100 * sin(M) -
1.274 * sin(2 * D - mPrime) -
0.658 * sin(2 * D) -
0.214 * sin(2 * mPrime) -
0.110 * sin(D)));
}
double decimalYears(DateTime date) {
return date.millisecondsSinceEpoch.toDouble() / 365.242191 / (24 * 60 * 60 * 1000);
}
double getTimeAsDecimalDay(DateTime date) {
return date.millisecondsSinceEpoch.toDouble() / (24 * 60 * 60 * 1000);
}
}