forked from lassefolkersen/highfrontier
-
Notifications
You must be signed in to change notification settings - Fork 0
/
planet.py
1670 lines (1277 loc) · 82.8 KB
/
planet.py
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
import primitives
import logging
import pygame, sys,os
from pygame.locals import *
#from ocempgui.widgets from PIL import ImageLabel
from PIL import Image, ImageChops, ImageOps, ImageFile,ImageFilter,ImageEnhance
import math
import pickle
import subprocess
import time
import os
import global_variables
import company
import random
logger = logging.getLogger(__name__)
proj_not_working_error = Exception(
"\n".join(
(
"Calling the subprocess proj did not work. ",
"On windows machines the proj.exe is found in the main highfrontier directory. ",
"Make sure you run the program from there. ",
"On unix-based machines it probably means that you don't have the proj command installed.",
"Please check and install proj if missing. ",
)
)
)
class planet:
"""
The class that holds all methods of the planets
And instance of class planet also holds all the base instances within.
"""
def __init__(self,planet_name,solar_system_object_link,planet_data):
planet_file_name = planet_name + ".jpg"
self.solar_system_object_link = solar_system_object_link
self.planet_data = planet_data
self.planet_diameter_km = planet_data["diameter_km"]
self.planet_type = planet_data["type"]
self.current_base = None
self.planet_name = planet_name
self.name = planet_name
self.surface_file_name = os.path.join("images","planet",planet_file_name)
self.projection_scaling=45
self.eastern_inclination = 0
self.northern_inclination = 0
self.gravity_at_surface = planet_data["gravity_at_surface"]
self.surface_area = 4 * math.pi * ((planet_data["diameter_km"]*0.5) ** 2)
self.athmospheric_surface_pressure_pa = self.planet_data["athmospheric_carbondioxide"]
self.athmospheric_nitrogen = self.planet_data["athmospheric_carbondioxide"]
self.athmospheric_carbondioxide = self.planet_data["athmospheric_carbondioxide"]
self.athmospheric_oxygen = self.planet_data["athmospheric_oxygen"]
self.athmospheric_helium = self.planet_data["athmospheric_helium"]
self.athmospheric_hydrogen = self.planet_data["athmospheric_hydrogen"]
self.areas_of_interest = {}
self.base_positions = {}
self.space_stations = {}
self.pre_drawn_surfaces = {}
self.pre_drawn_action_layers = {}
self.resource_maps = {}
self.planet_display_mode = "visible light"
if self.name == "earth":
self.water_level = 1
else:
self.water_level = 0
self.bases = self.read_pre_base_file(planet_name)
for base in list(self.bases.values()):
base.calculate_trade_routes(self)
self.co2_emissions = 0
self.high_grade_greenhouse_gas_emissions = 0
self.radioactive_emissions = 0
def change_gas_in_atmosphere(self,gas,ton):
"""
Function to manipulate partial gas pressure of the atmosphere of the planet.
Takes the gas type, and an amount of gas in tons (can be negative). It then updates the partial pressure to reflect
the change. The main use of the function is that takes into account the environment to which the gas is added.
If a million tonnes of CO2 is added to a small dense planet it has a much larger effect on partial pressure than
if the same amount is added to a large low gravity planet planet.
The assumptions behind the calculations is simply that the higher the surface gravity the more partial pressure per ton of gas
(because it will be drawn towards the surface), and also the larger the surface area of the planet the smaller the partial pressure
per ton of gas (because it has more room to fill). Numbers are currently fitted to the fact that wikipedia ("Carbon dioxide in
the Earth's atmosphere") states that there is today 3 terratonnes of CO2 in the atmosphere as of 2008. With a simple additive
model is assumed. There is of course plenty of space for improvement in this model.
"""
#according to wikipedia ("Carbon dioxide in the Earth's atmosphere") there is today 3 terratonnes of CO2 in the atmosphere
ton_carbondioxide_on_earth_2008 = 3000000000000
pascal_carbondioxide_on_earth_2008 = 384.94
#we use this to calculate the ton_per_pascal factor (and do the rough assumption that it is the same for other gases)
ton_per_pa_on_earth = ton_carbondioxide_on_earth_2008 / pascal_carbondioxide_on_earth_2008
#we then take surface area and gravity of the planet in account and calculate a useful factor
surface_area_ratio = self.solar_system_object_link.planets["earth"].surface_area / self.surface_area
gravity_at_surface_ratio = self.solar_system_object_link.planets["earth"].gravity_at_surface / self.gravity_at_surface
ton_per_pa_here = ton_per_pa_on_earth * gravity_at_surface_ratio / surface_area_ratio
ton_per_pa_here = ton_per_pa_here / (global_variables.gas_change_multiplier * 100000) # for fine tuning in global variables. The number is to try to keep 100.0 a standard value.
if str("athmospheric_" + gas) in list(self.planet_data.keys()):
before = getattr(self, "athmospheric_" + gas)
setattr(self, "athmospheric_" + gas, before + (ton / ton_per_pa_here))
print_dict = {"text":"added " + str(ton) + " " + str(gas) + " to " + self.name + " which made the partial pressure change from " + str((before)) + " to " + str(getattr(self, "athmospheric_" + gas)),"type":"climate"}
self.solar_system_object_link.messages.append(print_dict)
else:
raise Exception(self.name + " did not have a " + str("athmospheric_" + gas) + " entry in the athmospheric_ - only " + str(list(self.planet_data.keys())))
def check_gas_in_atmosphere(self):
"""
Checks if the water level of the planet should be raised
At the moment this is a very simple implementation where it is only the carbondioxide level
that plays in, but room for expansion of this model is open.
"""
difference_from_original = self.athmospheric_carbondioxide - self.planet_data["athmospheric_carbondioxide"]
if self.water_level * 10 + 10 < difference_from_original:
before = self.water_level
self.change_water_level(self.water_level + 0.5)
print_dict = {"text":"The waters are rising on" + self.name + "!","type":"general gameplay info"}
self.solar_system_object_link.messages.append(print_dict)
def read_pre_base_file(self,planet_name):
data_file_name = os.path.join("data","base_data",str(str(planet_name) + ".txt"))
if os.access(data_file_name,os.R_OK):
read_base_database = primitives.import_datasheet(data_file_name)
base_database = {}
#a placeholder "company to give the new bases. Since no companies are initialized yet, this is necessary
class Placeholder():
pass
placeholder = Placeholder()
placeholder.solar_system_object_link = self.solar_system_object_link
for base_name in read_base_database:
base_instance = company.base(self.solar_system_object_link,base_name,self,read_base_database[base_name],placeholder)
base_database[base_name] = base_instance
self.bases = base_database
else: #ie. if no pre-designed bases are found
base_database = {}
return base_database
def calculate_distance(self,position_a,position_b):
"""
Takes two sphere_positions as tuples or two list of sphere_positions as tuples and return the distance
between the two in kilometers based on the diameter_km entry in planet_data
"""
if len(position_a) != len(position_b):
if self.solar_system_object_link.message_printing["debugging"]:
print_dict = {"text":"WARNING: The two lists given in calculate_distance() are not the same length","type":"debugging"}
self.solar_system_object_link.messages.append(print_dict)
result = []
if isinstance(position_a,tuple):
position_a = [position_a]
if isinstance(position_b,tuple):
position_b = [position_b]
for i in range(len(position_a)):
single_position_a = position_a[i]
single_position_b = position_b[i]
long_1 = math.radians(single_position_a[0])
lat_1 = math.radians(single_position_a[1])
long_2 = math.radians(single_position_b[0])
lat_2 = math.radians(single_position_b[1])
# probably not necessary
# if long_1 > 2 * math.pi: long_1 = long_1 - 2 * math.pi
# if long_1 < 0: long_1 = long_1 + 2 * math.pi
# if long_2 > 2 * math.pi: long_2 = long_2 - 2 * math.pi
# if long_2 < 0: long_2 = long_2 + 2 * math.pi
dlong = long_2 - long_1
dlat = lat_2 - lat_1
a = (math.sin(dlat / 2))**2 + math.cos(lat_1) * math.cos(lat_2) * (math.sin(dlong / 2))**2
c = 2 * math.asin(min(1, math.sqrt(a)))
dist = self.planet_diameter_km * ( c / (2 * math.pi))
result.append(dist)
return result
def calculate_all_distances(self):
"""
Function that calculates all distances from all pixels, for use in assigning resource areas
The pixel grid is the (90,45) used in the resource overlay map. The function will return a
dictionary with keys being tuples of all 90 x 45 pixels. The value of each is another dictionary
with keys being 1n,2n,3n,4n(distances in degrees, n = step_size variable) and values being the pixel-tuples
within these distances.
"""
step_size = 1
steps = 9
distance_matrix = {}
planet_circumference = self.planet_diameter_km * math.pi
x1 = 0
for y1 in range(45):
distance_matrix[(x1,y1)] = {}
for i in range(0,step_size * steps,step_size):
distance_matrix[(x1,y1)][i] = []
for x2 in range(90):
for y2 in range(45):
distance_km = self.calculate_distance(((x1*4)-180,(y1*4)-90),((x2*4)-180,(y2*4)-90))
distance_degrees = (360 * distance_km[0]) / planet_circumference
degree_rounding = int(distance_degrees / step_size) * step_size
if degree_rounding in list(distance_matrix[(x1,y1)].keys()):
distance_matrix[(x1,y1)][degree_rounding].append((x2,y2))
distance_data = {"distance_matrix":distance_matrix,"step_size":step_size,"steps":steps}
return distance_data
def check_environmental_safety(self):
"""
Function that will check if humans can live on the surface without housing.
Returns ""Breathable atmosphere", "Survivable atmosphere", or "Lethal atmosphere"
"Breathable atmosphere" is earth like
"Survivable atmosphere" is not nice, but with simple assist devices it is possible (type breathing masks from Red Mars, Green Mars, Blue Mars)
FIXME add temperature at some point
"""
answer = "Breathable atmosphere"
if self.planet_data["athmospheric_surface_pressure_pa"] < 500000:
answer = "Survivable atmosphere"
if self.planet_data["athmospheric_surface_pressure_pa"] < 300000:
answer = "Lethal atmosphere"
if self.planet_data["athmospheric_oxygen"] < 200000:
answer = "Survivable atmosphere"
if self.planet_data["athmospheric_oxygen"] < 150000:
answer = "Lethal atmosphere"
if self.planet_data["athmospheric_carbondioxide"] > 3840:
answer = "Survivable atmosphere"
if self.planet_data["athmospheric_carbondioxide"] > 38400:
answer = "Lethal atmosphere"
return answer
def pickle_all_projection_calculations(self):
"""
A function that saves the projection_coordinate to sphere_coordinate conversions in a pickled file.
Each pickled file contains a dictionary with the projection coordinates as key and the sphere coordinates as value
This is only used when initializing and stuff, and will probably never be called during real execution of code
"""
for projection_scaling in (45,90,180,360):
for northern_inclination in (-90,-60,-30,0,30,60,90):
file_name = "projection_" + str(northern_inclination) + "_NS_" + str(projection_scaling) + "_zoom"
if os.access(os.path.join("pickledprojections",file_name),os.R_OK):
# print file_name + " found."
pass
else:
print(file_name + " not found. Doing calculations.")
plane_to_sphere_list = self.plane_to_sphere_total(0,northern_inclination,projection_scaling)
file = open(os.path.join("pickledprojections",file_name),"w")
pickle.dump(plane_to_sphere_list,file)
file.close()
print("Saved calculations as " + file_name +" in folder pickledprojections")
#print plane_to_sphere_list
def pickle_all_projections(self):
"""
Given a planet instance, this function will check the directory at /pickledsurfaces
to see if pre-drawn images of surfaces already exists. If so it will load them into the
pre_drawn_surfaces variable. If not it will calculate all rotation/zoom levels
and save them.
"""
self.load_for_drawing()
for projection_scaling in (45,90,180,360):
for eastern_inclination in (-150,-120,-90,-60,-30,0,30,60,90,120,150,180):
for northern_inclination in (-90,-60,-30,0,30,60,90):
pickle_file_name = str(self.planet_name) + "_" + str(projection_scaling) + "_zoom_" + str(northern_inclination) + "_NS_" + str(eastern_inclination) + "_EW.jpg"
pickle_file_name_and_path = os.path.join("pickledsurfaces",pickle_file_name)
if os.access(pickle_file_name_and_path,os.R_OK):
surface = pygame.image.load(pickle_file_name_and_path)
else:
print(str((eastern_inclination, northern_inclination, projection_scaling)) +" was not found - calculating")
self.load_for_drawing()
surface = self.draw_image(eastern_inclination, northern_inclination, projection_scaling)
#draw_image(self,eastern_inclination,northern_inclination,projection_scaling,fast_rendering=False,image=None):
pygame.image.save(surface,pickle_file_name_and_path)
self.pre_drawn_surfaces[(northern_inclination,eastern_inclination,projection_scaling)] = surface
def load_for_drawing(self,force_reload = False):
"""
Function that loads the picture of a planet and saves it in the instance.
This function could probably be made much better, since some of the map_dim etc.
are irelevant. Finally there could be a "unload" function or something.
"""
#print "loading images from planet " + str(self.planet_name)
try: self.image
except AttributeError:
if os.access(self.surface_file_name,os.R_OK):
self.image = Image.open(self.surface_file_name)
else:
self.image = Image.open(os.path.join("images","planet","placeholder.jpg"))
self.projection_dim = (self.projection_scaling,self.projection_scaling)
if((self.image.size[0]/self.image.size[1])!=2):
if self.solar_system_object_link.message_printing["debugging"]:
print_dict = {"text":"oh no! The map file is not twice as wide as it is high","type":"debugging"}
self.solar_system_object_link.messages.append(print_dict)
self.image = self.image.resize((self.image.size[0],self.image.size[0]/2))
if self.image.size[0]<1800:
self.image = self.image.resize((1800,900))
# self.image_string = self.image.tostring()
if (self.water_level != 0 and self.name != "earth") or (self.water_level != 1 and self.name == "earth"):
# print "Changing water level to " + str(self.water_level)
self.change_water_level(self.water_level)
else:
if force_reload:
del self.image
self.load_for_drawing()
def unload_from_drawing(self):
"""
Function that unloads the picture of a planet from memory after zoom_out
"""
#print "now unloading " + str(self.planet_name)
try: self.image
except AttributeError:
pass
else:
del self.image
# try: self.image_string
# except AttributeError:
# pass
# else:
# del self.image_string
try: self.heat_bar
except AttributeError:
pass
else:
del self.heat_bar
self.pre_drawn_action_layers = {}
def calculate_topography(self):
"""
Function that checks if a topography picture exists in the /images/planet/topo
If not it "calculates" the topography based on the physical picture
This is of course only an approximation to make it look realistic
In all cases the output is that self.topo_image will contain a topographical image
where red is lowest and yellow is highest.
"""
#check if this has already been loaded
try: self.topo_image
except AttributeError:
#test if a pre-calculated topo-file exists
topo_file_name_and_path = os.path.join("images","planet","topo",str(self.planet_name + ".png"))
if os.access(topo_file_name_and_path,os.R_OK):
self.topo_image = Image.open(topo_file_name_and_path)
#print "topo file does not exist for " + str(self.planet_name) + " - all ok"
else:
#print "topo file does not exist for " + str(self.planet_name)
#see if a regular image has already been loaded
if self.planet_type != "gasplanet":
try: self.image
except AttributeError:
#print "self.image does not exist running load_for_drawing"
self.load_for_drawing()
regular_image = self.image
else:
regular_image = self.image
regular_image = ImageOps.grayscale(regular_image)
topo_image = ImageOps.posterize(regular_image, 5)
topo_image = ImageOps.colorize(topo_image,"red","yellow")
topo_image = topo_image.resize((720,360))
#topo_image.save("test.png") #for testing purposes
self.topo_image = topo_image
else: #planet is a gasplanet
self.topo_image = Image.new("RGB",(720,360),(255,0,0))
else:
#print "self.topo_image does exists - all ok"
pass
def change_water_level(self,new_water_level):
"""
Function to redraw the wet_area image for a planet, after the water level of that planet has been changed
It checks if the topographical map has been loaded, and loads it if not it then computes the layout of
the different topological levels. The function also checks if bases are getting flooded and removes them if necessary.
The function saves a self.action_layer which is an "L" mode image that can receive region specific information. Currently this
values are defined:
191 - 220 are for newly flooded areas, 221 being for the lowest
221 - 250 are for half-wet flooded areas, 221 being for the lowest. Only one number in this range should therefore exist
255 is for dry areas
0 is for earth oceans
They can be translated with the convert_to_rgba
"""
#testing if self.topo exists
try: self.topo_image
except AttributeError:
self.calculate_topography()
topo_image = self.topo_image
#converting to BW
topo_image_bw = ImageOps.grayscale(topo_image)
assert topo_image_bw.mode == "L"
# makes a dictionary with the topology level as key and a tuble of color-span for which this topology holds as the value
colors_in_topo = topo_image_bw.getcolors()
# print "colors_in_topo: " + str(colors_in_topo) #[(153835, 76), (30, 77), (42
table_of_topology = {0:(0,0)}
#we would like all planets to have max 30 levels of topology - the sum of all color[0] equals the number of pixels in the image
pixels_in_image = topo_image_bw.size[0] * topo_image_bw.size[1]
pixels_each_level = pixels_in_image / 30
# print "pixels_each_level: " + str(pixels_each_level)
sum_of_pixels = 0
i = 1
for color in colors_in_topo:
sum_of_pixels = sum_of_pixels + color[0]
if sum_of_pixels > pixels_each_level:
topology_color_range = (table_of_topology[i-1][1],color[1])
table_of_topology[i] = topology_color_range
i = i + 1
sum_of_pixels = 0
del table_of_topology[0]
# print "table_of_topology: " + str(table_of_topology) #{1: (0, 76), 2: (76, 90), 3: (90, 113), 4: (113, 127), 5: (127, 137), 6: (137, 141)}
# print "the planet " + self.planet_name+ " has " + str(len(table_of_topology)) +" levels of topology"
if new_water_level > len(table_of_topology):
new_water_level = len(table_of_topology)
if self.solar_system_object_link.message_printing["debugging"]:
print_dict = {"text":"The planet " + str(self.planet_name) + " has reached its max water level of " + str(len(table_of_topology)),"type":"debugging"}
self.solar_system_object_link.messages.append(print_dict)
table_of_colors = []
for i in range(256):
topology_level_here = None
for topology_level in table_of_topology:
if table_of_topology[topology_level][0] < i <= table_of_topology[topology_level][1]:
topology_level_here = topology_level
break
if topology_level_here is None:
new_color = 255
elif topology_level_here == 1 and self.planet_name == "earth":
new_color = 0
elif topology_level_here <= new_water_level:
new_color = 190 + topology_level_here
elif topology_level_here - 0.5 == new_water_level:
new_color = 220 + topology_level_here
else:
new_color = 255
table_of_colors.append(new_color)
self.action_layer = topo_image_bw.point(table_of_colors)
self.pre_drawn_action_layers = {}
#determines how the bases on the planet fare in the surge. Bases under water are removed.
bases_to_remove = []
for base in self.bases:
if self.bases[base].terrain_type != "Space":
position_x_degrees = self.bases[base].position_coordinate[0]
position_y_degrees = self.bases[base].position_coordinate[1]
position_x_pixel = int(((position_x_degrees + 180.0 ) / 360.0) * self.action_layer.size[0])
position_y_pixel = int(self.action_layer.size[1] - ((position_y_degrees + 90.0 ) / 180.0) * self.action_layer.size[1])
pixel_color = self.action_layer.getpixel((position_x_pixel,position_y_pixel))
if 190 < pixel_color <= 220 or pixel_color == 0:
self.bases[base].is_on_dry_land = "no"
bases_to_remove.append(base)
elif 220 < pixel_color <= 250:
self.bases[base].is_on_dry_land = "almost"
else:
self.bases[base].is_on_dry_land = "yes"
for base in bases_to_remove:
self.kill_a_base(base)
if new_water_level != self.water_level:
self.water_level = new_water_level
def convert_to_rgba(self,image):
"""
Function that takes a image with information about the surface and converts it to an RGBA type image ready for drawing
Read the change_water_level documentation for more info on the different value codes.
"""
water_colors = {
1:(16,40,44),
2:(18,44,50),
3:(19,49,54),
4:(20,51,56),
5:(22,58,61),
6:(25,63,69),
7:(28,66,72),
8:(30,70,76),
9:(33,73,79),
10:(33,83,82),
11:(36,86,85),
12:(37,84,90),
13:(40,87,93),
14:(39,88,94),
15:(40,90,97),
16:(41,93,99),
17:(42,95,102),
18:(43,98,105),
19:(44,100,107),
20:(45,102,110),
21:(46,104,112),
22:(47,107,115),
23:(48,110,117),
24:(49,112,120),
25:(50,114,123),
26:(51,117,125),
27:(52,119,128),
28:(53,121,131),
29:(54,121,131),
30:(53,121,131)}
assert image.mode == "L"
table_of_colors = []
for band in range(4):
for i in range(256):
if band < 3:
if 190 < i <= 220:
RGB_color = water_colors[i - 190]
new_color = RGB_color[band]
elif 220 < i <= 250:
RGB_color = water_colors[i - 220]
new_color = RGB_color[band]
else:
new_color = 0
else:
if 190 < i <= 220:
new_color = 255
elif 220 < i <= 250:
new_color = 255/2
else:
new_color = 0
table_of_colors.append(new_color)
new_image = image.point(table_of_colors,"RGBA")
return new_image
def sphere_to_plane_total(self,sphere_coordinates,eastern_inclination,northern_inclination,projection_scaling):
"""
Function to translate a list of single sphere_coordinates into projection coordinates with only one
query to the proj program. Takes a list of tuples with sphere_coordinates.
This is much faster than the old sphere_to_plane()
General notes on maps:
Three map coordinate types:
Sphere... nothing is ever rendered like this. It is a tuple with (range(-180,180),range(-90,90),
which corresponds to degrees. The first longitude / x / east-west, the second is latitude / y / north_south.
Map.... the source map. It has map_coordinates that correspond to the size of the map (range(0, width(map))
, range(0,height(map))). The map_coordinates are directly translatable to sphere_coordinates and are of course
(east/west,north/south)
Projection.... the main rendition of the planet projection. It has projection_coordinates (range(0,1*scale),range(0,1*scale))
which corresponds to the location on the screen (top left is (0,0), further east is (1,0), and further
south is (0,1). Pixels outside of the globe-projection are black. An important concept is the rotation
which is the amount of turning the planet has seen relative to the 0 N, 0 W position. This is
given as rotation_coordinates (range(-180,180),range(-90,90))
The idea is to draw the projection by taking each pixel in the rendition, looking up its translation
to sphere_coordinates and then paint the corresponding projection_coordinate.
"""
projection_coordinates = []
if self.projection_scaling <= 360: #for the round world projection
#Creating the string that goes into the proj command
communication_string = ""
for i in range(0,len(sphere_coordinates)):
#projection_coordinates.append((i-(i/projection_dim[0])*projection_dim[0],i / projection_dim[1]))
x_sphere = sphere_coordinates[i][0]
y_sphere = sphere_coordinates[i][1]
communication_string = communication_string + (str(x_sphere) + " " + str(y_sphere) + "\n")
startup_string = "proj +proj=ortho +ellps=sphere +lon_0=" + str(eastern_inclination) + " +lat_0=" + str(northern_inclination)
try: proj = subprocess.Popen(startup_string,stdin=subprocess.PIPE,stdout=subprocess.PIPE, shell = True)
except:
raise Exception("Calling the subprocess proj did not work. On windows machines that is weird. On unix-based machines it probably means that you should install proj 4.6. Check your local repository or google for proj + cartographic")
else:
pass
stdout_tuple = proj.communicate(bytes(communication_string, 'utf-8'))
if len(stdout_tuple[0]) == 0:
try:
raise RuntimeError("The proj command did not return anything. This is probably because the proj command is not installed on your system")
except Exception as e:
raise proj_not_working_error from e
stdout_text = [None if stdout is None else bytes.decode(stdout, 'utf-8') for stdout in stdout_tuple ]
stdout_text = stdout_text[0].split("\n")
for i in range(0,len(stdout_text)):
if stdout_text[i].find("*") != -1:
projection_coordinates.append("Not seen")
elif len(stdout_text[i]) < 5: #to remove empty lines
pass
else:
splitting = stdout_text[i].partition("\t")
x_raw = splitting[0]
y_raw = splitting[2]
x_raw = float(x_raw.rstrip("\r"))
y_raw = float(y_raw.rstrip("\r"))
x_proj = ( x_raw / 6370997 ) * (projection_scaling * 0.5) + (projection_scaling * 0.5) #where 6370997 is the constant of the proj program
y_proj = -( y_raw / 5986778 ) * (projection_scaling * 0.5) + (projection_scaling * 0.5)
projection_coordinates.append((x_proj,y_proj))
if len(projection_coordinates) != len(sphere_coordinates):
try:
raise RuntimeError("The number of projection coordinates does not match the number of sphere coordinates")
except Exception as e:
raise proj_not_working_error from e
else: #planar map projection
window_size = global_variables.window_size
west_border = self.flat_image_borders["west_border"]
east_border = self.flat_image_borders["east_border"]
south_border = self.flat_image_borders["south_border"]
north_border = self.flat_image_borders["north_border"]
east_west_span = float(east_border - west_border) #114
north_south_span = float(north_border - south_border)
# sphere_hit_locations = []
for sphere_coordinate in sphere_coordinates:
if (west_border < sphere_coordinate[0] < east_border) and (south_border < sphere_coordinate[1] < north_border):
x_proj_position = (( sphere_coordinate[0] - west_border) / east_west_span ) * window_size[0]
y_proj_position = window_size[1] - ((( sphere_coordinate[1] - south_border ) / north_south_span ) * window_size[1])
projection_coordinates.append((int(x_proj_position),int(y_proj_position)))
else:
projection_coordinates.append("Not seen")
return projection_coordinates
def plane_to_sphere_total(self,eastern_inclination,northern_inclination,projection_scaling,given_coordinates = None):
"""
The function that calculates the relation of all the points on the projection to their sphere coordinates
It returns a dictionary of all projection coordinates and their corresponding sphere coordinates
This way is probably faster than many single queries to the proj command
Optional variables:
given_coordinates - if given as tuple or a list of tuples this will limit the algorithm to give only these as sphere_coordinates
"""
def parse_coordinate_from_sphere(coordinate):
if len(coordinate) > 3:
if coordinate.find("S") > 0 or coordinate.find("W") > 0:
negative_direction = True
else:
negative_direction = False
degrees = float(coordinate[0:coordinate.find("d")])
if coordinate.find("\'") != -1:
minutes = float(coordinate[coordinate.find("d")+1:coordinate.find("\'")])
else:
minutes = 0
if coordinate.find("\"") != -1:
seconds = float(coordinate[coordinate.find("\'")+1:coordinate.find("\"")])
else:
seconds = 0
decimal_degrees = degrees + minutes/60.0 + seconds/(60.0*60.0)
if negative_direction:
decimal_degrees = -decimal_degrees
else:
decimal_degrees = 0.0
return decimal_degrees
projection_dim = (projection_scaling,projection_scaling)
rotation_coordinates = (eastern_inclination,northern_inclination)
startup_string = "proj -I +proj=ortho +ellps=sphere +lat_0=" + str(-rotation_coordinates[1]) + " +lon_0=" + str(rotation_coordinates[0])
communication_string = ""
sphere_coordinates = []
projection_coordinates=[]
plane_to_sphere = {}
#new_image_string=""
if projection_scaling <= 360: #for the round world projection
if isinstance(given_coordinates,list) or isinstance(given_coordinates,tuple):
if isinstance(given_coordinates,tuple):
given_coordinates = [given_coordinates]
#Creating the string that goes into the proj command
for coordinate in given_coordinates:
projection_coordinates.append(coordinate)
x_proj = ((coordinate[0] / (projection_dim[0]*0.5)) -1.0) * 6370997
y_proj = ((coordinate[1] / (projection_dim[1]*0.5)) -1.0) * 6370997
communication_string = communication_string + (str(x_proj) + " " + str(y_proj) + "\n")
elif given_coordinates == None:
#Creating the string that goes into the proj command
for i in range(0,(projection_dim[0]*projection_dim[1])):
projection_coordinates.append((i-(i/projection_dim[0])*projection_dim[0],i / projection_dim[1])) #testing to see if the integer round works to my advantage
x_proj = ((projection_coordinates[i][0] / (projection_dim[0]*0.5)) -1.0) * 6370997
y_proj = ((projection_coordinates[i][1] / (projection_dim[1]*0.5)) -1.0) * 6370997
communication_string = communication_string + (str(x_proj) + " " + str(y_proj) + "\n")
else:
raise Exception("Major error in plane_to_sphere_total - the coordinates given does not make sense")
try: proj = subprocess.Popen(startup_string,stdin=subprocess.PIPE,stdout=subprocess.PIPE, shell = True)
except:
raise Exception("Calling the subprocess proj did not work. On windows machines that is weird. On unix-based machines it probably means that you should install proj 4.6. Check your local repository or google for proj + cartographic")
else:
pass
stdout_text = proj.communicate(bytes(communication_string, 'utf-8'))
if isinstance(stdout_text[0], bytes):
stdout_text = stdout_text[0].decode('utf-8').split("\n")
else:
stdout_text = stdout_text[0].split("\n")
#print "stdout_text: " + str(stdout_text)
for i in range(0,len(stdout_text)-1):
if stdout_text[i].find("*") != -1:
plane_to_sphere[projection_coordinates[i]] = "space"
else:
splitting = stdout_text[i].partition("\t")
x_total = splitting[0]
y_total = splitting[2]
sphere_coordinates_x = parse_coordinate_from_sphere(x_total)
sphere_coordinates_y = parse_coordinate_from_sphere(y_total)
plane_to_sphere[projection_coordinates[i]] = (sphere_coordinates_x,-sphere_coordinates_y)
else: #fot the flat world projection
if isinstance(given_coordinates,list) or isinstance(given_coordinates,tuple):
if isinstance(given_coordinates,tuple):
given_coordinates = [given_coordinates]
window_size = global_variables.window_size
west_border = self.flat_image_borders["west_border"]
east_border = self.flat_image_borders["east_border"]
south_border = self.flat_image_borders["south_border"]
north_border = self.flat_image_borders["north_border"]
east_west_span = east_border - west_border
north_south_span = north_border - south_border
for proj_position in given_coordinates:
x_sphere_position = (float(proj_position[0]) / float(window_size[0]) ) * east_west_span + west_border
y_sphere_position = ((float(window_size[1]) - float(proj_position[1])) / window_size[1] ) * north_south_span + south_border
plane_to_sphere[proj_position] =(x_sphere_position,y_sphere_position)
else:
raise Exception("Major error in plane_to_sphere_total - the coordinates given does not make sense")
return plane_to_sphere
def calculate_resource_map(self,resource_type):
"""
Function that checks if a resource picture exists in the /images/planet/nonrenewable materials map/"resource_type"
If not it "calculates" the topography based random parameters
In all cases the output is that self.resource_maps will contain a resource image of size (90,45)
where red is lowest and yellow is highest.
"""
#try to find the proper non-renewable resource map
try: self.resource_maps[resource_type]
except:
resource_file_name_and_path = os.path.join("images","planet","nonrenewable materials map",resource_type,str(self.planet_name + ".png"))
if os.access(resource_file_name_and_path,os.R_OK):
resource_map_image = Image.open(resource_file_name_and_path)
#print "resource file " + str(resource_type) + " does exist for " + str(self.planet_name) + " - all ok"
else:
#print "resource file " + str(resource_type) + " does not exist for " + str(self.planet_name) + " - creating a random"
resource_map_image = Image.new("L",(90,45))
lut = []
x_offset = random.random()
x_skewing = random.random()
x_band_clearness = random.random()*0.8
y_offset = random.random()
y_skewing = random.random()
y_band_clearness = random.random() * 0.8
resource_type_in_database = "ground_" + str(resource_type)
try: self.planet_data[resource_type_in_database]
except:
resource_level = 1
print("The resource_level for " + str(resource_type_in_database) + " was not found in planet_database so the background value was set to 1")
else:
resource_level = self.planet_data[resource_type_in_database]
#print (x_offset,x_skewing,x_band_clearness,y_offset,y_skewing,y_band_clearness)
if self.planet_type != "gasplanet":
for y in range(0,45):
for x in range(0,90):
pixel = (random.randint(0,255) + math.sin((x / 90.0)* 2 * math.pi + x_offset*90 + y_skewing*(y/7.0))*100 * x_band_clearness + math.sin((y / 90.0)* 2 * math.pi + y_offset*90 + x_skewing*(y/7.0))*100 * y_band_clearness) * resource_level
lut.append(pixel)
else:
for y in range(0,45):
for x in range(0,90):
pixel = 0
lut.append(pixel)
resource_map_image.putdata(lut)
enhancer = ImageEnhance.Sharpness(resource_map_image)
resource_map_image = enhancer.enhance(0)
#making the correct colors
lut = []
for i in range(256):
lut.extend([255, i, 0])
resource_map_image.putpalette(lut)
resource_map_image = resource_map_image.convert("RGB")
#print "saving calculated map"
#resource_map_image.save("testingresourcemap.png")
self.resource_maps[resource_type] = resource_map_image
else:
pass
#The self.resource_maps[resource_type] does already exist
def draw_overlay_map(self,eastern_inclination,northern_inclination,projection_scaling,resource_type):
"""
Function that gives a surface with a given overlay
The type can be topographical or the name of non-renewable resource used
It will first check if the map in question already exists, and if not it will generate it
The topographical needs to be special, because it is calculated from the looks of the actual surface.
Also this map is size (720,360) because it needs to be somewhat fine-grained for water-rising purposes
The non-renewable resource is calculated entire at random if it does not exists. It is only a (90,45)
size map so it shouldn't be too much to have a lot of them in memory.
The output is a pysurface for use with other plotting mechanisms.
The resolution of the surface will be automatically decreased as proper for the displaytype (topo/resource)
"""
#image_string = image.tostring()
if resource_type == "topographical":
#retrieve the topographical map.
self.calculate_topography()
overlay_image = self.topo_image
else:
self.calculate_resource_map(resource_type)
overlay_image = self.resource_maps[resource_type].copy()
if self.current_base is not None:
overlay_image = self.current_base.draw_mining_area(self,overlay_image)
overlay_image = overlay_image.convert("RGB")
surface = self.draw_image(eastern_inclination, northern_inclination,projection_scaling,fast_rendering=True,image=overlay_image)
return surface
def draw_image(self,eastern_inclination,northern_inclination,projection_scaling,fast_rendering=False,image=None,plane_to_sphere = None):
"""
Function that gives the actual surface for use with pysurface, of a planet the zoom/rotation parameters.
Optional arguments
fast_rendering boolean, False per default. If set to true the projection scaling will be halved for spherical
projections and the surface will be doubled before returning. This gives much faster calculation
times
image an image can be fed to the function (such as for example a topographical map) and then this
will be projected instead. If not the function will use the self.image (fixme delete and self.image_string)
plane_to_sphere The output from plane_to_sphere_total() given for special renditions. If not given it will load from the standard
calculations (ie. all lat/long's divisible by 30)
"""
if image != None:
check_memory = False #should only save images to memory when they are not resource/topographical overlays
else:
try: self.image
except: