ursina_simulator.py 9.3 KB
Newer Older
三月三net's avatar
三月三net 已提交
1 2 3 4 5 6 7 8 9
# -*- coding:utf-8 -*-
# title           :ursina天体运行模拟器
# description     :ursina天体运行模拟器
# author          :Python超人
# date            :2023-02-11
# link            :https://gitcode.net/pythoncr/
# python_version  :3.8
# ==============================================================================
# pip install -i http://pypi.douban.com/simple/ --trusted-host=pypi.douban.com ursina
M
march3 已提交
10
from ursina import Ursina, window, Entity, camera, color, mouse, Vec2, Vec3, load_texture, held_keys
M
march3 已提交
11
from ursina.prefabs.first_person_controller import FirstPersonController
M
march3 已提交
12 13

from simulators.views.ursina_view import UrsinaView, UrsinaPlayer
三月三net's avatar
三月三net 已提交
14

M
march3 已提交
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
# # -------------------------------------------------------------------------------
# app = Ursina()
# # window.fullscreen = True
# window.color = color.black
#
# planets = []
#
#
# class Planet(Entity):
#     def __init__(self, _type, pos, texture, scale=2):
#         self.angle = rd.uniform(0.0005, 0.01)
#         self.fastMode = 0
#         self.rotation = (rd.randint(0, 360) for i in range(3))
#         self.rotspeed = rd.uniform(0.25, 1.5)
#         self.rotMode = rd.choice(["x", "y", "z"])
#         self._type = _type
#         # texture = eval(f"{_type}_texture")
#         texture = load_texture(texture)
#         super().__init__(model="sphere",
#                          scale=scale,
#                          texture=texture,
#                          color=color.white,
#                          position=pos)
#
#     def turn(self, angle):
#         # if self._type != "sun":
#         #     if self.fastMode:
#         #         angle *= 200
#         # self.x = self.x * cos(radians(angle)) - self.y * sin(radians(angle))
#         # self.y = self.x * sin(radians(angle)) + self.y * cos(radians(angle))
#         exec(f"self.rotation_{self.rotMode}+=self.rotspeed")
#     #
#     def input(self, key):
#         if key == "enter":
#             self.fastMode = 1 - self.fastMode
#
#
#
#
#
三月三net's avatar
三月三net 已提交
55 56 57 58 59 60
# def update():
#     global planets, player
#     for planet in planets:
#         planet.turn(planet.angle)
#     player._update()
#
M
march3 已提交
61 62
# # os.chdir("../")
#
三月三net's avatar
三月三net 已提交
63
#
M
march3 已提交
64 65 66 67 68 69 70 71 72 73 74
# # sun_texture = load_texture(texture_root + "sun.png")
# # mercury_texture = load_texture(texture_root + "mercury.png")
# # venus_texture = load_texture(texture_root + "venus.png")
# # earth_texture = load_texture(texture_root + "earth.png")
# # mars_texture = load_texture(texture_root + "mars.png")
# # jupiter_texture = load_texture(texture_root + "jupiter.png")
# # saturn_texture = load_texture(texture_root + "saturn.png")
# # uranus_texture = load_texture(texture_root + "uranus.png")
# # neptune_texture = load_texture(texture_root + "neptune.png")
#
# texture_root = "../textures/"
三月三net's avatar
三月三net 已提交
75
# ps = ["sun", "mercury", "venus", "earth", "mars", "jupiter", "saturn", "uranus", "neptune"]
M
march3 已提交
76
# cp = [200, 15, 35, 42, 20, 160, 145, 90, 80]  # 大小缩放
三月三net's avatar
三月三net 已提交
77 78
# x, y, z = 0, 0, 0
# for i, p in enumerate(ps):
M
march3 已提交
79 80
#     # _type, pos, texture, scale=2
#     newPlanet = Planet(p, (x, y, z),texture_root+f"{p}.png", cp[i])
三月三net's avatar
三月三net 已提交
81 82 83
#     planets.append(newPlanet)
#     x += cp[i] * 10
#
M
march3 已提交
84 85
# player = Player(planets)
#
三月三net's avatar
三月三net 已提交
86
# if __name__ == '__main__':
M
march3 已提交
87
#     # os.chdir("../")
三月三net's avatar
三月三net 已提交
88 89 90
#     # sun_texture = os.path.join(texture_root, "sun.png")
#     # print(os.path.exists(sun_texture))
#     app.run()
M
march3 已提交
91 92 93 94
#
# # ---------------------------------------------------------------------------


三月三net's avatar
三月三net 已提交
95 96
from simulators.simulator import Simulator
from common.system import System
M
march3 已提交
97 98
import time
import datetime
三月三net's avatar
三月三net 已提交
99
from ursina import EditorCamera, PointLight, SpotLight, AmbientLight
三月三net's avatar
三月三net 已提交
100

M
march3 已提交
101 102 103
player = None


三月三net's avatar
三月三net 已提交
104 105 106
class UrsinaSimulator(Simulator):
    def __init__(self, bodies_sys: System):
        self.app = Ursina()
M
march3 已提交
107
        self.ursina_views = []
三月三net's avatar
三月三net 已提交
108 109 110 111 112 113 114
        window.color = color.black

        super().__init__(bodies_sys, UrsinaView)

        # ps = ["sun", "mercury", "venus", "earth", "mars", "jupiter", "saturn", "uranus", "neptune"]
        # cp = [200, 15, 35, 42, 20, 160, 145, 90, 80]
        # x, y, z = 0, 0, 0
M
march3 已提交
115
        for i, view in enumerate(self.body_views):
三月三net's avatar
三月三net 已提交
116
            # pos = tuple(body.position)
M
march3 已提交
117 118
            # ursina_view = UrsinaView(body)
            view.update()
M
march3 已提交
119
            self.ursina_views.append(view)
三月三net's avatar
三月三net 已提交
120 121 122
            # planets.append(newPlanet)
            # x += cp[i] * 10

M
march3 已提交
123 124 125 126
    def check_elapsed_time(self):
        """检查时间间隔是否已过"""
        now = datetime.datetime.now()
        elapsed_time = now - self.last_time
M
march3 已提交
127 128 129 130
        value = elapsed_time >= self.interval
        if value:
            self.last_time = now
        return value
M
march3 已提交
131 132 133 134 135

    def check_and_evolve(self):
        if self.check_elapsed_time():
            super().evolve(self.evolve_dt)

三月三net's avatar
三月三net 已提交
136 137
    def cosmic_background(self, texture='../textures/cosmic1.jpg'):
        texture = load_texture(texture)
三月三net's avatar
三月三net 已提交
138
        sky_dome = Entity(model='sky_dome', texture=texture, scale=500,
三月三net's avatar
三月三net 已提交
139 140 141 142
                          color=color.white,
                          position=(0, 0, 0),
                          rotation=(0, 0, 0))

三月三net's avatar
三月三net 已提交
143
    def run(self, dt, **kwargs):
M
march3 已提交
144 145
        self.evolve_dt = dt
        # 设定时间间隔为1秒
M
march3 已提交
146 147
        self.interval = datetime.timedelta(seconds=0.01)
        self.last_time = datetime.datetime.now() - datetime.timedelta(seconds=2)
三月三net's avatar
三月三net 已提交
148 149 150 151 152 153 154 155 156 157
        if "light" in kwargs:
            if kwargs["light"]:
                li = PointLight()
        # PointLight, SpotLight, AmbientLight
        if "cosmic_bg" in kwargs:
            cosmic_bg = kwargs["cosmic_bg"]
            import os
            if cosmic_bg is not None and os.path.exists(cosmic_bg):
                self.cosmic_background(cosmic_bg)

三月三net's avatar
三月三net 已提交
158
        EditorCamera()
三月三net's avatar
三月三net 已提交
159 160
        self.app.run()

M
march3 已提交
161

三月三net's avatar
三月三net 已提交
162
if __name__ == '__main__':
M
march3 已提交
163
    from bodies import Sun, Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto, Moon
三月三net's avatar
三月三net 已提交
164
    from common.consts import SECONDS_PER_WEEK, SECONDS_PER_DAY, SECONDS_PER_HALF_DAY
三月三net's avatar
三月三net 已提交
165 166 167 168 169

    """
    3个太阳、1个地球
    """
    bodies = [
M
march3 已提交
170
        Sun(name='太阳1', mass=1.5e30, init_position=[849597870.700, 0, 0], init_velocity=[0, 7.0, 0],
三月三net's avatar
三月三net 已提交
171
            size_scale=5e1, texture="sun.png"),  # 太阳放大 100 倍
M
march3 已提交
172
        Sun(name='太阳2', mass=2e30, init_position=[0, 0, 0], init_velocity=[0, -8.0, 0],
三月三net's avatar
三月三net 已提交
173
            size_scale=5e1, texture="sun.png"),  # 太阳放大 100 倍
M
march3 已提交
174
        Sun(name='太阳3', mass=2.5e30, init_position=[0, -849597870.700, 0], init_velocity=[18.0, 0, 0],
三月三net's avatar
三月三net 已提交
175
            size_scale=5e1, texture="sun.png"),  # 太阳放大 100 倍
M
march3 已提交
176
        Earth(name='地球', init_position=[0, -349597870.700, 0], init_velocity=[15.50, 0, 0],
三月三net's avatar
三月三net 已提交
177 178
              size_scale=4e3, texture="earth.png", distance_scale=1),  # 地球放大 4000 倍,距离保持不变
    ]
