ursina_view.py 8.3 KB
Newer Older
三月三net's avatar
三月三net 已提交
1 2 3 4 5 6 7 8 9
# -*- coding:utf-8 -*-
# title           :ursina天体视图
# description     :ursina天体视图(天体效果展示用,需要安装 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 11 12 13
from ursina import Ursina, window, Entity, Mesh, SmoothFollow, Texture, clamp, time, camera, color, mouse, Vec2, Vec3, \
    load_texture, held_keys

# from ursina.camera import OrthographicCamera
M
march3 已提交
14 15 16 17 18
from math import sin, cos, radians
from ursina.prefabs.first_person_controller import FirstPersonController
import sys
import random as rd
import os
三月三net's avatar
三月三net 已提交
19 20 21 22
from bodies import Body
import random
from simulators.views.body_view import BodyView
import numpy as np
M
march3 已提交
23
import math
三月三net's avatar
三月三net 已提交
24

三月三net's avatar
三月三net 已提交
25 26 27
SCALE_FACTOR = 5e-7
# 旋转因子为1,则为正常的转速
ROTATION_SPEED_FACTOR = 1.0
三月三net's avatar
三月三net 已提交
28
ROTATION_SPEED_FACTOR = 0.01
M
march3 已提交
29 30


三月三net's avatar
三月三net 已提交
31 32
class UrsinaPlayer(FirstPersonController):
    """
M
march3 已提交
33

三月三net's avatar
三月三net 已提交
34
    """
M
march3 已提交
35

M
march3 已提交
36
    def __init__(self, position, targets=None):
M
march3 已提交
37 38
        super().__init__()
        camera.fov = 100
M
march3 已提交
39 40
        camera.rotation_y = 90
        self.planets = None
M
march3 已提交
41
        if targets is not None:
M
march3 已提交
42
            self.planets = []
M
march3 已提交
43
            # targets = [view.planet.parent for view in targets]
M
march3 已提交
44
            # targets_parent = Entity()
M
march3 已提交
45
            for view in targets:
M
march3 已提交
46 47 48 49 50 51
                # view.planet.parent = targets_parent
                self.planets.append(view.planet)
            # self.camera_adj(planets)
            #     # planets.append(view.planet)
            #
            # camera.add_script(SmoothFollow(targets_parent, offset=(0, 8, -20)))
M
march3 已提交
52
        pos = np.array(position) * SCALE_FACTOR
三月三net's avatar
三月三net 已提交
53
        # self.position = Vec3(pos[0], pos[1], pos[2])
M
march3 已提交
54
        # 将摄像机位置设置为 x=0、y=1、z=0 的位置
三月三net's avatar
三月三net 已提交
55
        camera.position = Vec3(pos[0], pos[1], pos[2])
三月三net's avatar
三月三net 已提交
56
        # self.position = Vec3(pos[0], pos[1], pos[2])
M
march3 已提交
57
        # 将摄像机的观察角度绕 x 轴旋转 45 度,绕 y 轴旋转 0 度,绕 z 轴旋转 0 度
三月三net's avatar
三月三net 已提交
58 59
        # camera.rotation = Vec3(45, 90, 0)
        camera.rotation = Vec3(0, 0, 0)
M
march3 已提交
60

三月三net's avatar
三月三net 已提交
61 62 63 64
        # self.gravity = 0
        # self.vspeed = 400
        # self.speed = 1000
        # self.mouse_sensitivity = Vec2(160, 160)
M
march3 已提交
65
        self.on_enable()
三月三net's avatar
三月三net 已提交
66
        # self.rotation_speed = 80
M
march3 已提交
67

M
march3 已提交
68 69 70 71 72 73
    def input(self, key):
        if key == "escape":
            if mouse.locked:
                self.on_disable()
            else:
                sys.exit()
M
march3 已提交
74
        return super().input(key)
M
march3 已提交
75

三月三net's avatar
三月三net 已提交
76

三月三net's avatar
三月三net 已提交
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
from math import pi, sin, cos


# def create_sphere(radius, subdivisions):
#     # 生成球体的顶点、UV坐标、法线和三角面
#     # radius = 1
#     # subdivisions = 16
#     theta = np.linspace(0, 2 * np.pi, subdivisions + 1)
#     phi = np.linspace(0, np.pi, subdivisions + 1)
#     u = np.linspace(0, 1, subdivisions + 1)
#     v = np.linspace(0, 1, subdivisions + 1)
#     verts = []
#     uvs = []
#     normals = []
#     for i in range(len(theta)):
#         for j in range(len(phi)):
#             x = radius * np.sin(phi[j]) * np.cos(theta[i])
#             y = radius * np.sin(phi[j]) * np.sin(theta[i])
#             z = radius * np.cos(phi[j])
#             verts.append((x, y, z))
#             uvs.append((u[i], v[j]))
#             normals.append((x / radius, y / radius, z / radius))
#
#     tris = []
#     for i in range(len(theta)):
#         for j in range(len(phi)):
#             a = i * (subdivisions + 1) + j
#             b = (i + 1) * (subdivisions + 1) + j
#             tris.append((a, b, a + 1))
#             tris.append((a + 1, b, b + 1))
#
#     # # 反转面法线
#     # for i in range(len(tris)):
#     #     a, b, c = tris[i]
#     #     tris[i] = (c, b, a)
#     #     normals[a], normals[b], normals[c] = -Vec3(*normals[a]), -Vec3(*normals[b]), -Vec3(*normals[c])
#     #     normals[a], normals[b], normals[c] = -Vec3(*normals[a]), -Vec3(*normals[b]), -Vec3(*normals[c])
#
#     # 创建球体 Mesh 对象并设置材质
#     sphere_mesh = Mesh(vertices=verts, uvs=uvs, normals=normals, triangles=tris, mode='triangle')
#     return sphere_mesh

def create_sphere(radius, subdivisions):
    verts = []
    tris = []
    normals = []
    uvs = []

    for y in range(subdivisions + 1):
        for x in range(subdivisions + 1):
            x_segment = x / subdivisions
            y_segment = y / subdivisions
            x_pos = cos(x_segment * 2 * pi) * sin(y_segment * pi)
            y_pos = cos(y_segment * pi)
            z_pos = sin(x_segment * 2 * pi) * sin(y_segment * pi)

            verts.append(Vec3(x_pos, y_pos, z_pos) * radius)
            uvs.append(Vec2(x_segment, y_segment))
            normals.append(Vec3(x_pos, y_pos, z_pos))

    for y in range(subdivisions):
        for x in range(subdivisions):
            first = (y * (subdivisions + 1)) + x
            second = first + subdivisions + 1
            tris.append((first, second + 1, second))
            tris.append((first, first + 1, second + 1))

    # 反转面法线
    for i in range(len(tris)):
        a, b, c = tris[i]
        tris[i] = (c, b, a)
        # normals[a], normals[b], normals[c] = -Vec3(*normals[a]), -Vec3(*normals[b]), -Vec3(*normals[c])

    return Mesh(vertices=verts, triangles=tris, normals=normals, uvs=uvs, mode='triangle')


三月三net's avatar
三月三net 已提交
153
class Planet(Entity):
M
march3 已提交
154 155
    def __init__(self, body_view: BodyView):
        self.body_view = body_view
三月三net's avatar
三月三net 已提交
156
        self.rotation_speed = self.body_view.body.rotation_speed
M
march3 已提交
157 158 159
        self.rotMode = 'x'  # random.choice(["x", "y", "z"])
        self.name = body_view.name

M
march3 已提交
160
        pos = body_view.position * body_view.body.distance_scale * SCALE_FACTOR
M
march3 已提交
161 162
        scale = body_view.body.diameter * body_view.body.size_scale * SCALE_FACTOR

三月三net's avatar
三月三net 已提交
163 164
        subdivisions = 32 # int(scale*20)

三月三net's avatar
三月三net 已提交
165
        if hasattr(body_view, "texture"):
三月三net's avatar
三月三net 已提交
166 167 168
            texture = load_texture(body_view.texture)
        else:
            texture = None
M
march3 已提交
169

