"""
物理世界管理模块
负责物理世界的创建、配置、更新和销毁
"""

from panda3d.core import Vec3, Point3, ClockObject, ConfigVariableInt
from panda3d.bullet import BulletWorld, BulletSoftBodyWorldInfo
from panda3d.bullet import BulletPersistentManifold
import math
import time
import threading
from collections import deque


class PhysicsWorld:
    """
    物理世界管理类
    管理整个物理模拟环境，包括重力、时间步长、更新循环等
    """
    
    def __init__(self, gravity=Vec3(0, 0, -9.81)):
        """
        初始化物理世界
        
        Args:
            gravity (Vec3): 重力向量，默认为地球重力
        """
        # 创建Bullet物理世界
        self.bullet_world = BulletWorld()
        self.bullet_world.setGravity(gravity)
        
        # 软体世界信息（用于布料和软体物理）
        self.soft_body_world_info = BulletSoftBodyWorldInfo()
        self.soft_body_world_info.setGravity(gravity)
        self.soft_body_world_info.setAirDensity(1.225)
        self.soft_body_world_info.setWaterDensity(1000.0)
        self.soft_body_world_info.setWaterOffset(0.0)
        self.soft_body_world_info.setWaterNormal(Vec3(0, 0, 1))
        
        # 物理参数
        self.gravity = gravity
        self.time_step = 1.0/60.0  # 默认60FPS
        self.max_substeps = 10      # 最大子步数
        self.internal_time_step = 1.0/60.0  # 内部时间步长
        self.solver_iterations = 10  # 求解器迭代次数
        self.solver_tolerance = 0.001  # 求解器容差
        
        # 高级物理参数
        self.enable_split_impulse = True  # 启用分离冲量
        self.split_impulse_penetration_threshold = -0.04  # 分离冲量穿透阈值
        self.ccd_threshold = 0.0  # 连续碰撞检测阈值
        self.ccd_radius = 0.0  # 连续碰撞检测半径
        self.warm_starting = True  # 启用预热
        self.mpr_threshold = 0.0  # MPR阈值
        
        # 力场参数
        self.global_wind = Vec3(0, 0, 0)
        self.global_magnetic_field = Vec3(0, 0, 0)
        self.fluid_density = 1000.0
        self.fluid_viscosity = 0.001
        self.fluid_drag_coefficient = 0.01
        self.fluid_lift_coefficient = 0.01
        
        # 性能监控
        self.performance_stats = {
            'update_count': 0,
            'last_update_time': 0.0,
            'avg_update_time': 0.0,
            'max_update_time': 0.0,
            'min_update_time': float('inf'),
            'frame_times': deque(maxlen=1000),  # 最近1000帧的时间
            'collision_count': 0,
            'constraint_count': 0,
            'active_rigid_bodies': 0,
            'sleeping_rigid_bodies': 0,
            'memory_usage': 0.0,
            'collision_detection_time': 0.0,
            'constraint_solving_time': 0.0,
            'integration_time': 0.0,
            'broad_phase_time': 0.0,
            'narrow_phase_time': 0.0,
            'solver_time': 0.0,
            'islands_count': 0,
            'manifolds_count': 0,
            'contact_points_count': 0,
            'raycast_count': 0,
            'broad_phase_pairs': 0,
            'narrow_phase_pairs': 0
        }
        
        # 时间累积器
        self.time_accumulator = 0.0
        
        # 物理对象容器
        self.rigid_bodies = []
        self.constraints = []
        self.vehicles = []
        self.particles = []
        self.soft_bodies = []
        self.ghost_objects = []  # 幽灵对象（用于触发器）
        self.sensors = []  # 传感器对象
        self.triggers = []  # 触发器对象
        self.force_fields = []  # 力场对象
        self.fluids = []  # 流体对象
        
        # 碰撞回调
        self.collision_callbacks = []
        self.contact_callbacks = []
        self.raycast_callbacks = []
        
        # 多线程支持
        self.use_multithreading = False
        self.thread_count = 1
        self.worker_threads = []
        self.physics_thread = None
        self.physics_thread_lock = threading.Lock()
        
        # 物理场景分区（用于大型场景优化）
        self.spatial_partitioning = None
        self.partition_size = 100.0
        
        # 物理场景状态
        self.is_paused = False
        self.time_scale = 1.0
        self.frame_counter = 0
        
        # 碰撞检测优化
        self.enable_broad_phase = True
        self.enable_narrow_phase = True
        self.enable_continuous_collision = True
        self.enable_contact_caching = True
        self.enable_island_generation = True
        
        # 物理世界配置
        self.enable_sleeping = True
        self.enable_deactivation = True
        self.sleeping_threshold = 0.01
        self.deactivation_time = 2.0
        self.max_angular_velocity = 1000.0
        
        # 对象池
        self.rigid_body_pool = []
        self.constraint_pool = []
        
        # 事件系统
        self.event_queue = deque(maxlen=1000)
        self.collision_event_history = deque(maxlen=100)
        
        # 配置求解器
        self._configure_solver()
        
        # 设置分离冲量
        self._configure_split_impulse()
        
        # 初始化性能分析器
        self._init_profiler()
        
        print("物理世界初始化完成")
        
    def _configure_solver(self):
        """
        配置物理求解器
        """
        # 设置求解器参数
        self.bullet_world.setSolverNumIterations(self.solver_iterations)
        self.bullet_world.setSolverSorParameter(self.solver_tolerance)
        
        # 启用各种优化
        self.bullet_world.setEnableWarmStarting(self.warm_starting)
        self.bullet_world.setEnableCcd(self.enable_continuous_collision)
        
        # 设置最大角速度
        self.bullet_world.setMaxAngularVelocity(self.max_angular_velocity)
        
    def _configure_split_impulse(self):
        """
        配置分离冲量
        """
        if self.enable_split_impulse:
            self.bullet_world.setSplitImpulseEnabled(True)
            self.bullet_world.setSplitImpulsePenetrationThreshold(
                self.split_impulse_penetration_threshold)
            
    def _init_profiler(self):
        """
        初始化性能分析器
        """
        # 初始化性能分析器数据结构
        self.collision_detection_timer = 0.0
        self.constraint_solving_timer = 0.0
        self.integration_timer = 0.0
        self.broad_phase_timer = 0.0
        self.narrow_phase_timer = 0.0
        self.solver_timer = 0.0
        
    def set_gravity(self, gravity):
        """
        设置重力
        
        Args:
            gravity (Vec3): 重力向量
        """
        self.gravity = gravity
        self.bullet_world.setGravity(gravity)
        self.soft_body_world_info.setGravity(gravity)
        
    def set_time_step(self, time_step, max_substeps=10):
        """
        设置时间步长参数
        
        Args:
            time_step (float): 时间步长
            max_substeps (int): 最大子步数
        """
        self.time_step = time_step
        self.max_substeps = max_substeps
        self.internal_time_step = time_step
        
    def set_solver_parameters(self, iterations=None, tolerance=None, warm_starting=None):
        """
        设置求解器参数
        
        Args:
            iterations (int): 迭代次数
            tolerance (float): 容差
            warm_starting (bool): 是否启用预热
        """
        if iterations is not None:
            self.solver_iterations = iterations
            self.bullet_world.setSolverNumIterations(iterations)
        if tolerance is not None:
            self.solver_tolerance = tolerance
            self.bullet_world.setSolverSorParameter(tolerance)
        if warm_starting is not None:
            self.warm_starting = warm_starting
            self.bullet_world.setEnableWarmStarting(warm_starting)
        self._configure_solver()
        
    def set_split_impulse(self, enable=True, penetration_threshold=None):
        """
        设置分离冲量参数
        
        Args:
            enable (bool): 是否启用
            penetration_threshold (float): 穿透阈值
        """
        self.enable_split_impulse = enable
        if penetration_threshold is not None:
            self.split_impulse_penetration_threshold = penetration_threshold
        self._configure_split_impulse()
        
    def set_ccd_parameters(self, threshold=None, radius=None):
        """
        设置连续碰撞检测参数
        
        Args:
            threshold (float): CCD阈值
            radius (float): CCD半径
        """
        if threshold is not None:
            self.ccd_threshold = threshold
        if radius is not None:
            self.ccd_radius = radius
            
    def set_force_field_parameters(self, wind=None, magnetic_field=None, 
                                  fluid_density=None, fluid_viscosity=None,
                                  drag_coefficient=None, lift_coefficient=None):
        """
        设置力场参数
        
        Args:
            wind (Vec3): 风向量
            magnetic_field (Vec3): 磁场向量
            fluid_density (float): 流体密度
            fluid_viscosity (float): 流体粘度
            drag_coefficient (float): 阻力系数
            lift_coefficient (float): 升力系数
        """
        if wind is not None:
            self.global_wind = wind
        if magnetic_field is not None:
            self.global_magnetic_field = magnetic_field
        if fluid_density is not None:
            self.fluid_density = fluid_density
        if fluid_viscosity is not None:
            self.fluid_viscosity = fluid_viscosity
        if drag_coefficient is not None:
            self.fluid_drag_coefficient = drag_coefficient
        if lift_coefficient is not None:
            self.fluid_lift_coefficient = lift_coefficient
            
    def enable_multithreading(self, enable=True, thread_count=4):
        """
        启用多线程支持
        
        Args:
            enable (bool): 是否启用多线程
            thread_count (int): 线程数量
        """
        self.use_multithreading = enable
        self.thread_count = max(1, thread_count)
        
        # 配置Bullet多线程支持（如果可用）
        try:
            if enable:
                # 注意：Bullet Python绑定可能不支持多线程
                pass
        except Exception as e:
            print(f"多线程配置失败: {e}")
            
    def setup_spatial_partitioning(self, partition_size=100.0):
        """
        设置空间分区
        
        Args:
            partition_size (float): 分区大小
        """
        self.partition_size = partition_size
        # 这里可以实现八叉树或网格分区系统
        self.spatial_partitioning = {}
        
    def _update_spatial_partitioning(self):
        """
        更新空间分区
        """
        if self.spatial_partitioning is not None:
            # 清空现有分区
            self.spatial_partitioning.clear()
            
            # 重新分配对象到分区
            for body in self.rigid_bodies:
                pos = body.physics_node.getPos()
                # 计算分区索引
                partition_x = int(pos.getX() // self.partition_size)
                partition_y = int(pos.getY() // self.partition_size)
                partition_z = int(pos.getZ() // self.partition_size)
                partition_key = (partition_x, partition_y, partition_z)
                
                # 添加到分区
                if partition_key not in self.spatial_partitioning:
                    self.spatial_partitioning[partition_key] = []
                self.spatial_partitioning[partition_key].append(body)
                
    def update(self, dt):
        """
        更新物理世界
        
        Args:
            dt (float): 帧时间增量
        """
        # 如果暂停，不更新物理
        if self.is_paused:
            return
            
        # 应用时间缩放
        dt *= self.time_scale
        
        try:
            # 性能监控开始
            start_time = time.time()
            
            # 更新帧计数器
            self.frame_counter += 1
            
            # 累积时间
            self.time_accumulator += dt
            
            # 计算子步数
            num_substeps = min(
                int(self.time_accumulator / self.internal_time_step),
                self.max_substeps
            )
            
            # 至少执行一次更新
            if num_substeps == 0 and self.time_accumulator > 0:
                num_substeps = 1
                
            # 执行子步长模拟
            for i in range(num_substeps):
                # 应用全局力场
                self._apply_global_force_fields()
                
                # 在多线程模式下更新物理世界
                if self.use_multithreading and self.thread_count > 1:
                    self._update_multithreaded(self.internal_time_step)
                else:
                    # 记录各个阶段的时间
                    broad_start = time.time()
                    # 这里应用Broad Phase时间记录
                    broad_end = time.time()
                    self.broad_phase_timer += broad_end - broad_start
                    
                    narrow_start = time.time()
                    # 这里应用Narrow Phase时间记录
                    narrow_end = time.time()
                    self.narrow_phase_timer += narrow_end - narrow_start
                    
                    solver_start = time.time()
                    # 这里应用Solver时间记录
                    solver_end = time.time()
                    self.solver_timer += solver_end - solver_start
                    
                    # 执行物理模拟
                    self.bullet_world.doPhysics(self.internal_time_step)
                    
            # 减少累积时间
            if num_substeps > 0:
                self.time_accumulator -= num_substeps * self.internal_time_step
                
            # 更新空间分区
            self._update_spatial_partitioning()
            
            # 更新性能统计
            end_time = time.time()
            update_time = end_time - start_time
            self.performance_stats['last_update_time'] = update_time
            self.performance_stats['update_count'] += 1
            self.performance_stats['frame_times'].append(update_time)
            
            # 计算平均更新时间
            if self.performance_stats['update_count'] > 1:
                alpha = 0.1
                self.performance_stats['avg_update_time'] = (
                    alpha * update_time + 
                    (1 - alpha) * self.performance_stats['avg_update_time']
                )
            else:
                self.performance_stats['avg_update_time'] = update_time
                
            # 更新最大和最小更新时间
            if update_time > self.performance_stats['max_update_time']:
                self.performance_stats['max_update_time'] = update_time
            if update_time < self.performance_stats['min_update_time']:
                self.performance_stats['min_update_time'] = update_time
                
            # 更新对象状态统计
            self._update_object_stats()
            
            # 更新性能分析计时器
            self.performance_stats['collision_detection_time'] = self.collision_detection_timer
            self.performance_stats['constraint_solving_time'] = self.constraint_solving_timer
            self.performance_stats['integration_time'] = self.integration_timer
            self.performance_stats['broad_phase_time'] = self.broad_phase_timer
            self.performance_stats['narrow_phase_time'] = self.narrow_phase_timer
            self.performance_stats['solver_time'] = self.solver_timer
            
        except Exception as e:
            print(f"更新物理世界时出错: {e}")
            
    def _apply_global_force_fields(self):
        """
        应用全局力场
        """
        # 应用全局风力
        for body in self.rigid_bodies:
            if not body.is_static():
                # 计算风力
                velocity = body.get_linear_velocity()
                relative_wind = self.global_wind - velocity
                wind_force = relative_wind * self.fluid_drag_coefficient * body.mass
                body.bullet_body.applyCentralForce(wind_force)
                
                # 计算流体阻力
                drag_force = -velocity * self.fluid_drag_coefficient * body.mass
                body.bullet_body.applyCentralForce(drag_force)
                
                # 计算升力（基于角速度）
                angular_velocity = body.get_angular_velocity()
                lift_force = angular_velocity.cross(velocity) * self.fluid_lift_coefficient * body.mass
                body.bullet_body.applyCentralForce(lift_force)
                
                # 应用磁场力（如果定义）
                if self.global_magnetic_field.length() > 0:
                    magnetic_force = self.global_magnetic_field * 0.1 * body.mass
                    body.bullet_body.applyCentralForce(magnetic_force)
                    
    def _update_multithreaded(self, time_step):
        """
        多线程更新物理世界
        
        Args:
            time_step (float): 时间步长
        """
        # 这里可以实现多线程物理更新
        # 由于Bullet Python绑定的限制，这里使用单线程模拟
        self.bullet_world.doPhysics(time_step)
        
    def _update_object_stats(self):
        """
        更新对象状态统计
        """
        active_count = 0
        sleeping_count = 0
        
        for body in self.rigid_bodies:
            if body.bullet_body.isActive():
                active_count += 1
            else:
                sleeping_count += 1
                
        self.performance_stats['active_rigid_bodies'] = active_count
        self.performance_stats['sleeping_rigid_bodies'] = sleeping_count
        self.performance_stats['constraint_count'] = len(self.constraints)
        
    def add_rigid_body(self, rigid_body):
        """
        添加刚体到物理世界
        
        Args:
            rigid_body (RigidBody): 刚体对象
        """
        self.rigid_bodies.append(rigid_body)
        self.bullet_world.attachRigidBody(rigid_body.bullet_body)
        
        # 设置CCD参数（如果启用）
        if self.ccd_threshold > 0 or self.ccd_radius > 0:
            rigid_body.bullet_body.setCcdMotionThreshold(self.ccd_threshold)
            rigid_body.bullet_body.setCcdSweptSphereRadius(self.ccd_radius)
            
    def remove_rigid_body(self, rigid_body):
        """
        从物理世界移除刚体
        
        Args:
            rigid_body (RigidBody): 刚体对象
        """
        if rigid_body in self.rigid_bodies:
            self.rigid_bodies.remove(rigid_body)
            self.bullet_world.removeRigidBody(rigid_body.bullet_body)
            
    def add_constraint(self, constraint):
        """
        添加约束到物理世界
        
        Args:
            constraint: 约束对象
        """
        self.constraints.append(constraint)
        self.bullet_world.attachConstraint(constraint.bullet_constraint)
        
    def remove_constraint(self, constraint):
        """
        从物理世界移除约束
        
        Args:
            constraint: 约束对象
        """
        if constraint in self.constraints:
            self.constraints.remove(constraint)
            self.bullet_world.removeConstraint(constraint.bullet_constraint)
            
    def add_vehicle(self, vehicle):
        """
        添加车辆到物理世界
        
        Args:
            vehicle: 车辆对象
        """
        self.vehicles.append(vehicle)
        self.bullet_world.attachVehicle(vehicle.bullet_vehicle)
        
    def remove_vehicle(self, vehicle):
        """
        从物理世界移除车辆
        
        Args:
            vehicle: 车辆对象
        """
        if vehicle in self.vehicles:
            self.vehicles.remove(vehicle)
            self.bullet_world.removeVehicle(vehicle.bullet_vehicle)
            
    def add_particle_system(self, particle_system):
        """
        添加粒子系统到物理世界
        
        Args:
            particle_system: 粒子系统对象
        """
        self.particles.append(particle_system)
        
    def remove_particle_system(self, particle_system):
        """
        从物理世界移除粒子系统
        
        Args:
            particle_system: 粒子系统对象
        """
        if particle_system in self.particles:
            self.particles.remove(particle_system)
            
    def add_soft_body(self, soft_body):
        """
        添加软体到物理世界
        
        Args:
            soft_body: 软体对象
        """
        self.soft_bodies.append(soft_body)
        self.bullet_world.attachSoftBody(soft_body.bullet_soft_body)
        
    def remove_soft_body(self, soft_body):
        """
        从物理世界移除软体
        
        Args:
            soft_body: 软体对象
        """
        if soft_body in self.soft_bodies:
            self.soft_bodies.remove(soft_body)
            self.bullet_world.removeSoftBody(soft_body.bullet_soft_body)
            
    def add_ghost_object(self, ghost_object):
        """
        添加幽灵对象到物理世界
        
        Args:
            ghost_object: 幽灵对象
        """
        self.ghost_objects.append(ghost_object)
        self.bullet_world.attachGhostObject(ghost_object.bullet_ghost)
        
    def remove_ghost_object(self, ghost_object):
        """
        从物理世界移除幽灵对象
        
        Args:
            ghost_object: 幽灵对象
        """
        if ghost_object in self.ghost_objects:
            self.ghost_objects.remove(ghost_object)
            self.bullet_world.removeGhostObject(ghost_object.bullet_ghost)
            
    def add_sensor(self, sensor):
        """
        添加传感器到物理世界
        
        Args:
            sensor: 传感器对象
        """
        self.sensors.append(sensor)
        
    def remove_sensor(self, sensor):
        """
        从物理世界移除传感器
        
        Args:
            sensor: 传感器对象
        """
        if sensor in self.sensors:
            self.sensors.remove(sensor)
            
    def add_trigger(self, trigger):
        """
        添加触发器到物理世界
        
        Args:
            trigger: 触发器对象
        """
        self.triggers.append(trigger)
        
    def remove_trigger(self, trigger):
        """
        从物理世界移除触发器
        
        Args:
            trigger: 触发器对象
        """
        if trigger in self.triggers:
            self.triggers.remove(trigger)
            
    def add_force_field(self, force_field):
        """
        添加力场到物理世界
        
        Args:
            force_field: 力场对象
        """
        self.force_fields.append(force_field)
        
    def remove_force_field(self, force_field):
        """
        从物理世界移除力场
        
        Args:
            force_field: 力场对象
        """
        if force_field in self.force_fields:
            self.force_fields.remove(force_field)
            
    def add_fluid(self, fluid):
        """
        添加流体到物理世界
        
        Args:
            fluid: 流体对象
        """
        self.fluids.append(fluid)
        
    def remove_fluid(self, fluid):
        """
        从物理世界移除流体
        
        Args:
            fluid: 流体对象
        """
        if fluid in self.fluids:
            self.fluids.remove(fluid)
            
    def ray_test(self, from_pos, to_pos):
        """
        射线检测
        
        Args:
            from_pos (Point3): 起点
            to_pos (Point3): 终点
            
        Returns:
            BulletRayHit: 射线检测结果
        """
        self.performance_stats['raycast_count'] += 1
        return self.bullet_world.rayTestClosest(from_pos, to_pos)
        
    def ray_test_all(self, from_pos, to_pos):
        """
        射线检测（所有结果）
        
        Args:
            from_pos (Point3): 起点
            to_pos (Point3): 终点
            
        Returns:
            list: 射线检测结果列表
        """
        self.performance_stats['raycast_count'] += 1
        return self.bullet_world.rayTestAll(from_pos, to_pos)
        
    def sweep_test(self, shape, from_transform, to_transform):
        """
        扫掠检测
        
        Args:
            shape: 碰撞形状
            from_transform (TransformState): 起始变换
            to_transform (TransformState): 结束变换
            
        Returns:
            BulletConvexResult: 扫掠检测结果
        """
        return self.bullet_world.sweepTestClosest(shape, from_transform, to_transform)
        
    def contact_test(self, body, contact_results=None):
        """
        接触检测
        
        Args:
            body: 刚体对象
            contact_results: 接触结果容器
            
        Returns:
            list: 接触结果列表
        """
        if contact_results is None:
            contact_results = []
        self.bullet_world.contactTest(body.bullet_body, contact_results)
        return contact_results
        
    def get_performance_stats(self):
        """
        获取性能统计信息
        
        Returns:
            dict: 性能统计信息
        """
        # 计算帧率统计
        if self.performance_stats['frame_times']:
            avg_frame_time = sum(self.performance_stats['frame_times']) / len(self.performance_stats['frame_times'])
            fps = 1.0 / avg_frame_time if avg_frame_time > 0 else 0
        else:
            fps = 0
            
        stats = self.performance_stats.copy()
        stats['current_fps'] = fps
        stats['objects'] = {
            'rigid_bodies': len(self.rigid_bodies),
            'constraints': len(self.constraints),
            'vehicles': len(self.vehicles),
            'particles': len(self.particles),
            'soft_bodies': len(self.soft_bodies),
            'ghost_objects': len(self.ghost_objects),
            'sensors': len(self.sensors),
            'triggers': len(self.triggers),
            'force_fields': len(self.force_fields),
            'fluids': len(self.fluids)
        }
        
        return stats
        
    def get_detailed_performance_stats(self):
        """
        获取详细的性能统计信息
        
        Returns:
            dict: 详细性能统计信息
        """
        stats = self.get_performance_stats()
        
        # 添加额外的详细统计
        stats['detailed'] = {
            'solver_iterations': self.solver_iterations,
            'time_step': self.time_step,
            'max_substeps': self.max_substeps,
            'warm_starting': self.warm_starting,
            'split_impulse': self.enable_split_impulse,
            'continuous_collision': self.enable_continuous_collision,
            'sleeping_enabled': self.enable_sleeping,
            'deactivation_enabled': self.enable_deactivation,
            'broad_phase_enabled': self.enable_broad_phase,
            'narrow_phase_enabled': self.enable_narrow_phase
        }
        
        return stats
        
    def pause(self, paused=True):
        """
        暂停或恢复物理模拟
        
        Args:
            paused (bool): 是否暂停
        """
        self.is_paused = paused
        
    def set_time_scale(self, scale):
        """
        设置时间缩放
        
        Args:
            scale (float): 时间缩放因子
        """
        self.time_scale = max(0.0, scale)
        
    def clear(self):
        """
        清除物理世界中的所有对象
        """
        # 移除所有约束
        for constraint in self.constraints[:]:
            self.remove_constraint(constraint)
            
        # 移除所有刚体
        for rigid_body in self.rigid_bodies[:]:
            self.remove_rigid_body(rigid_body)
            
        # 移除所有车辆
        for vehicle in self.vehicles[:]:
            self.remove_vehicle(vehicle)
            
        # 移除所有软体
        for soft_body in self.soft_bodies[:]:
            self.remove_soft_body(soft_body)
            
        # 移除所有幽灵对象
        for ghost_object in self.ghost_objects[:]:
            self.remove_ghost_object(ghost_object)
            
        # 移除所有传感器
        for sensor in self.sensors[:]:
            self.remove_sensor(sensor)
            
        # 移除所有触发器
        for trigger in self.triggers[:]:
            self.remove_trigger(trigger)
            
        # 移除所有力场
        for force_field in self.force_fields[:]:
            self.remove_force_field(force_field)
            
        # 移除所有流体
        for fluid in self.fluids[:]:
            self.remove_fluid(fluid)
            
        # 清空粒子系统
        self.particles.clear()
        
        # 清空事件队列
        self.event_queue.clear()
        self.collision_event_history.clear()
        
        # 重置统计信息
        self.performance_stats['update_count'] = 0
        self.performance_stats['collision_count'] = 0
        self.performance_stats['constraint_count'] = 0
        self.performance_stats['active_rigid_bodies'] = 0
        self.performance_stats['sleeping_rigid_bodies'] = 0
        self.performance_stats['raycast_count'] = 0
        
        # 重置时间相关参数
        self.time_accumulator = 0.0
        self.frame_counter = 0
        
        print("物理世界已清除")
        
    def reset(self):
        """
        重置物理世界到初始状态
        """
        self.clear()
        self.is_paused = False
        self.time_scale = 1.0
        self._init_profiler()
        
    def optimize_for_performance(self):
        """
        优化物理世界性能
        """
        # 调整求解器参数以提高性能
        self.set_solver_parameters(iterations=5, tolerance=0.01)  # 减少迭代次数和容差
        
        # 禁用某些高级功能以提高性能
        self.enable_split_impulse = False
        self._configure_split_impulse()
        
        # 优化睡眠参数
        self.sleeping_threshold = 0.1  # 增加睡眠阈值
        self.deactivation_time = 1.0   # 减少停用时间
        
        # 优化时间步长
        self.time_step = 1.0/30.0  # 降低更新频率以提高性能
        
        print("物理世界已优化性能")
        
    def optimize_for_accuracy(self):
        """
        优化物理世界精度
        """
        # 调整求解器参数以提高精度
        self.set_solver_parameters(iterations=20, tolerance=0.001)  # 增加迭代次数和减小容差
        
        # 启用高级功能以提高精度
        self.enable_split_impulse = True
        self._configure_split_impulse()
        
        # 优化睡眠参数
        self.sleeping_threshold = 0.01  # 降低睡眠阈值
        self.deactivation_time = 2.0   # 增加停用时间
        
        # 优化时间步长
        self.time_step = 1.0/120.0  # 提高更新频率以提高精度
        
        print("物理世界已优化精度")
        
    def get_memory_usage(self):
        """
        获取内存使用情况
        
        Returns:
            dict: 内存使用情况
        """
        # 这里可以实现更精确的内存使用计算
        object_counts = {
            'rigid_bodies': len(self.rigid_bodies),
            'constraints': len(self.constraints),
            'vehicles': len(self.vehicles),
            'particles': len(self.particles),
            'soft_bodies': len(self.soft_bodies),
            'ghost_objects': len(self.ghost_objects),
            'sensors': len(self.sensors),
            'triggers': len(self.triggers),
            'force_fields': len(self.force_fields),
            'fluids': len(self.fluids)
        }
        
        total_objects = sum(object_counts.values())
        
        return {
            'object_counts': object_counts,
            'total_objects': total_objects,
            'estimated_memory_mb': total_objects * 0.1  # 估算每个对象占用0.1MB
        }
        
    def add_collision_event(self, body_a, body_b, contact_points, impulse):
        """
        添加碰撞事件到历史记录
        
        Args:
            body_a (RigidBody): 刚体A
            body_b (RigidBody): 刚体B
            contact_points (list): 接触点列表
            impulse (float): 冲量
        """
        collision_event = {
            'body_a': body_a,
            'body_b': body_b,
            'contact_points': contact_points,
            'impulse': impulse,
            'timestamp': time.time()
        }
        self.collision_event_history.append(collision_event)
        
    def get_recent_collision_events(self, duration=5.0):
        """
        获取最近的碰撞事件
        
        Args:
            duration (float): 时间范围（秒）
            
        Returns:
            list: 碰撞事件列表
        """
        current_time = time.time()
        start_time = current_time - duration
        
        recent_events = []
        for event in self.collision_event_history:
            if event['timestamp'] >= start_time:
                recent_events.append(event)
                
        return recent_events
        
    def get_collision_statistics(self):
        """
        获取碰撞统计信息
        
        Returns:
            dict: 碰撞统计信息
        """
        recent_events = self.get_recent_collision_events(duration=1.0)
        
        return {
            'total_collisions': len(self.collision_event_history),
            'recent_collisions': len(recent_events),
            'collision_rate_per_second': len(recent_events),
            'average_impulse': sum([e['impulse'] for e in recent_events if 'impulse' in e]) / max(1, len(recent_events)),
            'most_collided_bodies': self._get_most_collided_bodies()
        }
        
    def _get_most_collided_bodies(self):
        """
        获取碰撞最多的刚体
        
        Returns:
            list: 碰撞计数排序的刚体列表
        """
        collision_counts = {}
        current_time = time.time()
        
        for event in self.collision_event_history:
            if current_time - event['timestamp'] <= 5.0:  # 5秒内的事件
                body_a_name = event['body_a'].bullet_body.getName() if hasattr(event['body_a'], 'bullet_body') else 'unknown'
                body_b_name = event['body_b'].bullet_body.getName() if hasattr(event['body_b'], 'bullet_body') else 'unknown'
                
                collision_counts[body_a_name] = collision_counts.get(body_a_name, 0) + 1
                collision_counts[body_b_name] = collision_counts.get(body_b_name, 0) + 1
                
        # 按碰撞次数排序
        sorted_bodies = sorted(collision_counts.items(), key=lambda x: x[1], reverse=True)
        return sorted_bodies[:10]  # 返回前10个
        
    def __del__(self):
        """
        析构函数，清理资源
        """
        self.clear()
        # 清理多线程资源
        if self.worker_threads:
            for thread in self.worker_threads:
                if thread.is_alive():
                    thread.join(timeout=1.0)
        if self.physics_thread and self.physics_thread.is_alive():
            self.physics_thread.join(timeout=1.0)