M
march3 已提交
179 180 181 182 183 184 185 186 187 188 189
    # bodies = [
    #
    #     Sun(name='太阳2', mass=1.5e30, init_position=[0, 0, 0], init_velocity=[0, -8.0, 0],
    #         size_scale=5e1, texture="sun.png"),  # 太阳放大 100 倍
    #     Sun(name='太阳2', mass=1.5e30, init_position=[849597870.700, 0, 0], init_velocity=[0, -8.0, 0],
    #         size_scale=5e1, texture="sun.png"),  # 太阳放大 100 倍
    #     Sun(name='太阳2', mass=1.5e30, init_position=[0, -849597870.700, 0], init_velocity=[0, -8.0, 0],
    #         size_scale=5e1, texture="sun.png"),  # 太阳放大 100 倍
    #     Earth(name='地球', mass=5.97237e24, init_position=[0, -349597870.700, 0], init_velocity=[15.50, 0, 0],
    #           size_scale=4e3, texture="earth.png", distance_scale=1),  # 地球放大 4000 倍,距离保持不变
    # ]
M
march3 已提交
190
    bodies = [
三月三net's avatar
三月三net 已提交
191 192 193 194
        Sun(size_scale=0.8e2),  # 太阳放大 80 倍
        Mercury(size_scale=4e3, distance_scale=1.3),  # 水星放大 4000 倍,距离放大 1.3 倍
        Venus(size_scale=4e3, distance_scale=1.3),  # 金星放大 4000 倍,距离放大 1.3 倍
        Earth(size_scale=4e3, distance_scale=1.3),  # 地球放大 4000 倍,距离放大 1.3 倍
M
march3 已提交
195
        Moon(size_scale=4e3, distance_scale=1.3),
三月三net's avatar
三月三net 已提交
196
        Mars(size_scale=4e3, distance_scale=1.3),  # 火星放大 4000 倍,距离放大 1.3 倍
M
march3 已提交
197
        Jupiter(size_scale=0.68e3, distance_scale=0.65),  # 木星放大 680 倍,距离缩小到真实距离的 0.65
三月三net's avatar
三月三net 已提交
198 199 200 201
        Saturn(size_scale=0.68e3, distance_scale=0.52),  # 土星放大 680 倍,距离缩小到真实距离的 0.52
        Uranus(size_scale=0.8e3, distance_scale=0.36),  # 天王星放大 800 倍,距离缩小到真实距离的 0.36
        Neptune(size_scale=1e3, distance_scale=0.27),  # 海王星放大 1000 倍,距离缩小到真实距离的 0.27
        Pluto(size_scale=10e3, distance_scale=0.23),  # 冥王星放大 10000 倍,距离缩小到真实距离的 0.23(从太阳系的行星中排除)
M
march3 已提交
202
    ]
M
march3 已提交
203 204

    # bodies.append(Moon(size_scale=4e3, distance_scale=1.3))  # 月球放大 10 倍,距离保持不变)
M
march3 已提交
205 206 207 208
    # bodies = [
    #     Saturn(size_scale=0.68e3, init_position=[0, 0, 0],
    #            init_velocity=[0, 0, 0], distance_scale=0.52),  # 土星放大 680 倍,距离缩小到真实距离的 0.52
    #  ]
三月三net's avatar
三月三net 已提交
209 210 211
    body_sys = System(bodies)
    simulator = UrsinaSimulator(body_sys)

M
march3 已提交
212
    player = UrsinaPlayer((4000000, 800000000, 4000000), simulator.ursina_views)
三月三net's avatar
三月三net 已提交
213 214


M
march3 已提交
215
    # player = FirstPersonController()
M
march3 已提交
216
    # player = UrsinaPlayer((0, 0, 0), simulator.ursina_views)
M
march3 已提交
217 218 219

    def update():
        # print('OK')
M
march3 已提交
220 221
        for ursina_view in simulator.ursina_views:
            simulator.check_and_evolve()
M
march3 已提交
222 223
            ursina_view.update()
            # ursina_view.entity.turn(ursina_view.entity.angle)
M
march3 已提交
224
        # player._update()
M
march3 已提交
225 226


三月三net's avatar
三月三net 已提交
227
    light = True
三月三net's avatar
三月三net 已提交
228
    cosmic_bg = '../textures/cosmic1.png'
三月三net's avatar
三月三net 已提交
229 230
    # cosmic_bg = None
    simulator.run(SECONDS_PER_DAY, light=light, cosmic_bg=cosmic_bg)