#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Qt环境深度调试
诊断Qt集成环境中的渲染问题
"""

import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QLabel
from PyQt5.QtCore import Qt
from QMeta3D.QMeta3DWidget import QMeta3DWidget
from QMeta3D.Meta3DWorld import Meta3DWorld
from direct.gui.DirectGui import *
from direct.gui.OnscreenText import OnscreenText
from panda3d.core import *
import os

class DebugGUIWorld(Meta3DWorld):
    def __init__(self):
        super().__init__()
        
        print("=== 开始Qt环境调试 ===")
        
        # 设置背景色
        self.setBackgroundColor(0.2, 0.2, 0.3)
        print("背景色设置完成")
        
        # 检查基本渲染状态
        print(f"render节点: {self.render}")
        print(f"render2d节点: {self.render2d}")
        print(f"主相机: {self.cam}")
        print(f"2D相机: {self.camera2d}")
        
        # 检查图形状态
        print(f"图形引擎: {self.graphicsEngine}")
        if hasattr(self, 'win'):
            print(f"主窗口: {self.win}")
            print(f"窗口大小: {self.win.getXSize()} x {self.win.getYSize()}")
        
        # 创建一个简单的3D几何体测试
        self.create3DTest()
        
        # 延迟创建2D GUI
        self.taskMgr.doMethodLater(1.0, self.create2DTest, "create-2d-test")
    
    def create3DTest(self):
        """创建3D测试内容"""
        print("\n--- 创建3D测试内容 ---")
        
        # 创建一个简单的立方体
        from panda3d.core import CardMaker
        cm = CardMaker("test-cube")
        cm.setFrame(-1, 1, -1, 1)
        
        self.testCube = self.render.attachNewNode(cm.generate())
        self.testCube.setPos(0, 5, 0)
        self.testCube.setColor(1, 0, 0, 1)  # 红色
        
        print(f"3D立方体创建: {self.testCube}")
        print(f"立方体位置: {self.testCube.getPos()}")
        
        # 创建3D文本
        textNode = TextNode('3d-debug-text')
        textNode.setText("3D Test")
        textNode.setAlign(TextNode.ACenter)
        
        self.text3D = self.render.attachNewNode(textNode)
        self.text3D.setPos(0, 3, 2)
        self.text3D.setScale(0.5)
        self.text3D.setColor(1, 1, 0, 1)  # 黄色
        self.text3D.setBillboardAxis()
        
        print(f"3D文本创建: {self.text3D}")
        
        # 添加基础光照
        alight = AmbientLight('debug-alight')
        alight.setColor((0.3, 0.3, 0.3, 1))
        alnp = self.render.attachNewNode(alight)
        self.render.setLight(alnp)
        
        dlight = DirectionalLight('debug-dlight')
        dlight.setColor((0.8, 0.8, 0.8, 1))
        dlnp = self.render.attachNewNode(dlight)
        dlnp.setHpr(45, -45, 0)
        self.render.setLight(dlnp)
        
        print("光照设置完成")
    
    def create2DTest(self, task=None):
        """创建2D测试内容"""
        print("\n--- 创建2D测试内容 ---")
        
        # 检查2D渲染状态
        print(f"render2d: {self.render2d}")
        print(f"aspect2d: {self.aspect2d}")
        print(f"camera2d: {self.camera2d}")
        print(f"camera2d位置: {self.camera2d.getPos()}")
        print(f"camera2d朝向: {self.camera2d.getHpr()}")
        
        # 创建屏幕文本
        try:
            self.screenText = OnscreenText(
                text="2D Screen Test",
                pos=(0, 0.8),
                scale=0.1,
                fg=(1, 1, 1, 1),
                align=TextNode.ACenter
            )
            print(f"屏幕文本创建成功: {self.screenText}")
            print(f"屏幕文本父节点: {self.screenText.getParent()}")
        except Exception as e:
            print(f"屏幕文本创建失败: {str(e)}")
        
        # 创建DirectGUI按钮
        try:
            self.testButton = DirectButton(
                text="Test Button",
                pos=(0, 0, 0),
                scale=0.15,
                frameColor=(1, 0, 0, 1),  # 红色背景
                text_fg=(1, 1, 1, 1),     # 白色文字
                command=self.onButtonClick
            )
            print(f"DirectGUI按钮创建成功: {self.testButton}")
            print(f"按钮父节点: {self.testButton.getParent()}")
            print(f"按钮位置: {self.testButton.getPos()}")
            print(f"按钮隐藏状态: {self.testButton.isHidden()}")
        except Exception as e:
            print(f"DirectGUI按钮创建失败: {str(e)}")
        
        # 创建DirectGUI标签
        try:
            self.testLabel = DirectLabel(
                text="Test Label",
                pos=(0, 0, -0.3),
                scale=0.1,
                frameColor=(0, 1, 0, 1),  # 绿色背景
                text_fg=(0, 0, 0, 1)      # 黑色文字
            )
            print(f"DirectGUI标签创建成功: {self.testLabel}")
        except Exception as e:
            print(f"DirectGUI标签创建失败: {str(e)}")
        
        # 检查aspect2d的所有子节点
        print(f"\naspect2d子节点总数: {self.aspect2d.getNumChildren()}")
        for i in range(self.aspect2d.getNumChildren()):
            child = self.aspect2d.getChild(i)
            print(f"  子节点 {i}: {child.getName()} - {child}")
        
        # 检查渲染状态
        self.checkRenderState()
        
        return task.done if task else None
    
    def checkRenderState(self):
        """检查渲染状态"""
        print("\n--- 检查渲染状态 ---")
        
        # 检查显示区域
        if hasattr(self, 'win') and self.win:
            print(f"窗口有效: {self.win.isValid()}")
            print(f"窗口活跃: {self.win.isActive()}")
            print(f"窗口大小: {self.win.getXSize()} x {self.win.getYSize()}")
            
            # 检查显示区域
            for i in range(self.win.getNumDisplayRegions()):
                dr = self.win.getDisplayRegion(i)
                print(f"显示区域 {i}: {dr}")
                print(f"  相机: {dr.getCamera()}")
                print(f"  激活状态: {dr.isActive()}")
                print(f"  维度: {dr.getDimensions()}")
        
        # 强制渲染一帧
        try:
            if hasattr(self, 'graphicsEngine'):
                self.graphicsEngine.renderFrame()
                print("强制渲染帧完成")
        except Exception as e:
            print(f"强制渲染失败: {str(e)}")
    
    def onButtonClick(self):
        """按钮点击事件"""
        print("✓ 按钮被点击了！")

class DebugWidget(QMeta3DWidget):
    def __init__(self, world, parent=None):
        super().__init__(world, parent)
        self.world = world
        print(f"Qt部件初始化完成: {self}")

def main():
    """主函数"""
    print("启动Qt环境深度调试...")
    
    app = QApplication(sys.argv)
    
    # 创建主窗口
    mainWindow = QMainWindow()
    mainWindow.setWindowTitle("Qt环境深度调试")
    mainWindow.setGeometry(100, 100, 800, 600)
    
    # 创建布局和容器
    centralWidget = QWidget()
    layout = QVBoxLayout(centralWidget)
    
    # 添加状态标签
    statusLabel = QLabel("Qt环境调试 - 查看控制台输出")
    statusLabel.setAlignment(Qt.AlignCenter)
    statusLabel.setStyleSheet("background-color: lightblue; padding: 10px;")
    layout.addWidget(statusLabel)
    
    # 创建调试世界
    world = DebugGUIWorld()
    
    # 创建Panda3D部件
    pandaWidget = DebugWidget(world)
    layout.addWidget(pandaWidget)
    
    mainWindow.setCentralWidget(centralWidget)
    
    # 显示窗口
    mainWindow.show()
    
    print("调试窗口已显示")
    print("如果看到红色立方体和黄色3D文本，说明3D渲染正常")
    print("如果看到红色按钮和绿色标签，说明2D GUI渲染正常")
    print("如果窗口是黑色的，说明存在渲染问题")
    
    # 运行应用
    return app.exec_()

if __name__ == "__main__":
    exit_code = main() 