三月三net's avatar
三月三net 已提交
170
        super().__init__(
三月三net's avatar
三月三net 已提交
171 172
            # model="sphere",
            model=create_sphere(0.5, subdivisions),
三月三net's avatar
三月三net 已提交
173 174 175 176 177
            scale=scale,
            texture=texture,
            color=color.white,
            position=pos,
            rotation=(0, 0, 0))
三月三net's avatar
三月三net 已提交
178

M
march3 已提交
179
    def turn(self):
M
march3 已提交
180
        pos = self.body_view.position * SCALE_FACTOR
三月三net's avatar
三月三net 已提交
181

M
march3 已提交
182 183 184
        self.x = -pos[1]
        self.y = pos[2]
        self.z = pos[0]
M
march3 已提交
185

三月三net's avatar
三月三net 已提交
186 187 188 189 190 191 192 193
        dt = 0
        if hasattr(self.body_view.body, "dt"):
            dt = self.body_view.body.dt
        if self.rotation_speed is None or dt == 0:
            self.rotspeed = 0
            # 旋转速度和大小成反比(未使用真实数据)
            # self.rotspeed = 30000 / self.body_view.raduis  # random.uniform(1.0, 2.0)
        else:
三月三net's avatar
三月三net 已提交
194
            # 是通过月球保持一面面对地球,调整得到
三月三net's avatar
三月三net 已提交
195
            self.rotspeed = self.rotation_speed * (dt / 3600) / 2.4 * ROTATION_SPEED_FACTOR  # / 60 / 24
三月三net's avatar
三月三net 已提交
196 197
            # rotation_speed 度/小时  dt 秒 = (dt / 3600)小时

M
march3 已提交
198
        self.rotation_y -= self.rotspeed
M
march3 已提交
199

三月三net's avatar
三月三net 已提交
200 201 202
    # def input(self, key):
    #     if key == "enter":
    #         self.fastMode = 1 - self.fastMode
三月三net's avatar
三月三net 已提交
203 204 205 206 207 208 209 210 211


class UrsinaView(BodyView):
    """
    ursina天体视图(天体效果展示用)
    """

    def __init__(self, body: Body):
        BodyView.__init__(self, body)
M
march3 已提交
212 213
        self.velocity = body.velocity

M
march3 已提交
214
        self.planet = Planet(self)
M
march3 已提交
215 216 217 218
        if body.has_rings:
            self.create_rings()

    def create_rings(self):
三月三net's avatar
三月三net 已提交
219
        """
三月三net's avatar
三月三net 已提交
220
        创建行星环(使用土星贴图)
三月三net's avatar
三月三net 已提交
221 222
        :return:
        """
三月三net's avatar
三月三net 已提交
223
        # 行星环偏移角度
三月三net's avatar
三月三net 已提交
224
        self.ring_rotation_x = 75
三月三net's avatar
三月三net 已提交
225 226 227 228 229
        # 创建行星环
        self.ring = Entity(parent=self.planet, model="circle", texture='../textures/saturnRings.jpg', scale=2,
                           rotation=(self.ring_rotation_x, 0, 0), double_sided=True)

        # 设置行星环不受灯光影响,否则看不清行星环
三月三net's avatar
三月三net 已提交
230
        self.ring.set_light_off()
三月三net's avatar
三月三net 已提交
231 232

    def update(self):
三月三net's avatar
三月三net 已提交
233
        """
三月三net's avatar
三月三net 已提交
234

三月三net's avatar
三月三net 已提交
235 236 237 238
        :return:
        """
        self.planet.turn()
        # 如果有行星环
三月三net's avatar
三月三net 已提交
239
        if hasattr(self, "ring"):
三月三net's avatar
三月三net 已提交
240 241 242 243
            # 如果有行星环,则不让行星环跟随行星转动
            self.ring.rotation = -Vec3(self.planet.rotation_x - self.ring_rotation_x,
                                       self.planet.rotation_y,
                                       self.planet.rotation_z)
三月三net's avatar
三月三net 已提交
244 245 246 247 248

    def appear(self):
        pass

    def disappear(self):
M
march3 已提交
249
        self.planet.disable()