From 159806140fd33e6ddab951c0f6f180cfbf927d38 Mon Sep 17 00:00:00 2001 From: Dalai Felinto Date: Mon, 16 Apr 2018 14:07:42 +0200 Subject: Removing Blender Game Engine from Blender 2.8 Folders removed entirely: * //extern/recastnavigation * //intern/decklink * //intern/moto * //source/blender/editors/space_logic * //source/blenderplayer * //source/gameengine This includes DNA data and any reference to the BGE code in Blender itself. We are bumping the subversion. Pending tasks: * Tile/clamp code in image editor draw code. * Viewport drawing code (so much of this will go away because of BI removal that we can wait until then to remove this. --- source/gameengine/Ketsji/BL_Action.cpp | 534 --- source/gameengine/Ketsji/BL_Action.h | 151 - source/gameengine/Ketsji/BL_ActionManager.cpp | 164 - source/gameengine/Ketsji/BL_ActionManager.h | 132 - source/gameengine/Ketsji/BL_BlenderShader.cpp | 188 - source/gameengine/Ketsji/BL_BlenderShader.h | 96 - source/gameengine/Ketsji/BL_Material.cpp | 123 - source/gameengine/Ketsji/BL_Material.h | 182 - source/gameengine/Ketsji/BL_Shader.cpp | 1478 ------- source/gameengine/Ketsji/BL_Shader.h | 241 -- source/gameengine/Ketsji/BL_Texture.cpp | 759 ---- source/gameengine/Ketsji/BL_Texture.h | 82 - source/gameengine/Ketsji/CMakeLists.txt | 265 -- source/gameengine/Ketsji/KXNetwork/CMakeLists.txt | 56 - .../Ketsji/KXNetwork/KX_NetworkEventManager.cpp | 77 - .../Ketsji/KXNetwork/KX_NetworkEventManager.h | 55 - .../Ketsji/KXNetwork/KX_NetworkMessageActuator.cpp | 139 - .../Ketsji/KXNetwork/KX_NetworkMessageActuator.h | 72 - .../Ketsji/KXNetwork/KX_NetworkMessageSensor.cpp | 224 -- .../Ketsji/KXNetwork/KX_NetworkMessageSensor.h | 90 - .../Ketsji/KXNetwork/KX_NetworkObjectActuator.cpp | 31 - .../Ketsji/KXNetwork/KX_NetworkObjectActuator.h | 32 - .../Ketsji/KXNetwork/KX_NetworkObjectSensor.cpp | 32 - .../Ketsji/KXNetwork/KX_NetworkObjectSensor.h | 32 - source/gameengine/Ketsji/KX_ArmatureSensor.cpp | 208 - source/gameengine/Ketsji/KX_ArmatureSensor.h | 90 - source/gameengine/Ketsji/KX_BlenderMaterial.cpp | 1334 ------- source/gameengine/Ketsji/KX_BlenderMaterial.h | 200 - source/gameengine/Ketsji/KX_Camera.cpp | 1166 ------ source/gameengine/Ketsji/KX_Camera.h | 334 -- source/gameengine/Ketsji/KX_CameraActuator.cpp | 428 -- source/gameengine/Ketsji/KX_CameraActuator.h | 138 - .../gameengine/Ketsji/KX_CameraIpoSGController.cpp | 126 - .../gameengine/Ketsji/KX_CameraIpoSGController.h | 97 - source/gameengine/Ketsji/KX_CharacterWrapper.cpp | 167 - source/gameengine/Ketsji/KX_CharacterWrapper.h | 40 - source/gameengine/Ketsji/KX_ClientObjectInfo.h | 84 - source/gameengine/Ketsji/KX_ConstraintActuator.cpp | 629 --- source/gameengine/Ketsji/KX_ConstraintActuator.h | 152 - source/gameengine/Ketsji/KX_ConstraintWrapper.cpp | 133 - source/gameengine/Ketsji/KX_ConstraintWrapper.h | 61 - source/gameengine/Ketsji/KX_Dome.cpp | 2051 ---------- source/gameengine/Ketsji/KX_Dome.h | 197 - source/gameengine/Ketsji/KX_EmptyObject.cpp | 37 - source/gameengine/Ketsji/KX_EmptyObject.h | 50 - source/gameengine/Ketsji/KX_FontObject.cpp | 300 -- source/gameengine/Ketsji/KX_FontObject.h | 81 - source/gameengine/Ketsji/KX_GameActuator.cpp | 267 -- source/gameengine/Ketsji/KX_GameActuator.h | 91 - source/gameengine/Ketsji/KX_GameObject.cpp | 4203 -------------------- source/gameengine/Ketsji/KX_GameObject.h | 1142 ------ source/gameengine/Ketsji/KX_IInterpolator.h | 56 - source/gameengine/Ketsji/KX_IPOTransform.h | 87 - source/gameengine/Ketsji/KX_IPO_SGController.cpp | 373 -- source/gameengine/Ketsji/KX_IPO_SGController.h | 124 - source/gameengine/Ketsji/KX_IScalarInterpolator.h | 52 - source/gameengine/Ketsji/KX_ISceneConverter.h | 103 - source/gameengine/Ketsji/KX_ISystem.h | 63 - source/gameengine/Ketsji/KX_IpoConvert.cpp | 441 -- source/gameengine/Ketsji/KX_IpoConvert.h | 69 - source/gameengine/Ketsji/KX_KetsjiEngine.cpp | 2081 ---------- source/gameengine/Ketsji/KX_KetsjiEngine.h | 553 --- source/gameengine/Ketsji/KX_Light.cpp | 479 --- source/gameengine/Ketsji/KX_Light.h | 100 - .../gameengine/Ketsji/KX_LightIpoSGController.cpp | 122 - source/gameengine/Ketsji/KX_LightIpoSGController.h | 105 - .../gameengine/Ketsji/KX_MaterialIpoController.cpp | 105 - .../gameengine/Ketsji/KX_MaterialIpoController.h | 65 - source/gameengine/Ketsji/KX_MeshProxy.cpp | 464 --- source/gameengine/Ketsji/KX_MeshProxy.h | 85 - source/gameengine/Ketsji/KX_MotionState.cpp | 106 - source/gameengine/Ketsji/KX_MotionState.h | 65 - source/gameengine/Ketsji/KX_MouseActuator.cpp | 539 --- source/gameengine/Ketsji/KX_MouseActuator.h | 132 - source/gameengine/Ketsji/KX_MouseFocusSensor.cpp | 520 --- source/gameengine/Ketsji/KX_MouseFocusSensor.h | 208 - source/gameengine/Ketsji/KX_NavMeshObject.cpp | 747 ---- source/gameengine/Ketsji/KX_NavMeshObject.h | 80 - source/gameengine/Ketsji/KX_NearSensor.cpp | 292 -- source/gameengine/Ketsji/KX_NearSensor.h | 107 - .../Ketsji/KX_ObColorIpoSGController.cpp | 110 - .../gameengine/Ketsji/KX_ObColorIpoSGController.h | 80 - source/gameengine/Ketsji/KX_ObjectActuator.cpp | 709 ---- source/gameengine/Ketsji/KX_ObjectActuator.h | 234 -- source/gameengine/Ketsji/KX_ObstacleSimulation.cpp | 832 ---- source/gameengine/Ketsji/KX_ObstacleSimulation.h | 134 - .../Ketsji/KX_OrientationInterpolator.cpp | 56 - .../gameengine/Ketsji/KX_OrientationInterpolator.h | 64 - source/gameengine/Ketsji/KX_ParentActuator.cpp | 205 - source/gameengine/Ketsji/KX_ParentActuator.h | 91 - source/gameengine/Ketsji/KX_PhysicsEngineEnums.h | 42 - source/gameengine/Ketsji/KX_PolyProxy.cpp | 266 -- source/gameengine/Ketsji/KX_PolyProxy.h | 85 - .../gameengine/Ketsji/KX_PositionInterpolator.cpp | 42 - source/gameengine/Ketsji/KX_PositionInterpolator.h | 64 - .../gameengine/Ketsji/KX_PyConstraintBinding.cpp | 750 ---- source/gameengine/Ketsji/KX_PyConstraintBinding.h | 45 - source/gameengine/Ketsji/KX_PyMath.cpp | 215 - source/gameengine/Ketsji/KX_PyMath.h | 281 -- source/gameengine/Ketsji/KX_PythonInit.cpp | 2953 -------------- source/gameengine/Ketsji/KX_PythonInit.h | 95 - source/gameengine/Ketsji/KX_PythonInitTypes.cpp | 286 -- source/gameengine/Ketsji/KX_PythonInitTypes.h | 40 - source/gameengine/Ketsji/KX_PythonMain.cpp | 71 - source/gameengine/Ketsji/KX_PythonMain.h | 41 - source/gameengine/Ketsji/KX_RadarSensor.cpp | 230 -- source/gameengine/Ketsji/KX_RadarSensor.h | 100 - source/gameengine/Ketsji/KX_RayCast.cpp | 121 - source/gameengine/Ketsji/KX_RayCast.h | 149 - source/gameengine/Ketsji/KX_RayEventManager.cpp | 53 - source/gameengine/Ketsji/KX_RayEventManager.h | 53 - source/gameengine/Ketsji/KX_RaySensor.cpp | 383 -- source/gameengine/Ketsji/KX_RaySensor.h | 109 - .../gameengine/Ketsji/KX_SCA_AddObjectActuator.cpp | 284 -- .../gameengine/Ketsji/KX_SCA_AddObjectActuator.h | 133 - .../gameengine/Ketsji/KX_SCA_DynamicActuator.cpp | 160 - source/gameengine/Ketsji/KX_SCA_DynamicActuator.h | 76 - .../gameengine/Ketsji/KX_SCA_EndObjectActuator.cpp | 125 - .../gameengine/Ketsji/KX_SCA_EndObjectActuator.h | 74 - .../Ketsji/KX_SCA_ReplaceMeshActuator.cpp | 182 - .../gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.h | 96 - .../Ketsji/KX_SG_BoneParentNodeRelationship.cpp | 155 - .../Ketsji/KX_SG_BoneParentNodeRelationship.h | 96 - .../gameengine/Ketsji/KX_SG_NodeRelationships.cpp | 298 -- source/gameengine/Ketsji/KX_SG_NodeRelationships.h | 231 -- source/gameengine/Ketsji/KX_ScalarInterpolator.cpp | 39 - source/gameengine/Ketsji/KX_ScalarInterpolator.h | 69 - .../gameengine/Ketsji/KX_ScalingInterpolator.cpp | 42 - source/gameengine/Ketsji/KX_ScalingInterpolator.h | 64 - source/gameengine/Ketsji/KX_Scene.cpp | 2644 ------------ source/gameengine/Ketsji/KX_Scene.h | 697 ---- source/gameengine/Ketsji/KX_SceneActuator.cpp | 292 -- source/gameengine/Ketsji/KX_SceneActuator.h | 109 - source/gameengine/Ketsji/KX_SoundActuator.cpp | 571 --- source/gameengine/Ketsji/KX_SoundActuator.h | 127 - source/gameengine/Ketsji/KX_StateActuator.cpp | 171 - source/gameengine/Ketsji/KX_StateActuator.h | 97 - source/gameengine/Ketsji/KX_SteeringActuator.cpp | 639 --- source/gameengine/Ketsji/KX_SteeringActuator.h | 123 - source/gameengine/Ketsji/KX_TimeCategoryLogger.cpp | 141 - source/gameengine/Ketsji/KX_TimeCategoryLogger.h | 136 - source/gameengine/Ketsji/KX_TimeLogger.cpp | 117 - source/gameengine/Ketsji/KX_TimeLogger.h | 114 - source/gameengine/Ketsji/KX_TouchEventManager.cpp | 246 -- source/gameengine/Ketsji/KX_TouchEventManager.h | 109 - source/gameengine/Ketsji/KX_TouchSensor.cpp | 362 -- source/gameengine/Ketsji/KX_TouchSensor.h | 138 - source/gameengine/Ketsji/KX_TrackToActuator.cpp | 430 -- source/gameengine/Ketsji/KX_TrackToActuator.h | 98 - source/gameengine/Ketsji/KX_VehicleWrapper.cpp | 380 -- source/gameengine/Ketsji/KX_VehicleWrapper.h | 61 - source/gameengine/Ketsji/KX_VertexProxy.cpp | 595 --- source/gameengine/Ketsji/KX_VertexProxy.h | 112 - source/gameengine/Ketsji/KX_VisibilityActuator.cpp | 127 - source/gameengine/Ketsji/KX_VisibilityActuator.h | 75 - source/gameengine/Ketsji/KX_WorldInfo.cpp | 494 --- source/gameengine/Ketsji/KX_WorldInfo.h | 105 - source/gameengine/Ketsji/KX_WorldIpoController.cpp | 125 - source/gameengine/Ketsji/KX_WorldIpoController.h | 117 - 159 files changed, 48029 deletions(-) delete mode 100644 source/gameengine/Ketsji/BL_Action.cpp delete mode 100644 source/gameengine/Ketsji/BL_Action.h delete mode 100644 source/gameengine/Ketsji/BL_ActionManager.cpp delete mode 100644 source/gameengine/Ketsji/BL_ActionManager.h delete mode 100644 source/gameengine/Ketsji/BL_BlenderShader.cpp delete mode 100644 source/gameengine/Ketsji/BL_BlenderShader.h delete mode 100644 source/gameengine/Ketsji/BL_Material.cpp delete mode 100644 source/gameengine/Ketsji/BL_Material.h delete mode 100644 source/gameengine/Ketsji/BL_Shader.cpp delete mode 100644 source/gameengine/Ketsji/BL_Shader.h delete mode 100644 source/gameengine/Ketsji/BL_Texture.cpp delete mode 100644 source/gameengine/Ketsji/BL_Texture.h delete mode 100644 source/gameengine/Ketsji/CMakeLists.txt delete mode 100644 source/gameengine/Ketsji/KXNetwork/CMakeLists.txt delete mode 100644 source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.cpp delete mode 100644 source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.h delete mode 100644 source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.cpp delete mode 100644 source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.h delete mode 100644 source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.cpp delete mode 100644 source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.h delete mode 100644 source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectActuator.cpp delete mode 100644 source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectActuator.h delete mode 100644 source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectSensor.cpp delete mode 100644 source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectSensor.h delete mode 100644 source/gameengine/Ketsji/KX_ArmatureSensor.cpp delete mode 100644 source/gameengine/Ketsji/KX_ArmatureSensor.h delete mode 100644 source/gameengine/Ketsji/KX_BlenderMaterial.cpp delete mode 100644 source/gameengine/Ketsji/KX_BlenderMaterial.h delete mode 100644 source/gameengine/Ketsji/KX_Camera.cpp delete mode 100644 source/gameengine/Ketsji/KX_Camera.h delete mode 100644 source/gameengine/Ketsji/KX_CameraActuator.cpp delete mode 100644 source/gameengine/Ketsji/KX_CameraActuator.h delete mode 100644 source/gameengine/Ketsji/KX_CameraIpoSGController.cpp delete mode 100644 source/gameengine/Ketsji/KX_CameraIpoSGController.h delete mode 100644 source/gameengine/Ketsji/KX_CharacterWrapper.cpp delete mode 100644 source/gameengine/Ketsji/KX_CharacterWrapper.h delete mode 100644 source/gameengine/Ketsji/KX_ClientObjectInfo.h delete mode 100644 source/gameengine/Ketsji/KX_ConstraintActuator.cpp delete mode 100644 source/gameengine/Ketsji/KX_ConstraintActuator.h delete mode 100644 source/gameengine/Ketsji/KX_ConstraintWrapper.cpp delete mode 100644 source/gameengine/Ketsji/KX_ConstraintWrapper.h delete mode 100644 source/gameengine/Ketsji/KX_Dome.cpp delete mode 100644 source/gameengine/Ketsji/KX_Dome.h delete mode 100644 source/gameengine/Ketsji/KX_EmptyObject.cpp delete mode 100644 source/gameengine/Ketsji/KX_EmptyObject.h delete mode 100644 source/gameengine/Ketsji/KX_FontObject.cpp delete mode 100644 source/gameengine/Ketsji/KX_FontObject.h delete mode 100644 source/gameengine/Ketsji/KX_GameActuator.cpp delete mode 100644 source/gameengine/Ketsji/KX_GameActuator.h delete mode 100644 source/gameengine/Ketsji/KX_GameObject.cpp delete mode 100644 source/gameengine/Ketsji/KX_GameObject.h delete mode 100644 source/gameengine/Ketsji/KX_IInterpolator.h delete mode 100644 source/gameengine/Ketsji/KX_IPOTransform.h delete mode 100644 source/gameengine/Ketsji/KX_IPO_SGController.cpp delete mode 100644 source/gameengine/Ketsji/KX_IPO_SGController.h delete mode 100644 source/gameengine/Ketsji/KX_IScalarInterpolator.h delete mode 100644 source/gameengine/Ketsji/KX_ISceneConverter.h delete mode 100644 source/gameengine/Ketsji/KX_ISystem.h delete mode 100644 source/gameengine/Ketsji/KX_IpoConvert.cpp delete mode 100644 source/gameengine/Ketsji/KX_IpoConvert.h delete mode 100644 source/gameengine/Ketsji/KX_KetsjiEngine.cpp delete mode 100644 source/gameengine/Ketsji/KX_KetsjiEngine.h delete mode 100644 source/gameengine/Ketsji/KX_Light.cpp delete mode 100644 source/gameengine/Ketsji/KX_Light.h delete mode 100644 source/gameengine/Ketsji/KX_LightIpoSGController.cpp delete mode 100644 source/gameengine/Ketsji/KX_LightIpoSGController.h delete mode 100644 source/gameengine/Ketsji/KX_MaterialIpoController.cpp delete mode 100644 source/gameengine/Ketsji/KX_MaterialIpoController.h delete mode 100644 source/gameengine/Ketsji/KX_MeshProxy.cpp delete mode 100644 source/gameengine/Ketsji/KX_MeshProxy.h delete mode 100644 source/gameengine/Ketsji/KX_MotionState.cpp delete mode 100644 source/gameengine/Ketsji/KX_MotionState.h delete mode 100644 source/gameengine/Ketsji/KX_MouseActuator.cpp delete mode 100644 source/gameengine/Ketsji/KX_MouseActuator.h delete mode 100644 source/gameengine/Ketsji/KX_MouseFocusSensor.cpp delete mode 100644 source/gameengine/Ketsji/KX_MouseFocusSensor.h delete mode 100644 source/gameengine/Ketsji/KX_NavMeshObject.cpp delete mode 100644 source/gameengine/Ketsji/KX_NavMeshObject.h delete mode 100644 source/gameengine/Ketsji/KX_NearSensor.cpp delete mode 100644 source/gameengine/Ketsji/KX_NearSensor.h delete mode 100644 source/gameengine/Ketsji/KX_ObColorIpoSGController.cpp delete mode 100644 source/gameengine/Ketsji/KX_ObColorIpoSGController.h delete mode 100644 source/gameengine/Ketsji/KX_ObjectActuator.cpp delete mode 100644 source/gameengine/Ketsji/KX_ObjectActuator.h delete mode 100644 source/gameengine/Ketsji/KX_ObstacleSimulation.cpp delete mode 100644 source/gameengine/Ketsji/KX_ObstacleSimulation.h delete mode 100644 source/gameengine/Ketsji/KX_OrientationInterpolator.cpp delete mode 100644 source/gameengine/Ketsji/KX_OrientationInterpolator.h delete mode 100644 source/gameengine/Ketsji/KX_ParentActuator.cpp delete mode 100644 source/gameengine/Ketsji/KX_ParentActuator.h delete mode 100644 source/gameengine/Ketsji/KX_PhysicsEngineEnums.h delete mode 100644 source/gameengine/Ketsji/KX_PolyProxy.cpp delete mode 100644 source/gameengine/Ketsji/KX_PolyProxy.h delete mode 100644 source/gameengine/Ketsji/KX_PositionInterpolator.cpp delete mode 100644 source/gameengine/Ketsji/KX_PositionInterpolator.h delete mode 100644 source/gameengine/Ketsji/KX_PyConstraintBinding.cpp delete mode 100644 source/gameengine/Ketsji/KX_PyConstraintBinding.h delete mode 100644 source/gameengine/Ketsji/KX_PyMath.cpp delete mode 100644 source/gameengine/Ketsji/KX_PyMath.h delete mode 100644 source/gameengine/Ketsji/KX_PythonInit.cpp delete mode 100644 source/gameengine/Ketsji/KX_PythonInit.h delete mode 100644 source/gameengine/Ketsji/KX_PythonInitTypes.cpp delete mode 100644 source/gameengine/Ketsji/KX_PythonInitTypes.h delete mode 100644 source/gameengine/Ketsji/KX_PythonMain.cpp delete mode 100644 source/gameengine/Ketsji/KX_PythonMain.h delete mode 100644 source/gameengine/Ketsji/KX_RadarSensor.cpp delete mode 100644 source/gameengine/Ketsji/KX_RadarSensor.h delete mode 100644 source/gameengine/Ketsji/KX_RayCast.cpp delete mode 100644 source/gameengine/Ketsji/KX_RayCast.h delete mode 100644 source/gameengine/Ketsji/KX_RayEventManager.cpp delete mode 100644 source/gameengine/Ketsji/KX_RayEventManager.h delete mode 100644 source/gameengine/Ketsji/KX_RaySensor.cpp delete mode 100644 source/gameengine/Ketsji/KX_RaySensor.h delete mode 100644 source/gameengine/Ketsji/KX_SCA_AddObjectActuator.cpp delete mode 100644 source/gameengine/Ketsji/KX_SCA_AddObjectActuator.h delete mode 100644 source/gameengine/Ketsji/KX_SCA_DynamicActuator.cpp delete mode 100644 source/gameengine/Ketsji/KX_SCA_DynamicActuator.h delete mode 100644 source/gameengine/Ketsji/KX_SCA_EndObjectActuator.cpp delete mode 100644 source/gameengine/Ketsji/KX_SCA_EndObjectActuator.h delete mode 100644 source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.cpp delete mode 100644 source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.h delete mode 100644 source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp delete mode 100644 source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.h delete mode 100644 source/gameengine/Ketsji/KX_SG_NodeRelationships.cpp delete mode 100644 source/gameengine/Ketsji/KX_SG_NodeRelationships.h delete mode 100644 source/gameengine/Ketsji/KX_ScalarInterpolator.cpp delete mode 100644 source/gameengine/Ketsji/KX_ScalarInterpolator.h delete mode 100644 source/gameengine/Ketsji/KX_ScalingInterpolator.cpp delete mode 100644 source/gameengine/Ketsji/KX_ScalingInterpolator.h delete mode 100644 source/gameengine/Ketsji/KX_Scene.cpp delete mode 100644 source/gameengine/Ketsji/KX_Scene.h delete mode 100644 source/gameengine/Ketsji/KX_SceneActuator.cpp delete mode 100644 source/gameengine/Ketsji/KX_SceneActuator.h delete mode 100644 source/gameengine/Ketsji/KX_SoundActuator.cpp delete mode 100644 source/gameengine/Ketsji/KX_SoundActuator.h delete mode 100644 source/gameengine/Ketsji/KX_StateActuator.cpp delete mode 100644 source/gameengine/Ketsji/KX_StateActuator.h delete mode 100644 source/gameengine/Ketsji/KX_SteeringActuator.cpp delete mode 100644 source/gameengine/Ketsji/KX_SteeringActuator.h delete mode 100644 source/gameengine/Ketsji/KX_TimeCategoryLogger.cpp delete mode 100644 source/gameengine/Ketsji/KX_TimeCategoryLogger.h delete mode 100644 source/gameengine/Ketsji/KX_TimeLogger.cpp delete mode 100644 source/gameengine/Ketsji/KX_TimeLogger.h delete mode 100644 source/gameengine/Ketsji/KX_TouchEventManager.cpp delete mode 100644 source/gameengine/Ketsji/KX_TouchEventManager.h delete mode 100644 source/gameengine/Ketsji/KX_TouchSensor.cpp delete mode 100644 source/gameengine/Ketsji/KX_TouchSensor.h delete mode 100644 source/gameengine/Ketsji/KX_TrackToActuator.cpp delete mode 100644 source/gameengine/Ketsji/KX_TrackToActuator.h delete mode 100644 source/gameengine/Ketsji/KX_VehicleWrapper.cpp delete mode 100644 source/gameengine/Ketsji/KX_VehicleWrapper.h delete mode 100644 source/gameengine/Ketsji/KX_VertexProxy.cpp delete mode 100644 source/gameengine/Ketsji/KX_VertexProxy.h delete mode 100644 source/gameengine/Ketsji/KX_VisibilityActuator.cpp delete mode 100644 source/gameengine/Ketsji/KX_VisibilityActuator.h delete mode 100644 source/gameengine/Ketsji/KX_WorldInfo.cpp delete mode 100644 source/gameengine/Ketsji/KX_WorldInfo.h delete mode 100644 source/gameengine/Ketsji/KX_WorldIpoController.cpp delete mode 100644 source/gameengine/Ketsji/KX_WorldIpoController.h (limited to 'source/gameengine/Ketsji') diff --git a/source/gameengine/Ketsji/BL_Action.cpp b/source/gameengine/Ketsji/BL_Action.cpp deleted file mode 100644 index 7175eb877dd..00000000000 --- a/source/gameengine/Ketsji/BL_Action.cpp +++ /dev/null @@ -1,534 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * Contributor(s): Mitchell Stokes. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file BL_Action.cpp - * \ingroup ketsji - */ - -#include -#include - -#include "BL_Action.h" -#include "BL_ArmatureObject.h" -#include "BL_DeformableGameObject.h" -#include "BL_ShapeDeformer.h" -#include "KX_IpoConvert.h" -#include "KX_GameObject.h" - -#include "SG_Controller.h" - -// These three are for getting the action from the logic manager -#include "KX_Scene.h" -#include "SCA_LogicManager.h" - -extern "C" { -#include "BKE_animsys.h" -#include "BKE_action.h" -#include "RNA_access.h" -#include "RNA_define.h" - -// Needed for material IPOs -#include "BKE_material.h" -#include "DNA_material_types.h" -#include "DNA_scene_types.h" -} - -#include "MEM_guardedalloc.h" -#include "BKE_library.h" -#include "BKE_global.h" - -#include "BLI_threads.h" // for lock - -/* Lock to solve animation thread issues. - * A spin lock is better than a mutex in case of short wait - * because spin lock stop the thread by a loop contrary to mutex - * which switch all memory, process. - */ -static SpinLock BL_ActionLock; - -BL_Action::BL_Action(class KX_GameObject* gameobj) -: - m_action(NULL), - m_tmpaction(NULL), - m_blendpose(NULL), - m_blendinpose(NULL), - m_obj(gameobj), - m_startframe(0.f), - m_endframe(0.f), - m_localframe(0.f), - m_blendin(0.f), - m_blendframe(0.f), - m_blendstart(0.f), - m_speed(0.f), - m_priority(0), - m_playmode(ACT_MODE_PLAY), - m_blendmode(ACT_BLEND_BLEND), - m_ipo_flags(0), - m_done(true), - m_calc_localtime(true), - m_initializedTime(false) -{ -} - -BL_Action::~BL_Action() -{ - if (m_blendpose) - BKE_pose_free(m_blendpose); - if (m_blendinpose) - BKE_pose_free(m_blendinpose); - ClearControllerList(); - - if (m_tmpaction) { - BKE_libblock_free(G.main, m_tmpaction); - m_tmpaction = NULL; - } -} - -void BL_Action::ClearControllerList() -{ - // Clear out the controller list - std::vector::iterator it; - for (it = m_sg_contr_list.begin(); it != m_sg_contr_list.end(); it++) - { - m_obj->GetSGNode()->RemoveSGController((*it)); - delete *it; - } - - m_sg_contr_list.clear(); -} - -bool BL_Action::Play(const char* name, - float start, - float end, - short priority, - float blendin, - short play_mode, - float layer_weight, - short ipo_flags, - float playback_speed, - short blend_mode) -{ - - // Only start playing a new action if we're done, or if - // the new action has a higher priority - if (!IsDone() && priority > m_priority) - return false; - m_priority = priority; - bAction* prev_action = m_action; - - KX_Scene* kxscene = m_obj->GetScene(); - - // First try to load the action - m_action = (bAction*)kxscene->GetLogicManager()->GetActionByName(name); - if (!m_action) - { - printf("Failed to load action: %s\n", name); - m_done = true; - return false; - } - - // If we have the same settings, don't play again - // This is to resolve potential issues with pulses on sensors such as the ones - // reported in bug #29412. The fix is here so it works for both logic bricks and Python. - // However, this may eventually lead to issues where a user wants to override an already - // playing action with the same action and settings. If this becomes an issue, - // then this fix may have to be re-evaluated. - if (!IsDone() && m_action == prev_action && m_startframe == start && m_endframe == end - && m_priority == priority && m_speed == playback_speed) - return false; - - // Keep a copy of the action for threading purposes - if (m_tmpaction) { - BKE_libblock_free(G.main, m_tmpaction); - m_tmpaction = NULL; - } - m_tmpaction = BKE_action_copy(G.main, m_action); - - // First get rid of any old controllers - ClearControllerList(); - - // Create an SG_Controller - SG_Controller *sg_contr = BL_CreateIPO(m_action, m_obj, kxscene->GetSceneConverter()); - m_sg_contr_list.push_back(sg_contr); - m_obj->GetSGNode()->AddSGController(sg_contr); - sg_contr->SetObject(m_obj->GetSGNode()); - - // World - sg_contr = BL_CreateWorldIPO(m_action, kxscene->GetBlenderScene()->world, kxscene->GetSceneConverter()); - if (sg_contr) { - m_sg_contr_list.push_back(sg_contr); - m_obj->GetSGNode()->AddSGController(sg_contr); - sg_contr->SetObject(m_obj->GetSGNode()); - } - - // Try obcolor - sg_contr = BL_CreateObColorIPO(m_action, m_obj, kxscene->GetSceneConverter()); - if (sg_contr) { - m_sg_contr_list.push_back(sg_contr); - m_obj->GetSGNode()->AddSGController(sg_contr); - sg_contr->SetObject(m_obj->GetSGNode()); - } - - // Now try materials - if (m_obj->GetBlenderObject()->totcol==1) { - Material *mat = give_current_material(m_obj->GetBlenderObject(), 1); - if (mat) { - sg_contr = BL_CreateMaterialIpo(m_action, mat, 0, m_obj, kxscene->GetSceneConverter()); - if (sg_contr) { - m_sg_contr_list.push_back(sg_contr); - m_obj->GetSGNode()->AddSGController(sg_contr); - sg_contr->SetObject(m_obj->GetSGNode()); - } - } - } else { - Material *mat; - STR_HashedString matname; - - for (int matidx = 1; matidx <= m_obj->GetBlenderObject()->totcol; ++matidx) { - mat = give_current_material(m_obj->GetBlenderObject(), matidx); - if (mat) { - matname = mat->id.name; - sg_contr = BL_CreateMaterialIpo(m_action, mat, matname.hash(), m_obj, kxscene->GetSceneConverter()); - if (sg_contr) { - m_sg_contr_list.push_back(sg_contr); - m_obj->GetSGNode()->AddSGController(sg_contr); - sg_contr->SetObject(m_obj->GetSGNode()); - } - } - } - } - - // Extra controllers - if (m_obj->GetGameObjectType() == SCA_IObject::OBJ_LIGHT) - { - sg_contr = BL_CreateLampIPO(m_action, m_obj, kxscene->GetSceneConverter()); - m_sg_contr_list.push_back(sg_contr); - m_obj->GetSGNode()->AddSGController(sg_contr); - sg_contr->SetObject(m_obj->GetSGNode()); - } - else if (m_obj->GetGameObjectType() == SCA_IObject::OBJ_CAMERA) - { - sg_contr = BL_CreateCameraIPO(m_action, m_obj, kxscene->GetSceneConverter()); - m_sg_contr_list.push_back(sg_contr); - m_obj->GetSGNode()->AddSGController(sg_contr); - sg_contr->SetObject(m_obj->GetSGNode()); - } - - m_ipo_flags = ipo_flags; - InitIPO(); - - // Setup blendin shapes/poses - if (m_obj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE) - { - BL_ArmatureObject *obj = (BL_ArmatureObject*)m_obj; - obj->GetPose(&m_blendinpose); - } - else - { - BL_DeformableGameObject *obj = (BL_DeformableGameObject*)m_obj; - BL_ShapeDeformer *shape_deformer = dynamic_cast(obj->GetDeformer()); - - if (shape_deformer && shape_deformer->GetKey()) - { - obj->GetShape(m_blendinshape); - - // Now that we have the previous blend shape saved, we can clear out the key to avoid any - // further interference. - KeyBlock *kb; - for (kb=(KeyBlock *)shape_deformer->GetKey()->block.first; kb; kb=(KeyBlock *)kb->next) - kb->curval = 0.f; - } - } - - // Now that we have an action, we have something we can play - m_starttime = -1.f; // We get the start time on our first update - m_startframe = m_localframe = start; - m_endframe = end; - m_blendin = blendin; - m_playmode = play_mode; - m_blendmode = blend_mode; - m_blendframe = 0.f; - m_blendstart = 0.f; - m_speed = playback_speed; - m_layer_weight = layer_weight; - - m_done = false; - m_initializedTime = false; - - return true; -} - -bool BL_Action::IsDone() -{ - return m_done; -} - -void BL_Action::InitIPO() -{ - // Initialize the IPOs - std::vector::iterator it; - for (it = m_sg_contr_list.begin(); it != m_sg_contr_list.end(); it++) - { - (*it)->SetOption(SG_Controller::SG_CONTR_IPO_RESET, true); - (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_AS_FORCE, m_ipo_flags & ACT_IPOFLAG_FORCE); - (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_ADD, m_ipo_flags & ACT_IPOFLAG_ADD); - (*it)->SetOption(SG_Controller::SG_CONTR_IPO_LOCAL, m_ipo_flags & ACT_IPOFLAG_LOCAL); - } -} - -bAction *BL_Action::GetAction() -{ - return (IsDone()) ? NULL : m_action; -} - -float BL_Action::GetFrame() -{ - return m_localframe; -} - -const char *BL_Action::GetName() -{ - if (m_action != NULL) { - return m_action->id.name + 2; - } - else { - return ""; - } - - -} - -void BL_Action::SetFrame(float frame) -{ - // Clamp the frame to the start and end frame - if (frame < min(m_startframe, m_endframe)) - frame = min(m_startframe, m_endframe); - else if (frame > max(m_startframe, m_endframe)) - frame = max(m_startframe, m_endframe); - - m_localframe = frame; - m_calc_localtime = false; -} - -void BL_Action::SetPlayMode(short play_mode) -{ - m_playmode = play_mode; -} - -void BL_Action::SetTimes(float start, float end) -{ - m_startframe = start; - m_endframe = end; -} - -void BL_Action::SetLocalTime(float curtime) -{ - float dt = (curtime-m_starttime)*(float)KX_KetsjiEngine::GetAnimFrameRate()*m_speed; - - if (m_endframe < m_startframe) - dt = -dt; - - m_localframe = m_startframe + dt; -} - -void BL_Action::ResetStartTime(float curtime) -{ - float dt = (m_localframe > m_startframe) ? m_localframe - m_startframe : m_startframe - m_localframe; - - m_starttime = curtime - dt / ((float)KX_KetsjiEngine::GetAnimFrameRate()*m_speed); - SetLocalTime(curtime); -} - -void BL_Action::IncrementBlending(float curtime) -{ - // Setup m_blendstart if we need to - if (m_blendstart == 0.f) - m_blendstart = curtime; - - // Bump the blend frame - m_blendframe = (curtime - m_blendstart)*(float)KX_KetsjiEngine::GetAnimFrameRate(); - - // Clamp - if (m_blendframe>m_blendin) - m_blendframe = m_blendin; -} - - -void BL_Action::BlendShape(Key* key, float srcweight, std::vector& blendshape) -{ - vector::const_iterator it; - float dstweight; - KeyBlock *kb; - - dstweight = 1.0F - srcweight; - //printf("Dst: %f\tSrc: %f\n", srcweight, dstweight); - for (it=blendshape.begin(), kb = (KeyBlock *)key->block.first; - kb && it != blendshape.end(); - kb = (KeyBlock *)kb->next, it++) - { - //printf("OirgKeys: %f\t%f\n", kb->curval, (*it)); - kb->curval = kb->curval * dstweight + (*it) * srcweight; - //printf("NewKey: %f\n", kb->curval); - } - //printf("\n"); -} - -void BL_Action::Update(float curtime) -{ - // Don't bother if we're done with the animation - if (m_done) - return; - - curtime -= (float)KX_KetsjiEngine::GetSuspendedDelta(); - - // Grab the start time here so we don't end up with a negative m_localframe when - // suspending and resuming scenes. - if (!m_initializedTime) { - m_starttime = curtime; - m_initializedTime = true; - } - - if (m_calc_localtime) - SetLocalTime(curtime); - else - { - ResetStartTime(curtime); - m_calc_localtime = true; - } - - // Handle wrap around - if (m_localframe < min(m_startframe, m_endframe) || m_localframe > max(m_startframe, m_endframe)) { - switch (m_playmode) { - case ACT_MODE_PLAY: - // Clamp - m_localframe = m_endframe; - m_done = true; - break; - case ACT_MODE_LOOP: - // Put the time back to the beginning - m_localframe = m_startframe; - m_starttime = curtime; - break; - case ACT_MODE_PING_PONG: - // Swap the start and end frames - float temp = m_startframe; - m_startframe = m_endframe; - m_endframe = temp; - - m_starttime = curtime; - - break; - } - } - - if (m_obj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE) - { - BL_ArmatureObject *obj = (BL_ArmatureObject*)m_obj; - - if (m_layer_weight >= 0) - obj->GetPose(&m_blendpose); - - // Extract the pose from the action - obj->SetPoseByAction(m_tmpaction, m_localframe); - - // Handle blending between armature actions - if (m_blendin && m_blendframeBlendInPose(m_blendinpose, weight, ACT_BLEND_BLEND); - } - - - // Handle layer blending - if (m_layer_weight >= 0) - obj->BlendInPose(m_blendpose, m_layer_weight, m_blendmode); - - obj->UpdateTimestep(curtime); - } - else - { - BL_DeformableGameObject *obj = (BL_DeformableGameObject*)m_obj; - BL_ShapeDeformer *shape_deformer = dynamic_cast(obj->GetDeformer()); - - // Handle shape actions if we have any - if (shape_deformer && shape_deformer->GetKey()) - { - Key *key = shape_deformer->GetKey(); - - PointerRNA ptrrna; - RNA_id_pointer_create(&key->id, &ptrrna); - - animsys_evaluate_action(&ptrrna, m_tmpaction, NULL, m_localframe); - - // Handle blending between shape actions - if (m_blendin && m_blendframe < m_blendin) - { - IncrementBlending(curtime); - - float weight = 1.f - (m_blendframe/m_blendin); - - // We go through and clear out the keyblocks so there isn't any interference - // from other shape actions - KeyBlock *kb; - for (kb=(KeyBlock *)key->block.first; kb; kb=(KeyBlock *)kb->next) - kb->curval = 0.f; - - // Now blend the shape - BlendShape(key, weight, m_blendinshape); - } - - // Handle layer blending - if (m_layer_weight >= 0) - { - obj->GetShape(m_blendshape); - BlendShape(key, m_layer_weight, m_blendshape); - } - - obj->SetActiveAction(NULL, 0, curtime); - } - } - - BLI_spin_lock(&BL_ActionLock); - /* This function is not thread safe because of recursive scene graph transform - * updates on children. e.g: If an object and one of its children is animated, - * the both can write transform at the same time. A thread lock avoid problems. */ - m_obj->UpdateIPO(m_localframe, m_ipo_flags & ACT_IPOFLAG_CHILD); - BLI_spin_unlock(&BL_ActionLock); - - if (m_done) - ClearControllerList(); -} - -void BL_Action::InitLock() -{ - BLI_spin_init(&BL_ActionLock); -} - -void BL_Action::EndLock() -{ - BLI_spin_end(&BL_ActionLock); -} diff --git a/source/gameengine/Ketsji/BL_Action.h b/source/gameengine/Ketsji/BL_Action.h deleted file mode 100644 index f4c2975a547..00000000000 --- a/source/gameengine/Ketsji/BL_Action.h +++ /dev/null @@ -1,151 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * Contributor(s): Mitchell Stokes. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file BL_Action.h - * \ingroup ketsji - */ - -#ifndef __BL_ACTION_H__ -#define __BL_ACTION_H__ - - -#include - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -class BL_Action -{ -private: - struct bAction* m_action; - struct bAction* m_tmpaction; - struct bPose* m_blendpose; - struct bPose* m_blendinpose; - std::vector m_sg_contr_list; - class KX_GameObject* m_obj; - std::vector m_blendshape; - std::vector m_blendinshape; - - float m_startframe; - float m_endframe; - /// The current action frame. - float m_localframe; - float m_starttime; - - float m_blendin; - float m_blendframe; - float m_blendstart; - - float m_layer_weight; - - float m_speed; - - short m_priority; - - short m_playmode; - short m_blendmode; - - short m_ipo_flags; - - bool m_done; - bool m_calc_localtime; - /// Set to true when m_starttime is initialized in Update. - bool m_initializedTime; - - void ClearControllerList(); - void InitIPO(); - void SetLocalTime(float curtime); - void ResetStartTime(float curtime); - void IncrementBlending(float curtime); - void BlendShape(struct Key* key, float srcweight, std::vector& blendshape); -public: - BL_Action(class KX_GameObject* gameobj); - ~BL_Action(); - - /** - * Play an action - */ - bool Play(const char* name, - float start, - float end, - short priority, - float blendin, - short play_mode, - float layer_weight, - short ipo_flags, - float playback_speed, - short blend_mode); - /** - * Whether or not the action is still playing - */ - bool IsDone(); - /** - * Update the action's frame, etc. - */ - void Update(float curtime); - - // Accessors - float GetFrame(); - const char *GetName(); - - struct bAction *GetAction(); - - // Mutators - void SetFrame(float frame); - void SetPlayMode(short play_mode); - void SetTimes(float start, float end); - - enum - { - ACT_MODE_PLAY = 0, - ACT_MODE_LOOP, - ACT_MODE_PING_PONG, - ACT_MODE_MAX, - }; - - enum - { - ACT_BLEND_BLEND=0, - ACT_BLEND_ADD=1, - ACT_BLEND_MAX, - }; - - enum - { - ACT_IPOFLAG_FORCE = 1, - ACT_IPOFLAG_LOCAL = 2, - ACT_IPOFLAG_ADD = 4, - ACT_IPOFLAG_CHILD = 8, - }; - - /// Initialize a lock for animation thread issues. - static void InitLock(); - /// Finalize a lock for animation thread issues. - static void EndLock(); - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_Action") -#endif -}; - -#endif /* BL_ACTION */ diff --git a/source/gameengine/Ketsji/BL_ActionManager.cpp b/source/gameengine/Ketsji/BL_ActionManager.cpp deleted file mode 100644 index 35f605f1a5f..00000000000 --- a/source/gameengine/Ketsji/BL_ActionManager.cpp +++ /dev/null @@ -1,164 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * Contributor(s): Mitchell Stokes. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file BL_ActionManager.cpp - * \ingroup ketsji - */ - -#include "BL_Action.h" -#include "BL_ActionManager.h" -#include "DNA_ID.h" - -#define IS_TAGGED(_id) ((_id) && (((ID *)_id)->tag & LIB_TAG_DOIT)) - -BL_ActionManager::BL_ActionManager(class KX_GameObject *obj): - m_obj(obj), - m_prevUpdate(-1.0f) -{ -} - -BL_ActionManager::~BL_ActionManager() -{ - BL_ActionMap::iterator it; - - for (it = m_layers.begin(); it != m_layers.end(); it++) - delete it->second; - - m_layers.clear(); -} - -BL_Action *BL_ActionManager::GetAction(short layer) -{ - BL_ActionMap::iterator it = m_layers.find(layer); - - return (it != m_layers.end()) ? it->second : 0; -} - -float BL_ActionManager::GetActionFrame(short layer) -{ - BL_Action *action = GetAction(layer); - - return action ? action->GetFrame() : 0.f; -} - -const char *BL_ActionManager::GetActionName(short layer) -{ - BL_Action *action = GetAction(layer); - return action ? action->GetName() : ""; -} - -void BL_ActionManager::SetActionFrame(short layer, float frame) -{ - BL_Action *action = GetAction(layer); - - if (action) action->SetFrame(frame); -} - -struct bAction *BL_ActionManager::GetCurrentAction(short layer) -{ - BL_Action *action = GetAction(layer); - - return action ? action->GetAction() : 0; -} - -void BL_ActionManager::SetPlayMode(short layer, short mode) -{ - BL_Action *action = GetAction(layer); - - if (action) action->SetPlayMode(mode); -} - -void BL_ActionManager::SetTimes(short layer, float start, float end) -{ - BL_Action *action = GetAction(layer); - - if (action) action->SetTimes(start, end); -} - -bool BL_ActionManager::PlayAction(const char* name, - float start, - float end, - short layer, - short priority, - float blendin, - short play_mode, - float layer_weight, - short ipo_flags, - float playback_speed, - short blend_mode) -{ - // Only this method will create layer if non-existent - BL_Action *action = GetAction(layer); - if (!action) { - action = new BL_Action(m_obj); - m_layers[layer] = action; - } - - // Disable layer blending on the first layer - if (layer == 0) layer_weight = -1.f; - - return action->Play(name, start, end, priority, blendin, play_mode, layer_weight, ipo_flags, playback_speed, blend_mode); -} - -void BL_ActionManager::StopAction(short layer) -{ - BL_Action *action = GetAction(layer); - - if (action) { - m_layers.erase(layer); - delete action; - } -} - -void BL_ActionManager::RemoveTaggedActions() -{ - for (BL_ActionMap::iterator it = m_layers.begin(); it != m_layers.end();) { - if (IS_TAGGED(it->second->GetAction())) { - delete it->second; - m_layers.erase(it++); - } - else - ++it; - } -} - -bool BL_ActionManager::IsActionDone(short layer) -{ - BL_Action *action = GetAction(layer); - - return action ? action->IsDone() : true; -} - -void BL_ActionManager::Update(float curtime) -{ - if (m_prevUpdate == curtime) - return; - m_prevUpdate = curtime; - - BL_ActionMap::iterator it; - for (it = m_layers.begin(); it != m_layers.end(); ++it) - { - if (!it->second->IsDone()) { - it->second->Update(curtime); - } - } -} diff --git a/source/gameengine/Ketsji/BL_ActionManager.h b/source/gameengine/Ketsji/BL_ActionManager.h deleted file mode 100644 index 69c6d611df0..00000000000 --- a/source/gameengine/Ketsji/BL_ActionManager.h +++ /dev/null @@ -1,132 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * Contributor(s): Mitchell Stokes. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file BL_ActionManager.h - * \ingroup ketsji - */ - -#ifndef __BL_ACTIONMANAGER_H__ -#define __BL_ACTIONMANAGER_H__ - -#ifdef WITH_CXX_GUARDEDALLOC - #include "MEM_guardedalloc.h" -#endif - -#include - -// Currently, we use the max value of a short. -// We should switch to unsigned short; doesn't make sense to support negative layers. -// This will also give us 64k layers instead of 32k. -#define MAX_ACTION_LAYERS 32767 - -class BL_Action; - -/** - * BL_ActionManager is responsible for handling a KX_GameObject's actions. - */ -class BL_ActionManager -{ -private: - typedef std::map BL_ActionMap; - - class KX_GameObject* m_obj; - BL_ActionMap m_layers; - - // The last update time to avoid double animation update. - float m_prevUpdate; - - /** - * Check if an action exists - */ - BL_Action* GetAction(short layer); - -public: - BL_ActionManager(class KX_GameObject* obj); - ~BL_ActionManager(); - - bool PlayAction(const char* name, - float start, - float end, - short layer=0, - short priority=0, - float blendin=0.f, - short play_mode=0, - float layer_weight=0.f, - short ipo_flags=0, - float playback_speed=1.f, - short blend_mode=0); - /** - * Gets the current frame of an action - */ - float GetActionFrame(short layer); - - /** - * Gets the name of the current action - */ - const char *GetActionName(short layer); - - /** - * Sets the current frame of an action - */ - void SetActionFrame(short layer, float frame); - - /** - * Gets the currently running action on the given layer - */ - struct bAction *GetCurrentAction(short layer); - - /** - * Sets play mode of the action on the given layer - */ - void SetPlayMode(short layer, short mode); - - /** - * Sets the start and end times of the action on the given layer - */ - void SetTimes(short layer, float start, float end); - - /** - * Stop playing the action on the given layer - */ - void StopAction(short layer); - - /** - * Remove playing tagged actions. - */ - void RemoveTaggedActions(); - - /** - * Check if an action has finished playing - */ - bool IsActionDone(short layer); - - /** - * Update any running actions - */ - void Update(float); - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_ActionManager") -#endif -}; - -#endif /* BL_ACTIONMANAGER */ diff --git a/source/gameengine/Ketsji/BL_BlenderShader.cpp b/source/gameengine/Ketsji/BL_BlenderShader.cpp deleted file mode 100644 index 572218e691d..00000000000 --- a/source/gameengine/Ketsji/BL_BlenderShader.cpp +++ /dev/null @@ -1,188 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/BL_BlenderShader.cpp - * \ingroup ketsji - */ - -#include "DNA_customdata_types.h" -#include "DNA_material_types.h" -#include "DNA_scene_types.h" - -#include "BLI_utildefines.h" - -#include "BKE_global.h" -#include "BKE_main.h" -#include "BKE_DerivedMesh.h" - -#include "BL_BlenderShader.h" -#include "BL_Material.h" - -#include "GPU_material.h" -#include "GPU_shader.h" - -#include "RAS_BucketManager.h" -#include "RAS_MeshObject.h" -#include "RAS_IRasterizer.h" - -BL_BlenderShader::BL_BlenderShader(KX_Scene *scene, struct Material *ma, int lightlayer) -: - mMat(ma), - mLightLayer(lightlayer), - mGPUMat(NULL) -{ - mBlenderScene = scene->GetBlenderScene(); - mAlphaBlend = GPU_BLEND_SOLID; - - ReloadMaterial(); -} - -BL_BlenderShader::~BL_BlenderShader() -{ - if (mGPUMat) - GPU_material_unbind(mGPUMat); -} - -void BL_BlenderShader::ReloadMaterial() -{ - mGPUMat = (mMat) ? GPU_material_from_blender(mBlenderScene, mMat, false) : NULL; -} - -void BL_BlenderShader::SetProg(bool enable, double time, RAS_IRasterizer* rasty) -{ - if (VerifyShader()) { - if (enable) { - assert(rasty != NULL); // XXX Kinda hacky, but SetProg() should always have the rasterizer if enable is true - - float viewmat[4][4], viewinvmat[4][4]; - const MT_Matrix4x4& view = rasty->GetViewMatrix(); - const MT_Matrix4x4& viewinv = rasty->GetViewInvMatrix(); - view.getValue(&viewmat[0][0]); - viewinv.getValue(&viewinvmat[0][0]); - - GPU_material_bind(mGPUMat, mLightLayer, mBlenderScene->lay, time, 1, viewmat, viewinvmat, NULL); - } - else - GPU_material_unbind(mGPUMat); - } -} - -int BL_BlenderShader::GetAttribNum() -{ - GPUVertexAttribs attribs; - int i, enabled = 0; - - if (!VerifyShader()) - return enabled; - - GPU_material_vertex_attributes(mGPUMat, &attribs); - - for (i = 0; i < attribs.totlayer; i++) - if (attribs.layer[i].glindex+1 > enabled) - enabled= attribs.layer[i].glindex+1; - - if (enabled > BL_MAX_ATTRIB) - enabled = BL_MAX_ATTRIB; - - return enabled; -} - -void BL_BlenderShader::SetAttribs(RAS_IRasterizer* ras, const BL_Material *mat) -{ - GPUVertexAttribs attribs; - GPUMaterial *gpumat; - int i, attrib_num, uv = 0; - - ras->SetAttribNum(0); - - if (!VerifyShader()) - return; - - gpumat = mGPUMat; - if (ras->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED || (ras->GetDrawingMode() == RAS_IRasterizer::KX_SHADOW && - mat->alphablend != GEMAT_SOLID && !ras->GetUsingOverrideShader())) { - GPU_material_vertex_attributes(gpumat, &attribs); - attrib_num = GetAttribNum(); - - ras->SetTexCoordNum(0); - ras->SetAttribNum(attrib_num); - for (i = 0; i < attrib_num; i++) - ras->SetAttrib(RAS_IRasterizer::RAS_TEXCO_DISABLE, i); - - for (i = 0; i < attribs.totlayer; i++) { - if (attribs.layer[i].glindex > attrib_num) - continue; - - if (attribs.layer[i].type == CD_MTFACE) - ras->SetAttrib(RAS_IRasterizer::RAS_TEXCO_UV, attribs.layer[i].glindex, uv++); - else if (attribs.layer[i].type == CD_TANGENT) - ras->SetAttrib(RAS_IRasterizer::RAS_TEXTANGENT, attribs.layer[i].glindex); - else if (attribs.layer[i].type == CD_ORCO) - ras->SetAttrib(RAS_IRasterizer::RAS_TEXCO_ORCO, attribs.layer[i].glindex); - else if (attribs.layer[i].type == CD_NORMAL) - ras->SetAttrib(RAS_IRasterizer::RAS_TEXCO_NORM, attribs.layer[i].glindex); - else if (attribs.layer[i].type == CD_MCOL) - ras->SetAttrib(RAS_IRasterizer::RAS_TEXCO_VCOL, attribs.layer[i].glindex); - else - ras->SetAttrib(RAS_IRasterizer::RAS_TEXCO_DISABLE, attribs.layer[i].glindex); - } - } -} - -void BL_BlenderShader::Update(const RAS_MeshSlot & ms, RAS_IRasterizer* rasty ) -{ - float obmat[4][4], viewmat[4][4], obcol[4]; - GPUMaterial *gpumat; - - gpumat = mGPUMat; - - if (!gpumat || !GPU_material_bound(gpumat)) - return; - - MT_Matrix4x4 model; - model.setValue(ms.m_OpenGLMatrix); - - // note: getValue gives back column major as needed by OpenGL - model.getValue(&obmat[0][0]); - - if (ms.m_bObjectColor) - ms.m_RGBAcolor.getValue(&obcol[0]); - else - obcol[0] = obcol[1] = obcol[2] = obcol[3] = 1.0f; - - rasty->GetViewMatrix().getValue(&viewmat[0][0]); - float auto_bump_scale = ms.m_pDerivedMesh!=0 ? ms.m_pDerivedMesh->auto_bump_scale : 1.0f; - GPU_material_bind_uniforms(gpumat, obmat, viewmat, obcol, auto_bump_scale, NULL, NULL); - - mAlphaBlend = GPU_material_alpha_blend(gpumat, obcol); -} - -int BL_BlenderShader::GetAlphaBlend() -{ - return mAlphaBlend; -} - -bool BL_BlenderShader::Equals(BL_BlenderShader *blshader) -{ - /* to avoid unneeded state switches */ - return (blshader && mMat == blshader->mMat && mLightLayer == blshader->mLightLayer); -} - -// eof diff --git a/source/gameengine/Ketsji/BL_BlenderShader.h b/source/gameengine/Ketsji/BL_BlenderShader.h deleted file mode 100644 index e03bb5a11d9..00000000000 --- a/source/gameengine/Ketsji/BL_BlenderShader.h +++ /dev/null @@ -1,96 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) Blender Foundation - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file BL_BlenderShader.h - * \ingroup ketsji - */ - -#ifndef __BL_BLENDERSHADER_H__ -#define __BL_BLENDERSHADER_H__ - -#include "GPU_material.h" - -#include "MT_Matrix4x4.h" -#include "MT_Matrix3x3.h" -#include "MT_Tuple2.h" -#include "MT_Tuple3.h" -#include "MT_Tuple4.h" - -#include "RAS_IPolygonMaterial.h" - -#include "KX_Scene.h" - -struct Material; -struct Scene; -class BL_Material; - -#define BL_MAX_ATTRIB 16 - -/** - * BL_BlenderShader - * Blender GPU shader material - */ -class BL_BlenderShader -{ -private: - struct Scene *mBlenderScene; - struct Material *mMat; - int mLightLayer; - int mAlphaBlend; - GPUMaterial *mGPUMat; - - bool VerifyShader() - { - return (NULL != mGPUMat); - } - -public: - BL_BlenderShader(KX_Scene *scene, struct Material *ma, int lightlayer); - virtual ~BL_BlenderShader(); - - bool Ok() - { - // same as VerifyShared - return (NULL != mGPUMat); - } - void SetProg(bool enable, double time=0.0, RAS_IRasterizer* rasty=NULL); - - int GetAttribNum(); - void SetAttribs(class RAS_IRasterizer* ras, const BL_Material *mat); - void Update(const class RAS_MeshSlot & ms, class RAS_IRasterizer* rasty); - void ReloadMaterial(); - int GetAlphaBlend(); - - bool Equals(BL_BlenderShader *blshader); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_BlenderShader") -#endif -}; - -#endif /* __BL_BLENDERSHADER_H__ */ diff --git a/source/gameengine/Ketsji/BL_Material.cpp b/source/gameengine/Ketsji/BL_Material.cpp deleted file mode 100644 index 40384b43054..00000000000 --- a/source/gameengine/Ketsji/BL_Material.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/BL_Material.cpp - * \ingroup ketsji - */ - -#include "BL_Material.h" -#include "DNA_material_types.h" -#include "DNA_texture_types.h" -#include "DNA_image_types.h" -#include "DNA_mesh_types.h" -#include "IMB_imbuf_types.h" -#include "IMB_imbuf.h" - -MTex* getMTexFromMaterial(Material *mat, int index) -{ - if (mat && (index >= 0) && (index < MAX_MTEX)) { - return mat->mtex[index]; - } - else { - return NULL; - } -} - -BL_Material::BL_Material() -{ - Initialize(); -} - -void BL_Material::Initialize() -{ - rgb[0] = 0xFFFFFFFFL; - rgb[1] = 0xFFFFFFFFL; - rgb[2] = 0xFFFFFFFFL; - rgb[3] = 0xFFFFFFFFL; - IdMode = 0; - ras_mode = 0; - glslmat = 0; - tile = 0; - matname = "NoMaterial"; - matcolor[0] = 0.5f; - matcolor[1] = 0.5f; - matcolor[2] = 0.5f; - matcolor[3] = 0.5f; - speccolor[0] = 1.f; - speccolor[1] = 1.f; - speccolor[2] = 1.f; - alphablend = 0; - hard = 50.f; - spec_f = 0.5f; - alpha = 1.f; - emit = 0.f; - material = 0; - materialindex = 0; - amb=0.5f; - num_enabled = 0; - num_users = 1; - share = false; - - int i; - - for (i = 0; i < MAXTEX; i++) // :( - { - mapping[i].mapping = 0; - mapping[i].offsets[0] = 0.f; - mapping[i].offsets[1] = 0.f; - mapping[i].offsets[2] = 0.f; - mapping[i].scale[0] = 1.f; - mapping[i].scale[1] = 1.f; - mapping[i].scale[2] = 1.f; - mapping[i].projplane[0] = PROJX; - mapping[i].projplane[1] = PROJY; - mapping[i].projplane[2] = PROJZ; - mapping[i].objconame = ""; - mtexname[i] = "NULL"; - imageId[i]="NULL"; - flag[i] = 0; - texname[i] = "NULL"; - tilexrep[i] = 1; - tileyrep[i] = 1; - color_blend[i] = 1.f; - blend_mode[i] = 0; - img[i] = 0; - cubemap[i] = 0; - } -} - -void BL_Material::SetSharedMaterial(bool v) -{ - if ((v && num_users == -1) || num_users > 1 ) - share = true; - else - share = false; -} - -bool BL_Material::IsShared() -{ - return share; -} - -void BL_Material::SetUsers(int num) -{ - num_users = num; -} - diff --git a/source/gameengine/Ketsji/BL_Material.h b/source/gameengine/Ketsji/BL_Material.h deleted file mode 100644 index 710c02f4871..00000000000 --- a/source/gameengine/Ketsji/BL_Material.h +++ /dev/null @@ -1,182 +0,0 @@ - -/** \file BL_Material.h - * \ingroup ketsji - */ - -#ifndef __BL_MATERIAL_H__ -#define __BL_MATERIAL_H__ - -#include "STR_String.h" -#include "MT_Point2.h" -#include "DNA_meshdata_types.h" - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -// -- -struct MTex; -struct Material; -struct Image; -struct MTFace; -struct MTex; -struct Material; -struct EnvMap; -// -- - -/** max units - * this will default to users available units - * to build with more available, just increment this value - * although the more you add the slower the search time will be. - * we will go for eight, which should be enough - */ -#define MAXTEX 8 //match in RAS_TexVert & RAS_OpenGLRasterizer - -// different mapping modes -class BL_Mapping -{ -public: - int mapping; - float scale[3]; - float offsets[3]; - int projplane[3]; - STR_String objconame; - STR_String uvCoName; -}; - -// base material struct -class BL_Material -{ -private: - int num_users; - bool share; - -public: - // ----------------------------------- - BL_Material(); - void Initialize(); - - int IdMode; - unsigned int ras_mode; - bool glslmat; - - STR_String texname[MAXTEX]; - unsigned int flag[MAXTEX]; - int tile,tilexrep[MAXTEX],tileyrep[MAXTEX]; - STR_String matname; - STR_String mtexname[MAXTEX]; - int materialindex; - - float matcolor[4]; - float speccolor[3]; - short alphablend, pad; - - float hard, spec_f; - float alpha, emit, color_blend[MAXTEX], ref; - float amb; - - int blend_mode[MAXTEX]; - - int num_enabled; - - BL_Mapping mapping[MAXTEX]; - STR_String imageId[MAXTEX]; - - - Material* material; - Image* img[MAXTEX]; - EnvMap* cubemap[MAXTEX]; - - unsigned int rgb[4]; - - void SetSharedMaterial(bool v); - bool IsShared(); - void SetUsers(int num); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_Material") -#endif -}; - -// BL_Material::IdMode -enum BL_IdMode { - DEFAULT_BLENDER=-1, - TEXFACE, - ONETEX, - TWOTEX, - GREATERTHAN2 -}; - -// BL_Material::blend_mode[index] -enum BL_BlendMode -{ - BLEND_MIX=1, - BLEND_ADD, - BLEND_SUB, - BLEND_MUL, - BLEND_SCR -}; - -// ------------------------------------- -// BL_Material::flag[index] -enum BL_flag -{ - MIPMAP=1, // set to use mipmaps - CALCALPHA=2, // additive - USEALPHA=4, // use actual alpha channel - TEXALPHA=8, // use alpha combiner functions - TEXNEG=16, // negate blending - /*HASIPO=32,*/ // unused, commeted for now. - USENEGALPHA=64 -}; - -// BL_Material::ras_mode -enum BL_ras_mode -{ - // POLY_VIS=1, - COLLIDER=2, - ZSORT=4, - ALPHA=8, - // TRIANGLE=16, - USE_LIGHT=32, - WIRE=64, - CAST_SHADOW=128, - TEX=256, - TWOSIDED=512, - ONLY_SHADOW=1024, -}; - -// ------------------------------------- -// BL_Material::mapping[index]::mapping -enum BL_MappingFlag -{ - USEENV =1, - // -- - USEREFL =2, - USEOBJ =4, - USENORM =8, - USEORCO =16, - USEUV =32, - USETANG =64, - DISABLE =128, - USECUSTOMUV=256 -}; - -// BL_Material::BL_Mapping::projplane -enum BL_MappingProj -{ - PROJN=0, - PROJX, - PROJY, - PROJZ -}; - -// ------------------------------------ -//extern void initBL_Material(BL_Material* mat); -extern MTex* getMTexFromMaterial(Material *mat, int index); -// ------------------------------------ - -#endif - - diff --git a/source/gameengine/Ketsji/BL_Shader.cpp b/source/gameengine/Ketsji/BL_Shader.cpp deleted file mode 100644 index d344e18c313..00000000000 --- a/source/gameengine/Ketsji/BL_Shader.cpp +++ /dev/null @@ -1,1478 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/BL_Shader.cpp - * \ingroup ketsji - */ - -#include "GPU_glew.h" - -#include -#include "BL_Shader.h" -#include "BL_Material.h" - -#include "MT_assert.h" -#include "MT_Matrix4x4.h" -#include "MT_Matrix3x3.h" -#include "KX_PyMath.h" -#include "KX_PythonInit.h" -#include "MEM_guardedalloc.h" - -#include "RAS_MeshObject.h" -#include "RAS_IRasterizer.h" - -#define spit(x) std::cout << x << std::endl; - -#define SORT_UNIFORMS 1 -#define UNIFORM_MAX_LEN (int)sizeof(float) * 16 -#define MAX_LOG_LEN 262144 // bounds - -BL_Uniform::BL_Uniform(int data_size) - : - mLoc(-1), - mDirty(true), - mType(UNI_NONE), - mTranspose(0), - mDataLen(data_size) -{ -#ifdef SORT_UNIFORMS - MT_assert((int)mDataLen <= UNIFORM_MAX_LEN); - mData = (void *)MEM_mallocN(mDataLen, "shader-uniform-alloc"); -#endif -} - -BL_Uniform::~BL_Uniform() -{ -#ifdef SORT_UNIFORMS - if (mData) { - MEM_freeN(mData); - mData = NULL; - } -#endif -} - -bool BL_Uniform::Apply(class BL_Shader *shader) -{ -#ifdef SORT_UNIFORMS - RAS_IRasterizer *ras; - MT_assert(mType > UNI_NONE && mType < UNI_MAX && mData); - - if (!mDirty) - return false; - - mDirty = false; - switch (mType) { - case UNI_FLOAT: - { - float *f = (float *)mData; - glUniform1fARB(mLoc, (GLfloat)*f); - break; - } - case UNI_FLOAT_EYE: - { - float *f = (float*)mData; - ras = KX_GetActiveEngine()->GetRasterizer(); - *f = (ras->GetEye() == RAS_IRasterizer::RAS_STEREO_LEFTEYE) ? 0.0f : 0.5f; - glUniform1fARB(mLoc, (GLfloat)*f); - mDirty = (ras->Stereo()) ? true : false; - break; - } - case UNI_INT: - { - int *f = (int *)mData; - glUniform1iARB(mLoc, (GLint)*f); - break; - } - case UNI_FLOAT2: - { - float *f = (float *)mData; - glUniform2fvARB(mLoc, 1, (GLfloat *)f); - break; - } - case UNI_FLOAT3: - { - float *f = (float *)mData; - glUniform3fvARB(mLoc, 1, (GLfloat *)f); - break; - } - case UNI_FLOAT4: - { - float *f = (float *)mData; - glUniform4fvARB(mLoc, 1, (GLfloat *)f); - break; - } - case UNI_INT2: - { - int *f = (int *)mData; - glUniform2ivARB(mLoc, 1, (GLint *)f); - break; - } - case UNI_INT3: - { - int *f = (int *)mData; - glUniform3ivARB(mLoc, 1, (GLint *)f); - break; - } - case UNI_INT4: - { - int *f = (int *)mData; - glUniform4ivARB(mLoc, 1, (GLint *)f); - break; - } - case UNI_MAT4: - { - float *f = (float *)mData; - glUniformMatrix4fvARB(mLoc, 1, mTranspose ? GL_TRUE : GL_FALSE, (GLfloat *)f); - break; - } - case UNI_MAT3: - { - float *f = (float *)mData; - glUniformMatrix3fvARB(mLoc, 1, mTranspose ? GL_TRUE : GL_FALSE, (GLfloat *)f); - break; - } - } - return mDirty; -#endif -} - -void BL_Uniform::SetData(int location, int type, bool transpose) -{ -#ifdef SORT_UNIFORMS - mType = type; - mLoc = location; - mDirty = true; -#endif -} - -bool BL_Shader::Ok()const -{ - return (mShader != 0 && mOk && mUse); -} - -BL_Shader::BL_Shader() - : - PyObjectPlus(), - mShader(0), - mPass(1), - mOk(0), - mUse(0), - mAttr(0), - vertProg(NULL), - fragProg(NULL), - mError(0), - mDirty(true) -{ - // if !GLEW_ARB_shader_objects this class will not be used - //for (int i=0; iDeleteTex(); - // } - //} - ClearUniforms(); - - if (mShader) { - glDeleteObjectARB(mShader); - mShader = 0; - } - - vertProg = NULL; - fragProg = NULL; - mOk = 0; - glUseProgramObjectARB(0); -} - -void BL_Shader::ClearUniforms() -{ - BL_UniformVec::iterator it = mUniforms.begin(); - while (it != mUniforms.end()) { - delete *it; - it++; - } - mUniforms.clear(); - - BL_UniformVecDef::iterator itp = mPreDef.begin(); - while (itp != mPreDef.end()) { - delete *itp; - itp++; - } - mPreDef.clear(); -} - -BL_Uniform *BL_Shader::FindUniform(const int location) -{ -#ifdef SORT_UNIFORMS - BL_UniformVec::iterator it = mUniforms.begin(); - while (it != mUniforms.end()) { - if ((*it)->GetLocation() == location) { - return *it; - } - it++; - } -#endif - return NULL; -} - -void BL_Shader::SetUniformfv(int location, int type, float *param, int size, bool transpose) -{ -#ifdef SORT_UNIFORMS - BL_Uniform *uni = FindUniform(location); - - if (uni) { - memcpy(uni->getData(), param, size); - uni->SetData(location, type, transpose); - } - else { - uni = new BL_Uniform(size); - memcpy(uni->getData(), param, size); - uni->SetData(location, type, transpose); - mUniforms.push_back(uni); - } - - mDirty = true; -#endif -} - -void BL_Shader::SetUniformiv(int location, int type, int *param, int size, bool transpose) -{ -#ifdef SORT_UNIFORMS - BL_Uniform *uni = FindUniform(location); - - if (uni) { - memcpy(uni->getData(), param, size); - uni->SetData(location, type, transpose); - } - else { - uni = new BL_Uniform(size); - memcpy(uni->getData(), param, size); - uni->SetData(location, type, transpose); - mUniforms.push_back(uni); - } - - mDirty = true; -#endif -} - -void BL_Shader::ApplyShader() -{ -#ifdef SORT_UNIFORMS - if (!mDirty) { - return; - } - - mDirty = false; - for (unsigned int i=0; iApply(this); - } -#endif -} - -void BL_Shader::UnloadShader() -{ - // -} - -bool BL_Shader::LinkProgram() -{ - int vertlen = 0, fraglen = 0, proglen = 0; - int vertstatus = 0, fragstatus = 0, progstatus = 0; - unsigned int tmpVert = 0, tmpFrag = 0, tmpProg = 0; - int char_len = 0; - char *logInf = NULL; - - if (mError) { - goto programError; - } - - if (!vertProg || !fragProg) { - spit("Invalid GLSL sources"); - return false; - } - - if (!GLEW_ARB_fragment_shader) { - spit("Fragment shaders not supported"); - return false; - } - - if (!GLEW_ARB_vertex_shader) { - spit("Vertex shaders not supported"); - return false; - } - - if (vertProg[0] != 0) { - // -- vertex shader ------------------ - tmpVert = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB); - glShaderSourceARB(tmpVert, 1, (const char**)&vertProg, 0); - glCompileShaderARB(tmpVert); - glGetObjectParameterivARB(tmpVert, GL_OBJECT_INFO_LOG_LENGTH_ARB, (GLint*)&vertlen); - - // print info if any - if (vertlen > 0 && vertlen < MAX_LOG_LEN) { - logInf = (char*)MEM_mallocN(vertlen, "vert-log"); - glGetInfoLogARB(tmpVert, vertlen, (GLsizei*)&char_len, logInf); - if (char_len > 0) { - spit("---- Vertex Shader Error ----"); - spit(logInf); - } - MEM_freeN(logInf); - logInf = 0; - } - // check for compile errors - glGetObjectParameterivARB(tmpVert, GL_OBJECT_COMPILE_STATUS_ARB, (GLint*)&vertstatus); - if (!vertstatus) { - spit("---- Vertex shader failed to compile ----"); - goto programError; - } - } - - if (fragProg[0] != 0) { - // -- fragment shader ---------------- - tmpFrag = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB); - glShaderSourceARB(tmpFrag, 1, (const char**)&fragProg, 0); - glCompileShaderARB(tmpFrag); - glGetObjectParameterivARB(tmpFrag, GL_OBJECT_INFO_LOG_LENGTH_ARB, (GLint*)&fraglen); - if (fraglen > 0 && fraglen < MAX_LOG_LEN) { - logInf = (char*)MEM_mallocN(fraglen, "frag-log"); - glGetInfoLogARB(tmpFrag, fraglen, (GLsizei*)&char_len, logInf); - if (char_len > 0) { - spit("---- Fragment Shader Error ----"); - spit(logInf); - } - MEM_freeN(logInf); - logInf = 0; - } - - glGetObjectParameterivARB(tmpFrag, GL_OBJECT_COMPILE_STATUS_ARB, (GLint*)&fragstatus); - if (!fragstatus) { - spit("---- Fragment shader failed to compile ----"); - goto programError; - } - } - - if (!tmpFrag && !tmpVert) { - spit("---- No shader given ----"); - goto programError; - } - - // -- program ------------------------ - // set compiled vert/frag shader & link - tmpProg = glCreateProgramObjectARB(); - if (tmpVert) { - glAttachObjectARB(tmpProg, tmpVert); - } - if (tmpFrag) { - glAttachObjectARB(tmpProg, tmpFrag); - } - glLinkProgramARB(tmpProg); - glGetObjectParameterivARB(tmpProg, GL_OBJECT_INFO_LOG_LENGTH_ARB, (GLint *)&proglen); - glGetObjectParameterivARB(tmpProg, GL_OBJECT_LINK_STATUS_ARB, (GLint *)&progstatus); - - if (proglen > 0 && proglen < MAX_LOG_LEN) { - logInf = (char *)MEM_mallocN(proglen, "prog-log"); - glGetInfoLogARB(tmpProg, proglen, (GLsizei *)&char_len, logInf); - - if (char_len > 0) { - spit("---- GLSL Program ----"); - spit(logInf); - } - - MEM_freeN(logInf); - logInf = 0; - } - - if (!progstatus) { - spit("---- GLSL program failed to link ----"); - goto programError; - } - - // set - mShader = tmpProg; - if (tmpVert) { - glDeleteObjectARB(tmpVert); - } - if (tmpFrag) { - glDeleteObjectARB(tmpFrag); - } - mOk = 1; - mError = 0; - return true; - -programError: - if (tmpVert) { - glDeleteObjectARB(tmpVert); - tmpVert = 0; - } - - if (tmpFrag) { - glDeleteObjectARB(tmpFrag); - tmpFrag = 0; - } - - if (tmpProg) { - glDeleteObjectARB(tmpProg); - tmpProg = 0; - } - - mOk = 0; - mUse = 0; - mError = 1; - return false; -} - -const char *BL_Shader::GetVertPtr() -{ - return vertProg ? vertProg : NULL; -} - -const char *BL_Shader::GetFragPtr() -{ - return fragProg ? fragProg : NULL; -} - -void BL_Shader::SetVertPtr(char *vert) -{ - vertProg = vert; -} - -void BL_Shader::SetFragPtr(char *frag) -{ - fragProg = frag; -} - -unsigned int BL_Shader::GetProg() -{ - return mShader; -} - -//const BL_Sampler *BL_Shader::GetSampler(int i) -//{ -// MT_assert(i<=MAXTEX); -// return &mSampler[i]; -//} - -void BL_Shader::SetSampler(int loc, int unit) -{ - if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) { - glUniform1iARB(loc, unit); - } -} - -//void BL_Shader::InitializeSampler(int unit, BL_Texture *texture) -//{ -// MT_assert(unit <= MAXTEX); -// mSampler[unit].mTexture = texture; -// mSampler[unit].mLoc = -1; -// mSampler[unit].mOwn = 0; -//} - -void BL_Shader::SetProg(bool enable) -{ - if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) { - if (mShader != 0 && mOk && enable) { - glUseProgramObjectARB(mShader); - } - else { - glUseProgramObjectARB(0); - } - } -} - -void BL_Shader::Update(const RAS_MeshSlot &ms, RAS_IRasterizer *rasty) -{ - if (!Ok() || !mPreDef.size()) { - return; - } - - if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) { - MT_Matrix4x4 model; - model.setValue(ms.m_OpenGLMatrix); - const MT_Matrix4x4 &view = rasty->GetViewMatrix(); - - if (mAttr == SHD_TANGENT) { - ms.m_mesh->SetMeshModified(true); - } - - BL_UniformVecDef::iterator it; - for (it = mPreDef.begin(); it != mPreDef.end(); it++) { - BL_DefUniform *uni = (*it); - - if (uni->mLoc == -1) { - continue; - } - - switch (uni->mType) { - case MODELMATRIX: - { - SetUniform(uni->mLoc, model); - break; - } - case MODELMATRIX_TRANSPOSE: - { - SetUniform(uni->mLoc, model, true); - break; - } - case MODELMATRIX_INVERSE: - { - model.invert(); - SetUniform(uni->mLoc, model); - break; - } - case MODELMATRIX_INVERSETRANSPOSE: - { - model.invert(); - SetUniform(uni->mLoc, model, true); - break; - } - case MODELVIEWMATRIX: - { - SetUniform(uni->mLoc, view * model); - break; - } - case MODELVIEWMATRIX_TRANSPOSE: - { - MT_Matrix4x4 mat(view * model); - SetUniform(uni->mLoc, mat, true); - break; - } - case MODELVIEWMATRIX_INVERSE: - { - MT_Matrix4x4 mat(view * model); - mat.invert(); - SetUniform(uni->mLoc, mat); - break; - } - case MODELVIEWMATRIX_INVERSETRANSPOSE: - { - MT_Matrix4x4 mat(view * model); - mat.invert(); - SetUniform(uni->mLoc, mat, true); - break; - } - case CAM_POS: - { - MT_Point3 pos(rasty->GetCameraPosition()); - SetUniform(uni->mLoc, pos); - break; - } - case VIEWMATRIX: - { - SetUniform(uni->mLoc, view); - break; - } - case VIEWMATRIX_TRANSPOSE: - { - SetUniform(uni->mLoc, view, true); - break; - } - case VIEWMATRIX_INVERSE: - { - MT_Matrix4x4 viewinv = view; - viewinv.invert(); - SetUniform(uni->mLoc, view); - break; - } - case VIEWMATRIX_INVERSETRANSPOSE: - { - MT_Matrix4x4 viewinv = view; - viewinv.invert(); - SetUniform(uni->mLoc, view, true); - break; - } - case CONSTANT_TIMER: - { - SetUniform(uni->mLoc, (float)rasty->GetTime()); - break; - } - default: - break; - } - } - } -} - -int BL_Shader::GetAttribLocation(const char *name) -{ - if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) { - return glGetAttribLocationARB(mShader, name); - } - - return -1; -} - -void BL_Shader::BindAttribute(const char *attr, int loc) -{ - if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) { - glBindAttribLocationARB(mShader, loc, attr); - } -} - -int BL_Shader::GetUniformLocation(const char *name) -{ - if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) { - MT_assert(mShader != 0); - int location = glGetUniformLocationARB(mShader, name); - - if (location == -1) { - spit("Invalid uniform value: " << name << "."); - } - - return location; - } - return -1; -} - -void BL_Shader::SetUniform(int uniform, const MT_Tuple2 &vec) -{ - if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) { - float value[2]; - vec.getValue(value); - glUniform2fvARB(uniform, 1, value); - } -} - -void BL_Shader::SetUniform(int uniform, const MT_Tuple3 &vec) -{ - if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) { - float value[3]; - vec.getValue(value); - glUniform3fvARB(uniform, 1, value); - } -} - -void BL_Shader::SetUniform(int uniform, const MT_Tuple4 &vec) -{ - if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) { - float value[4]; - vec.getValue(value); - glUniform4fvARB(uniform, 1, value); - } -} - -void BL_Shader::SetUniform(int uniform, const unsigned int &val) -{ - if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) { - glUniform1iARB(uniform, val); - } -} - -void BL_Shader::SetUniform(int uniform, const int val) -{ - if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) { - glUniform1iARB(uniform, val); - } -} - -void BL_Shader::SetUniform(int uniform, const float &val) -{ - if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) { - glUniform1fARB(uniform, val); - } -} - -void BL_Shader::SetUniform(int uniform, const MT_Matrix4x4 &vec, bool transpose) -{ - if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) { - float value[16]; - // note: getValue gives back column major as needed by OpenGL - vec.getValue(value); - glUniformMatrix4fvARB(uniform, 1, transpose ? GL_TRUE : GL_FALSE, value); - } -} - -void BL_Shader::SetUniform(int uniform, const MT_Matrix3x3 &vec, bool transpose) -{ - if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) { - float value[9]; - value[0] = (float)vec[0][0]; - value[1] = (float)vec[1][0]; - value[2] = (float)vec[2][0]; - value[3] = (float)vec[0][1]; - value[4] = (float)vec[1][1]; - value[5] = (float)vec[2][1]; - value[6] = (float)vec[0][2]; - value[7] = (float)vec[1][2]; - value[8] = (float)vec[2][2]; - glUniformMatrix3fvARB(uniform, 1, transpose ? GL_TRUE : GL_FALSE, value); - } -} - -void BL_Shader::SetUniform(int uniform, const float *val, int len) -{ - if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) { - if (len == 2) { - glUniform2fvARB(uniform, 1, (GLfloat *)val); - } - else if (len == 3) { - glUniform3fvARB(uniform, 1, (GLfloat *)val); - } - else if (len == 4) { - glUniform4fvARB(uniform, 1, (GLfloat *)val); - } - else { - MT_assert(0); - } - } -} - -void BL_Shader::SetUniform(int uniform, const int *val, int len) -{ - if (GLEW_ARB_fragment_shader && GLEW_ARB_vertex_shader && GLEW_ARB_shader_objects) { - if (len == 2) { - glUniform2ivARB(uniform, 1, (GLint *)val); - } - else if (len == 3) { - glUniform3ivARB(uniform, 1, (GLint *)val); - } - else if (len == 4) { - glUniform4ivARB(uniform, 1, (GLint *)val); - } - else { - MT_assert(0); - } - } -} - -#ifdef WITH_PYTHON -PyMethodDef BL_Shader::Methods[] = { - // creation - KX_PYMETHODTABLE(BL_Shader, setSource), - KX_PYMETHODTABLE(BL_Shader, delSource), - KX_PYMETHODTABLE(BL_Shader, getVertexProg), - KX_PYMETHODTABLE(BL_Shader, getFragmentProg), - KX_PYMETHODTABLE(BL_Shader, setNumberOfPasses), - KX_PYMETHODTABLE(BL_Shader, validate), - // access functions - KX_PYMETHODTABLE(BL_Shader, isValid), - KX_PYMETHODTABLE(BL_Shader, setUniformEyef), - KX_PYMETHODTABLE(BL_Shader, setUniform1f), - KX_PYMETHODTABLE(BL_Shader, setUniform2f), - KX_PYMETHODTABLE(BL_Shader, setUniform3f), - KX_PYMETHODTABLE(BL_Shader, setUniform4f), - KX_PYMETHODTABLE(BL_Shader, setUniform1i), - KX_PYMETHODTABLE(BL_Shader, setUniform2i), - KX_PYMETHODTABLE(BL_Shader, setUniform3i), - KX_PYMETHODTABLE(BL_Shader, setUniform4i), - KX_PYMETHODTABLE(BL_Shader, setAttrib), - KX_PYMETHODTABLE(BL_Shader, setUniformfv), - KX_PYMETHODTABLE(BL_Shader, setUniformiv), - KX_PYMETHODTABLE(BL_Shader, setUniformDef), - KX_PYMETHODTABLE(BL_Shader, setSampler), - KX_PYMETHODTABLE(BL_Shader, setUniformMatrix4), - KX_PYMETHODTABLE(BL_Shader, setUniformMatrix3), - {NULL, NULL} //Sentinel -}; - -PyAttributeDef BL_Shader::Attributes[] = { - {NULL} //Sentinel -}; - -PyTypeObject BL_Shader::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "BL_Shader", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0, 0, 0, 0, 0, 0, 0, 0, 0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0, 0, 0, 0, 0, 0, 0, - Methods, - 0, - 0, - &PyObjectPlus::Type, - 0, 0, 0, 0, 0, 0, - py_base_new -}; - -KX_PYMETHODDEF_DOC(BL_Shader, setSource, " setSource(vertexProgram, fragmentProgram)") -{ - if (mShader != 0 && mOk) { - // already set... - Py_RETURN_NONE; - } - - char *v, *f; - int apply = 0; - - if (PyArg_ParseTuple(args, "ssi:setSource", &v, &f, &apply)) { - vertProg = v; - fragProg = f; - - if (LinkProgram()) { - glUseProgramObjectARB(mShader); - mUse = apply != 0; - Py_RETURN_NONE; - } - - vertProg = NULL; - fragProg = NULL; - mUse = 0; - Py_RETURN_NONE; - } - return NULL; -} - - -KX_PYMETHODDEF_DOC(BL_Shader, delSource, "delSource( )") -{ - ClearUniforms(); - glUseProgramObjectARB(0); - glDeleteObjectARB(mShader); - mShader = 0; - mOk = 0; - mUse = 0; - Py_RETURN_NONE; -} - -KX_PYMETHODDEF_DOC(BL_Shader, isValid, "isValid()") -{ - return PyBool_FromLong((mShader != 0 && mOk)); -} - -KX_PYMETHODDEF_DOC(BL_Shader, getVertexProg, "getVertexProg( )") -{ - return PyUnicode_FromString(vertProg ? vertProg : ""); -} - -KX_PYMETHODDEF_DOC(BL_Shader, getFragmentProg, "getFragmentProg( )") -{ - return PyUnicode_FromString(fragProg ? fragProg : ""); -} - -KX_PYMETHODDEF_DOC(BL_Shader, validate, "validate()") -{ - if (mError) { - Py_RETURN_NONE; - } - - if (mShader == 0) { - PyErr_SetString(PyExc_TypeError, "shader.validate(): BL_Shader, invalid shader object"); - return NULL; - } - - int stat = 0; - glValidateProgramARB(mShader); - glGetObjectParameterivARB(mShader, GL_OBJECT_VALIDATE_STATUS_ARB, (GLint *)&stat); - - if (stat > 0 && stat < MAX_LOG_LEN) { - int char_len = 0; - char *logInf = (char *)MEM_mallocN(stat, "validate-log"); - - glGetInfoLogARB(mShader, stat, (GLsizei *)&char_len, logInf); - - if (char_len > 0) { - spit("---- GLSL Validation ----"); - spit(logInf); - } - MEM_freeN(logInf); - logInf = NULL; - } - Py_RETURN_NONE; -} - - -KX_PYMETHODDEF_DOC(BL_Shader, setSampler, "setSampler(name, index)") -{ - if (mError) { - Py_RETURN_NONE; - } - - const char *uniform; - int index = -1; - - if (PyArg_ParseTuple(args, "si:setSampler", &uniform, &index)) { - int loc = GetUniformLocation(uniform); - - if (loc != -1) { - if (index >= MAXTEX || index < 0) { - spit("Invalid texture sample index: " << index); - } -#ifdef SORT_UNIFORMS - SetUniformiv(loc, BL_Uniform::UNI_INT, &index, (sizeof(int))); -#else - SetUniform(loc, index); -#endif - //if (index <= MAXTEX) - // mSampler[index].mLoc = loc; - //else - // spit("Invalid texture sample index: " << index); - } - Py_RETURN_NONE; - } - return NULL; -} - -KX_PYMETHODDEF_DOC(BL_Shader, setNumberOfPasses, "setNumberOfPasses( max-pass )") -{ - int pass = 1; - - if (!PyArg_ParseTuple(args, "i:setNumberOfPasses", &pass)) { - return NULL; - } - - mPass = 1; - Py_RETURN_NONE; -} - -/// access functions -KX_PYMETHODDEF_DOC(BL_Shader, setUniform1f, "setUniform1f(name, fx)") -{ - if (mError) { - Py_RETURN_NONE; - } - - const char *uniform; - float value = 0.0f; - - if (PyArg_ParseTuple(args, "sf:setUniform1f", &uniform, &value)) { - int loc = GetUniformLocation(uniform); - - if (loc != -1) { -#ifdef SORT_UNIFORMS - SetUniformfv(loc, BL_Uniform::UNI_FLOAT, &value, sizeof(float)); -#else - SetUniform(loc, (float)value); -#endif - } - Py_RETURN_NONE; - } - return NULL; -} - -KX_PYMETHODDEF_DOC(BL_Shader, setUniform2f, "setUniform2f(name, fx, fy)") -{ - if (mError) { - Py_RETURN_NONE; - } - - const char *uniform; - float array[2] = {0.0f, 0.0f}; - - if (PyArg_ParseTuple(args, "sff:setUniform2f", &uniform, &array[0], &array[1])) { - int loc = GetUniformLocation(uniform); - - if (loc != -1) { -#ifdef SORT_UNIFORMS - SetUniformfv(loc, BL_Uniform::UNI_FLOAT2, array, (sizeof(float) * 2)); -#else - SetUniform(loc, array, 2); -#endif - } - Py_RETURN_NONE; - } - return NULL; -} - -KX_PYMETHODDEF_DOC(BL_Shader, setUniform3f, "setUniform3f(name, fx,fy,fz) ") -{ - if (mError) { - Py_RETURN_NONE; - } - - const char *uniform; - float array[3] = {0.0f, 0.0f, 0.0f}; - - if (PyArg_ParseTuple(args, "sfff:setUniform3f", &uniform, &array[0], &array[1], &array[2])) { - int loc = GetUniformLocation(uniform); - - if (loc != -1) { -#ifdef SORT_UNIFORMS - SetUniformfv(loc, BL_Uniform::UNI_FLOAT3, array, (sizeof(float) * 3)); -#else - SetUniform(loc, array, 3); -#endif - } - Py_RETURN_NONE; - } - return NULL; -} - -KX_PYMETHODDEF_DOC(BL_Shader, setUniform4f, "setUniform4f(name, fx,fy,fz, fw) ") -{ - if (mError) { - Py_RETURN_NONE; - } - - const char *uniform; - float array[4] = {0.0f, 0.0f, 0.0f, 0.0f}; - - if (PyArg_ParseTuple(args, "sffff:setUniform4f", &uniform, &array[0], &array[1], &array[2], &array[3])) { - int loc = GetUniformLocation(uniform); - - if (loc != -1) { -#ifdef SORT_UNIFORMS - SetUniformfv(loc, BL_Uniform::UNI_FLOAT4, array, (sizeof(float) * 4)); -#else - SetUniform(loc, array, 4); -#endif - } - Py_RETURN_NONE; - } - return NULL; -} - -KX_PYMETHODDEF_DOC(BL_Shader, setUniformEyef, "setUniformEyef(name)") -{ - if (mError) { - Py_RETURN_NONE; - } - const char *uniform; - float value = 0.0f; - if (PyArg_ParseTuple(args, "s:setUniformEyef", &uniform)) { - int loc = GetUniformLocation(uniform); - if (loc != -1) { -#ifdef SORT_UNIFORMS - SetUniformfv(loc, BL_Uniform::UNI_FLOAT_EYE, &value, sizeof(float)); -#else - SetUniform(loc, (int)value); -#endif - } - Py_RETURN_NONE; - } - return NULL; -} - -KX_PYMETHODDEF_DOC(BL_Shader, setUniform1i, "setUniform1i(name, ix)") -{ - if (mError) { - Py_RETURN_NONE; - } - - const char *uniform; - int value = 0; - - if (PyArg_ParseTuple(args, "si:setUniform1i", &uniform, &value)) { - int loc = GetUniformLocation(uniform); - - if (loc != -1) { -#ifdef SORT_UNIFORMS - SetUniformiv(loc, BL_Uniform::UNI_INT, &value, sizeof(int)); -#else - SetUniform(loc, (int)value); -#endif - } - Py_RETURN_NONE; - } - return NULL; -} - -KX_PYMETHODDEF_DOC(BL_Shader, setUniform2i, "setUniform2i(name, ix, iy)") -{ - if (mError) { - Py_RETURN_NONE; - } - - const char *uniform; - int array[2] = {0, 0}; - - if (PyArg_ParseTuple(args, "sii:setUniform2i", &uniform, &array[0], &array[1])) { - int loc = GetUniformLocation(uniform); - - if (loc != -1) { -#ifdef SORT_UNIFORMS - SetUniformiv(loc, BL_Uniform::UNI_INT2, array, sizeof(int) * 2); -#else - SetUniform(loc, array, 2); -#endif - } - Py_RETURN_NONE; - } - return NULL; -} - -KX_PYMETHODDEF_DOC(BL_Shader, setUniform3i, "setUniform3i(name, ix,iy,iz) ") -{ - if (mError) { - Py_RETURN_NONE; - } - - const char *uniform; - int array[3] = {0, 0, 0}; - - if (PyArg_ParseTuple(args, "siii:setUniform3i", &uniform, &array[0], &array[1], &array[2])) { - int loc = GetUniformLocation(uniform); - - if (loc != -1) { -#ifdef SORT_UNIFORMS - SetUniformiv(loc, BL_Uniform::UNI_INT3, array, sizeof(int) * 3); -#else - SetUniform(loc, array, 3); -#endif - } - Py_RETURN_NONE; - } - return NULL; -} - -KX_PYMETHODDEF_DOC(BL_Shader, setUniform4i, "setUniform4i(name, ix,iy,iz, iw) ") -{ - if (mError) { - Py_RETURN_NONE; - } - - const char *uniform; - int array[4] = {0, 0, 0, 0}; - - if (PyArg_ParseTuple(args, "siiii:setUniform4i", &uniform, &array[0], &array[1], &array[2], &array[3])) { - int loc = GetUniformLocation(uniform); - - if (loc != -1) { -#ifdef SORT_UNIFORMS - SetUniformiv(loc, BL_Uniform::UNI_INT4, array, sizeof(int) * 4); -#else - SetUniform(loc, array, 4); -#endif - } - Py_RETURN_NONE; - } - return NULL; -} - -KX_PYMETHODDEF_DOC(BL_Shader, setUniformfv, "setUniformfv(float (list2 or list3 or list4))") -{ - if (mError) { - Py_RETURN_NONE; - } - - const char *uniform = ""; - PyObject *listPtr = NULL; - float array_data[4] = {0.0f, 0.0f, 0.0f, 0.0f}; - - if (PyArg_ParseTuple(args, "sO:setUniformfv", &uniform, &listPtr)) { - int loc = GetUniformLocation(uniform); - if (loc != -1) { - if (PySequence_Check(listPtr)) { - unsigned int list_size = PySequence_Size(listPtr); - - for (unsigned int i = 0; (i < list_size && i < 4); i++) { - PyObject *item = PySequence_GetItem(listPtr, i); - array_data[i] = (float)PyFloat_AsDouble(item); - Py_DECREF(item); - } - - switch (list_size) { - case 2: - { - float array2[2] = {array_data[0], array_data[1]}; -#ifdef SORT_UNIFORMS - SetUniformfv(loc, BL_Uniform::UNI_FLOAT2, array2, sizeof(float) * 2); -#else - SetUniform(loc, array2, 2); -#endif - Py_RETURN_NONE; - break; - } - case 3: - { - float array3[3] = {array_data[0], array_data[1], array_data[2]}; -#ifdef SORT_UNIFORMS - SetUniformfv(loc, BL_Uniform::UNI_FLOAT3, array3, sizeof(float) * 3); -#else - SetUniform(loc, array3, 3); -#endif - Py_RETURN_NONE; - break; - } - case 4: - { - float array4[4] = {array_data[0], array_data[1], array_data[2], array_data[3]}; -#ifdef SORT_UNIFORMS - SetUniformfv(loc, BL_Uniform::UNI_FLOAT4, array4, sizeof(float) * 4); -#else - SetUniform(loc, array4, 4); -#endif - Py_RETURN_NONE; - break; - } - default: - { - PyErr_SetString(PyExc_TypeError, - "shader.setUniform4i(name, ix,iy,iz, iw): BL_Shader. invalid list size"); - return NULL; - break; - } - } - } - } - } - return NULL; -} - -KX_PYMETHODDEF_DOC(BL_Shader, setUniformiv, "setUniformiv(uniform_name, (list2 or list3 or list4))") -{ - if (mError) { - Py_RETURN_NONE; - } - - const char *uniform = ""; - PyObject *listPtr = NULL; - int array_data[4] = {0, 0, 0, 0}; - - if (!PyArg_ParseTuple(args, "sO:setUniformiv", &uniform, &listPtr)) { - return NULL; - } - - int loc = GetUniformLocation(uniform); - - if (loc == -1) { - PyErr_SetString(PyExc_TypeError, - "shader.setUniformiv(...): BL_Shader, first string argument is not a valid uniform value"); - return NULL; - } - - if (!PySequence_Check(listPtr)) { - PyErr_SetString(PyExc_TypeError, "shader.setUniformiv(...): BL_Shader, second argument is not a sequence"); - return NULL; - } - - unsigned int list_size = PySequence_Size(listPtr); - - for (unsigned int i = 0; (i < list_size && i < 4); i++) { - PyObject *item = PySequence_GetItem(listPtr, i); - array_data[i] = PyLong_AsLong(item); - Py_DECREF(item); - } - - if (PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, - "shader.setUniformiv(...): BL_Shader, one or more values in the list is not an int"); - return NULL; - } - - // Sanity checks done! - switch (list_size) { - case 2: - { - int array2[2] = {array_data[0], array_data[1]}; -#ifdef SORT_UNIFORMS - SetUniformiv(loc, BL_Uniform::UNI_INT2, array2, sizeof(int) * 2); -#else - SetUniform(loc, array2, 2); -#endif - Py_RETURN_NONE; - break; - } - case 3: - { - int array3[3] = {array_data[0], array_data[1], array_data[2]}; -#ifdef SORT_UNIFORMS - SetUniformiv(loc, BL_Uniform::UNI_INT3, array3, sizeof(int) * 3); -#else - SetUniform(loc, array3, 3); -#endif - Py_RETURN_NONE; - break; - } - case 4: - { - int array4[4] = {array_data[0], array_data[1], array_data[2], array_data[3]}; -#ifdef SORT_UNIFORMS - SetUniformiv(loc, BL_Uniform::UNI_INT4, array4, sizeof(int) * 4); -#else - SetUniform(loc, array4, 4); -#endif - Py_RETURN_NONE; - break; - } - default: - { - PyErr_SetString(PyExc_TypeError, - "shader.setUniformiv(...): BL_Shader, second argument, invalid list size, expected an int " - "list between 2 and 4"); - return NULL; - break; - } - } - Py_RETURN_NONE; -} - -KX_PYMETHODDEF_DOC(BL_Shader, setUniformMatrix4, - "setUniformMatrix4(uniform_name, mat-4x4, transpose(row-major=true, col-major=false)") -{ - if (mError) { - Py_RETURN_NONE; - } - - float matr[16] = { - 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f - }; - - const char *uniform; - PyObject *matrix = NULL; - int transp = 0; // python use column major by default, so no transpose.... - - if (!PyArg_ParseTuple(args, "sO|i:setUniformMatrix4", &uniform, &matrix, &transp)) { - return NULL; - } - - int loc = GetUniformLocation(uniform); - - if (loc == -1) { - PyErr_SetString(PyExc_TypeError, - "shader.setUniformMatrix4(...): BL_Shader, first string argument is not a valid uniform value"); - return NULL; - } - - MT_Matrix4x4 mat; - - if (!PyMatTo(matrix, mat)) { - PyErr_SetString(PyExc_TypeError, - "shader.setUniformMatrix4(...): BL_Shader, second argument cannot be converted into a 4x4 matrix"); - return NULL; - } - - // Sanity checks done! -#ifdef SORT_UNIFORMS - mat.getValue(matr); - SetUniformfv(loc, BL_Uniform::UNI_MAT4, matr, (sizeof(float) * 16), (transp != 0)); -#else - SetUniform(loc, mat, (transp != 0)); -#endif - Py_RETURN_NONE; -} - - -KX_PYMETHODDEF_DOC(BL_Shader, setUniformMatrix3, - "setUniformMatrix3(uniform_name, list[3x3], transpose(row-major=true, col-major=false)") -{ - if (mError) { - Py_RETURN_NONE; - } - - float matr[9] = { - 1.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 1.0f, - }; - - const char *uniform; - PyObject *matrix = NULL; - int transp = 0; // python use column major by default, so no transpose.... - - if (!PyArg_ParseTuple(args, "sO|i:setUniformMatrix3", &uniform, &matrix, &transp)) { - return NULL; - } - - int loc = GetUniformLocation(uniform); - - if (loc == -1) { - PyErr_SetString(PyExc_TypeError, - "shader.setUniformMatrix3(...): BL_Shader, first string argument is not a valid uniform value"); - return NULL; - } - - MT_Matrix3x3 mat; - - if (!PyMatTo(matrix, mat)) { - PyErr_SetString(PyExc_TypeError, - "shader.setUniformMatrix3(...): BL_Shader, second argument cannot be converted into a 3x3 matrix"); - return NULL; - } - -#ifdef SORT_UNIFORMS - mat.getValue3x3(matr); - SetUniformfv(loc, BL_Uniform::UNI_MAT3, matr, (sizeof(float) * 9), (transp != 0)); -#else - SetUniform(loc, mat, (transp != 0)); -#endif - Py_RETURN_NONE; -} - -KX_PYMETHODDEF_DOC(BL_Shader, setAttrib, "setAttrib(enum)") -{ - if (mError) { - Py_RETURN_NONE; - } - - int attr = 0; - - if (!PyArg_ParseTuple(args, "i:setAttrib", &attr)) { - return NULL; - } - - attr = SHD_TANGENT; // user input is ignored for now, there is only 1 attr - - if (mShader == 0) { - PyErr_SetString(PyExc_ValueError, "shader.setAttrib() BL_Shader, invalid shader object"); - return NULL; - } - - mAttr = attr; - glUseProgramObjectARB(mShader); - glBindAttribLocationARB(mShader, mAttr, "Tangent"); - Py_RETURN_NONE; -} - - -KX_PYMETHODDEF_DOC(BL_Shader, setUniformDef, "setUniformDef(name, enum)") -{ - if (mError) { - Py_RETURN_NONE; - } - - const char *uniform; - int nloc = 0; - if (PyArg_ParseTuple(args, "si:setUniformDef", &uniform, &nloc)) { - int loc = GetUniformLocation(uniform); - - if (loc != -1) { - bool defined = false; - BL_UniformVecDef::iterator it = mPreDef.begin(); - while (it != mPreDef.end()) { - if ((*it)->mLoc == loc) { - defined = true; - break; - } - it++; - } - - if (defined) { - Py_RETURN_NONE; - } - - BL_DefUniform *uni = new BL_DefUniform(); - uni->mLoc = loc; - uni->mType = nloc; - uni->mFlag = 0; - mPreDef.push_back(uni); - Py_RETURN_NONE; - } - } - return NULL; -} - -#endif // WITH_PYTHON - -// eof diff --git a/source/gameengine/Ketsji/BL_Shader.h b/source/gameengine/Ketsji/BL_Shader.h deleted file mode 100644 index 5de715d67d4..00000000000 --- a/source/gameengine/Ketsji/BL_Shader.h +++ /dev/null @@ -1,241 +0,0 @@ - -/** \file BL_Shader.h - * \ingroup ketsji - */ - -#ifndef __BL_SHADER_H__ -#define __BL_SHADER_H__ - -#include "EXP_PyObjectPlus.h" -#include "BL_Material.h" -#include "BL_Texture.h" -#include "MT_Matrix4x4.h" -#include "MT_Matrix3x3.h" -#include "MT_Tuple2.h" -#include "MT_Tuple3.h" -#include "MT_Tuple4.h" - -/** - * BL_Sampler - * Sampler access - */ -class BL_Sampler -{ -public: - BL_Sampler() - : - mLoc(-1) - { - } - - int mLoc; // Sampler location - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_Sampler") -#endif -}; - -/** - * BL_Uniform - * uniform storage - */ -class BL_Uniform -{ -private: - int mLoc; // Uniform location - void *mData; // Memory allocated for variable - bool mDirty; // Caching variable - int mType; // Enum UniformTypes - bool mTranspose; // Transpose matrices - const int mDataLen; // Length of our data -public: - BL_Uniform(int data_size); - ~BL_Uniform(); - - enum UniformTypes { - UNI_NONE = 0, - UNI_INT, - UNI_FLOAT, - UNI_INT2, - UNI_FLOAT2, - UNI_INT3, - UNI_FLOAT3, - UNI_INT4, - UNI_FLOAT4, - UNI_MAT3, - UNI_MAT4, - UNI_FLOAT_EYE, - UNI_MAX - }; - - bool Apply(class BL_Shader *shader); - void SetData(int location, int type, bool transpose = false); - int GetLocation() { return mLoc; } - void *getData() { return mData; } - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_Uniform") -#endif -}; - -/** - * BL_DefUniform - * pre defined uniform storage - */ -class BL_DefUniform -{ -public: - BL_DefUniform() - : - mType(0), - mLoc(0), - mFlag(0) - { - } - - int mType; - int mLoc; - unsigned int mFlag; - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_DefUniform") -#endif -}; - -/** - * BL_Shader - * shader access - */ -class BL_Shader : public PyObjectPlus -{ - Py_Header -private: - typedef std::vector BL_UniformVec; - typedef std::vector BL_UniformVecDef; - - unsigned int mShader; // Shader object - int mPass; // 1.. unused - bool mOk; // Valid and ok - bool mUse; - //BL_Sampler mSampler[MAXTEX]; // Number of samplers - int mAttr; // Tangent attribute - const char *vertProg; // Vertex program string - const char *fragProg; // Fragment program string - bool mError; - bool mDirty; - - // Stored uniform variables - BL_UniformVec mUniforms; - BL_UniformVecDef mPreDef; - - // Compiles and links the shader - bool LinkProgram(); - - // search by location - BL_Uniform *FindUniform(const int location); - - // clears uniform data - void ClearUniforms(); - -public: - BL_Shader(); - virtual ~BL_Shader(); - - // Unused for now tangent is set as tex coords - enum AttribTypes { - SHD_TANGENT = 1 - }; - - enum GenType { - MODELVIEWMATRIX, - MODELVIEWMATRIX_TRANSPOSE, - MODELVIEWMATRIX_INVERSE, - MODELVIEWMATRIX_INVERSETRANSPOSE, - MODELMATRIX, - MODELMATRIX_TRANSPOSE, - MODELMATRIX_INVERSE, - MODELMATRIX_INVERSETRANSPOSE, - VIEWMATRIX, - VIEWMATRIX_TRANSPOSE, - VIEWMATRIX_INVERSE, - VIEWMATRIX_INVERSETRANSPOSE, - CAM_POS, - CONSTANT_TIMER - }; - - const char *GetVertPtr(); - const char *GetFragPtr(); - void SetVertPtr(char *vert); - void SetFragPtr(char *frag); - int getNumPass() { return mPass; } - bool GetError() { return mError; } - - //const BL_Sampler *GetSampler(int i); - void SetSampler(int loc, int unit); - bool Ok() const; - unsigned int GetProg(); - void SetProg(bool enable); - int GetAttribute() { return mAttr; } - - // Apply methods : sets colected uniforms - void ApplyShader(); - void UnloadShader(); - - // Update predefined uniforms each render call - void Update(const class RAS_MeshSlot &ms, class RAS_IRasterizer *rasty); - - // Set sampler units (copied) - //void InitializeSampler(int unit, BL_Texture *texture); - void SetUniformfv(int location, int type, float *param, int size, bool transpose = false); - void SetUniformiv(int location, int type, int *param, int size, bool transpose = false); - int GetAttribLocation(const char *name); - void BindAttribute(const char *attr, int loc); - int GetUniformLocation(const char *name); - void SetUniform(int uniform, const MT_Tuple2 &vec); - void SetUniform(int uniform, const MT_Tuple3 &vec); - void SetUniform(int uniform, const MT_Tuple4 &vec); - void SetUniform(int uniform, const MT_Matrix4x4 &vec, bool transpose = false); - void SetUniform(int uniform, const MT_Matrix3x3 &vec, bool transpose = false); - void SetUniform(int uniform, const float &val); - void SetUniform(int uniform, const float *val, int len); - void SetUniform(int uniform, const int *val, int len); - void SetUniform(int uniform, const unsigned int &val); - void SetUniform(int uniform, const int val); - - // Python interface -#ifdef WITH_PYTHON - virtual PyObject *py_repr() - { - return PyUnicode_FromFormat("BL_Shader\n\tvertex shader:%s\n\n\tfragment shader%s\n\n", vertProg, fragProg); - } - - // ----------------------------------- - KX_PYMETHOD_DOC(BL_Shader, setSource); - KX_PYMETHOD_DOC(BL_Shader, delSource); - KX_PYMETHOD_DOC(BL_Shader, getVertexProg); - KX_PYMETHOD_DOC(BL_Shader, getFragmentProg); - KX_PYMETHOD_DOC(BL_Shader, setNumberOfPasses); - KX_PYMETHOD_DOC(BL_Shader, isValid); - KX_PYMETHOD_DOC(BL_Shader, validate); - - // ----------------------------------- - KX_PYMETHOD_DOC(BL_Shader, setUniform4f); - KX_PYMETHOD_DOC(BL_Shader, setUniform3f); - KX_PYMETHOD_DOC(BL_Shader, setUniform2f); - KX_PYMETHOD_DOC(BL_Shader, setUniform1f); - KX_PYMETHOD_DOC(BL_Shader, setUniform4i); - KX_PYMETHOD_DOC(BL_Shader, setUniform3i); - KX_PYMETHOD_DOC(BL_Shader, setUniform2i); - KX_PYMETHOD_DOC(BL_Shader, setUniform1i); - KX_PYMETHOD_DOC(BL_Shader, setUniformEyef); - KX_PYMETHOD_DOC(BL_Shader, setUniformfv); - KX_PYMETHOD_DOC(BL_Shader, setUniformiv); - KX_PYMETHOD_DOC(BL_Shader, setUniformMatrix4); - KX_PYMETHOD_DOC(BL_Shader, setUniformMatrix3); - KX_PYMETHOD_DOC(BL_Shader, setUniformDef); - KX_PYMETHOD_DOC(BL_Shader, setAttrib); - KX_PYMETHOD_DOC(BL_Shader, setSampler); -#endif -}; - -#endif /* __BL_SHADER_H__ */ diff --git a/source/gameengine/Ketsji/BL_Texture.cpp b/source/gameengine/Ketsji/BL_Texture.cpp deleted file mode 100644 index c3b799b9424..00000000000 --- a/source/gameengine/Ketsji/BL_Texture.cpp +++ /dev/null @@ -1,759 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/BL_Texture.cpp - * \ingroup ketsji - */ - -#include "GPU_glew.h" - -#include -#include -#include - -#include "BL_Material.h" -#include "BL_Texture.h" -#include "MT_assert.h" - -#include "DNA_texture_types.h" -#include "DNA_image_types.h" -#include "IMB_imbuf_types.h" -#include "BKE_image.h" -#include "BLI_blenlib.h" - -#include "RAS_ICanvas.h" -#include "RAS_Rect.h" - -#include "KX_GameObject.h" - -#define spit(x) std::cout << x << std::endl; - -#include "MEM_guardedalloc.h" -#include "GPU_draw.h" -#include "GPU_extensions.h" - -extern "C" { - // envmaps - #include "IMB_imbuf.h" - void my_envmap_split_ima(EnvMap *env, ImBuf *ibuf); - void my_free_envmapdata(EnvMap *env); -} - -// (n&(n-1)) zeros the least significant bit of n -static int is_power_of_2_i(int num) -{ - return ((num)&(num-1))==0; -} -static int power_of_2_min_i(int num) -{ - while (!is_power_of_2_i(num)) - num= num&(num-1); - return num; -} - -// Place holder for a full texture manager -class BL_TextureObject -{ -public: - unsigned int gl_texture; - void* ref_buffer; -}; - -typedef std::map BL_TextureMap; -static BL_TextureMap g_textureManager; -static GLint g_max_units = -1; - - -BL_Texture::BL_Texture() -: mTexture(0), - mOk(0), - mNeedsDeleted(0), - mType(0), - mUnit(0), - mEnvState(0) -{ - // -- -} - -BL_Texture::~BL_Texture() -{ - // -- -} - -void BL_Texture::DeleteTex() -{ - if ( mNeedsDeleted ) { - glDeleteTextures(1, (GLuint*)&mTexture); - mNeedsDeleted = 0; - mOk = 0; - } - - if (mEnvState) { - glDeleteLists((GLuint)mEnvState, 1); - mEnvState =0; - } - - if (mDisableState) { - glDeleteLists((GLuint)mDisableState, 1); - mDisableState =0; - } - g_textureManager.clear(); -} - - -bool BL_Texture::InitFromImage(int unit, Image *img, bool mipmap) -{ - - ImBuf *ibuf; - if (!img || img->ok==0) - { - mOk = false; - return mOk; - } - - ibuf= BKE_image_acquire_ibuf(img, NULL, NULL); - if (ibuf==NULL) - { - img->ok = 0; - mOk = false; - return mOk; - } - - mipmap = mipmap && GPU_get_mipmap(); - - mTexture = img->bindcode[TEXTARGET_TEXTURE_2D]; - mType = GL_TEXTURE_2D; - mUnit = unit; - - ActivateUnit(mUnit); - - if (mTexture != 0) { - glBindTexture(GL_TEXTURE_2D, mTexture ); - Validate(); - BKE_image_release_ibuf(img, ibuf, NULL); - return mOk; - } - - // look for an existing gl image - BL_TextureMap::iterator mapLook = g_textureManager.find(img->id.name); - if (mapLook != g_textureManager.end()) - { - if (mapLook->second.gl_texture != 0) - { - mTexture = mapLook->second.gl_texture; - glBindTexture(GL_TEXTURE_2D, mTexture); - mOk = IsValid(); - BKE_image_release_ibuf(img, ibuf, NULL); - return mOk; - } - } - - mNeedsDeleted = 1; - glGenTextures(1, (GLuint*)&mTexture); - -#ifdef WITH_DDS - if (ibuf->ftype == IMB_FTYPE_DDS) - InitGLCompressedTex(ibuf, mipmap); - else - InitGLTex(ibuf->rect, ibuf->x, ibuf->y, mipmap); -#else - InitGLTex(ibuf->rect, ibuf->x, ibuf->y, mipmap); -#endif - - // track created units - BL_TextureObject obj; - obj.gl_texture = mTexture; - obj.ref_buffer = img; - g_textureManager.insert(std::pair((char*)img->id.name, obj)); - - - glDisable(GL_TEXTURE_2D); - ActivateUnit(0); - Validate(); - - BKE_image_release_ibuf(img, ibuf, NULL); - - return mOk; -} - -void BL_Texture::InitGLTex(unsigned int *pix,int x,int y,bool mipmap) -{ - if (!GPU_full_non_power_of_two_support() && (!is_power_of_2_i(x) || !is_power_of_2_i(y)) ) { - InitNonPow2Tex(pix, x,y,mipmap); - return; - } - - glBindTexture(GL_TEXTURE_2D, mTexture ); - if ( mipmap ) { - int i; - ImBuf *ibuf; - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - - ibuf = IMB_allocFromBuffer(pix, NULL, x, y); - - IMB_makemipmap(ibuf, true); - - for (i = 0; i < ibuf->miptot; i++) { - ImBuf *mip = IMB_getmipmap(ibuf, i); - - glTexImage2D(GL_TEXTURE_2D, i, GL_RGBA, mip->x, mip->y, 0, GL_RGBA, GL_UNSIGNED_BYTE, mip->rect); - } - IMB_freeImBuf(ibuf); - } - else { - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, x, y, 0, GL_RGBA, GL_UNSIGNED_BYTE, pix ); - } - - if (GLEW_EXT_texture_filter_anisotropic) - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, GPU_get_anisotropic()); - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); -} - -void BL_Texture::InitGLCompressedTex(ImBuf *ibuf, bool mipmap) -{ -#ifndef WITH_DDS - // Fall back to uncompressed if DDS isn't enabled - InitGLTex(ibuf->rect, ibuf->x, ibuf->y, mipmap); - return; -#else - glBindTexture(GL_TEXTURE_2D, mTexture); - - if (GPU_upload_dxt_texture(ibuf) == 0) { - InitGLTex(ibuf->rect, ibuf->x, ibuf->y, mipmap); - return; - } -#endif -} - -void BL_Texture::InitNonPow2Tex(unsigned int *pix,int x,int y,bool mipmap) -{ - int nx= power_of_2_min_i(x); - int ny= power_of_2_min_i(y); - - ImBuf *ibuf = IMB_allocFromBuffer(pix, NULL, x, y); - IMB_scaleImBuf(ibuf, nx, ny); - - glBindTexture(GL_TEXTURE_2D, mTexture ); - - if ( mipmap ) { - int i; - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - - IMB_makemipmap(ibuf, true); - - for (i = 0; i < ibuf->miptot; i++) { - ImBuf *mip = IMB_getmipmap(ibuf, i); - - glTexImage2D(GL_TEXTURE_2D, i, GL_RGBA, mip->x, mip->y, 0, GL_RGBA, GL_UNSIGNED_BYTE, mip->rect); - } - } - else { - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, nx, ny, 0, GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect ); - } - - if (GLEW_EXT_texture_filter_anisotropic) - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, GPU_get_anisotropic()); - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - IMB_freeImBuf(ibuf); -} - - -bool BL_Texture::InitCubeMap(int unit, EnvMap *cubemap) -{ - if (!GLEW_ARB_texture_cube_map) - { - spit("cubemaps not supported"); - mOk = false; - return mOk; - } - else if (!cubemap || cubemap->ima->ok==0) - { - mOk = false; - return mOk; - } - - ImBuf *ibuf= BKE_image_acquire_ibuf(cubemap->ima, NULL, NULL); - if (ibuf==0) - { - cubemap->ima->ok = 0; - mOk = false; - return mOk; - } - - mNeedsDeleted = 1; - mType = GL_TEXTURE_CUBE_MAP_ARB; - mTexture = 0; - mUnit = unit; - - ActivateUnit(mUnit); - - BL_TextureMap::iterator mapLook = g_textureManager.find(cubemap->ima->id.name); - if (mapLook != g_textureManager.end()) - { - if (mapLook->second.gl_texture != 0 && mapLook->second.ref_buffer == cubemap->ima) - { - mTexture = mapLook->second.gl_texture; - glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, mTexture); - mOk = IsValid(); - BKE_image_release_ibuf(cubemap->ima, ibuf, NULL); - return mOk; - } - } - - - glGenTextures(1, (GLuint*)&mTexture); - glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, mTexture); - - - // track created units - BL_TextureObject obj; - obj.gl_texture = mTexture; - obj.ref_buffer = cubemap->ima; - g_textureManager.insert(std::pair((char*)cubemap->ima->id.name, obj)); - - - bool needs_split = false; - if (!cubemap->cube[0]) - { - needs_split = true; - spit ("Re-Generating texture buffer"); - } - - if (needs_split) - my_envmap_split_ima(cubemap, ibuf); - - - if (!is_power_of_2_i(cubemap->cube[0]->x) || !is_power_of_2_i(cubemap->cube[0]->y)) - { - spit("invalid envmap size please render with CubeRes @ power of two"); - - my_free_envmapdata(cubemap); - mOk = false; - BKE_image_release_ibuf(cubemap->ima, ibuf, NULL); - return mOk; - } - - -#define SetCubeMapFace(face, num) \ - glTexImage2D(face, 0,GL_RGBA, \ - cubemap->cube[num]->x, \ - cubemap->cube[num]->y, \ - 0, GL_RGBA, GL_UNSIGNED_BYTE, \ - cubemap->cube[num]->rect) - - SetCubeMapFace(GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB, 5); - SetCubeMapFace(GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB, 3); - SetCubeMapFace(GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB, 0); - SetCubeMapFace(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB, 1); - SetCubeMapFace(GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB, 2); - SetCubeMapFace(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB, 4); - - glTexParameteri( GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); - glTexParameteri( GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); - glTexParameteri( GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); - glTexParameteri( GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); - if (GLEW_VERSION_1_2) - glTexParameteri( GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE ); - - if (needs_split) - my_free_envmapdata(cubemap); - - - - glDisable(GL_TEXTURE_CUBE_MAP_ARB); - ActivateUnit(0); - - mOk = IsValid(); - - BKE_image_release_ibuf(cubemap->ima, ibuf, NULL); - - return mOk; -} - -bool BL_Texture::IsValid() -{ - return (mTexture!= 0)?glIsTexture(mTexture)!=0:false; -} - - -void BL_Texture::Validate() -{ - mOk = IsValid(); -} - - -bool BL_Texture::Ok() -{ - return (mTexture!= 0); -} - - -unsigned int BL_Texture::GetTextureType() const -{ - return mType; -} - -int BL_Texture::GetMaxUnits() -{ - if (g_max_units < 0) { - GLint unit = 0; - glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS_ARB, &unit); - g_max_units = (MAXTEX >= unit) ? unit : MAXTEX; - } - - return g_max_units; -} - -void BL_Texture::ActivateFirst() -{ - if (GLEW_ARB_multitexture) - glActiveTextureARB(GL_TEXTURE0_ARB); -} - -void BL_Texture::ActivateUnit(int unit) -{ - if (GLEW_ARB_multitexture) - if (unit <= MAXTEX) - glActiveTextureARB(GL_TEXTURE0_ARB+unit); -} - - -void BL_Texture::DisableUnit() -{ - if (GLEW_ARB_multitexture) - glActiveTextureARB(GL_TEXTURE0_ARB+mUnit); - - glMatrixMode(GL_TEXTURE); - glLoadIdentity(); - glMatrixMode(GL_MODELVIEW); - - if (GLEW_ARB_texture_cube_map && glIsEnabled(GL_TEXTURE_CUBE_MAP_ARB)) - glDisable(GL_TEXTURE_CUBE_MAP_ARB); - else - { - if (glIsEnabled(GL_TEXTURE_2D)) - glDisable(GL_TEXTURE_2D); - } - - glDisable(GL_TEXTURE_GEN_S); - glDisable(GL_TEXTURE_GEN_T); - glDisable(GL_TEXTURE_GEN_R); - glDisable(GL_TEXTURE_GEN_Q); - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ); -} - - -void BL_Texture::DisableAllTextures() -{ - for (int i=0; iflag[mUnit] &TEXALPHA ) { - combiner = GL_COMBINE_ALPHA_ARB; - source0 = GL_SOURCE0_ALPHA_ARB; - source1 = GL_SOURCE1_ALPHA_ARB; - source2 = GL_SOURCE2_ALPHA_ARB; - op0 = GL_OPERAND0_ALPHA_ARB; - op1 = GL_OPERAND1_ALPHA_ARB; - op2 = GL_OPERAND2_ALPHA_ARB; - blend_operand = GL_SRC_ALPHA; - blend_operand_prev = GL_SRC_ALPHA; - // invert - if (mat->flag[mUnit] &TEXNEG) { - blend_operand_prev = GL_ONE_MINUS_SRC_ALPHA; - blend_operand = GL_ONE_MINUS_SRC_ALPHA; - } - } - else { - if (mat->flag[mUnit] &TEXNEG) { - blend_operand_prev=GL_ONE_MINUS_SRC_COLOR; - blend_operand = GL_ONE_MINUS_SRC_COLOR; - } - } - bool using_alpha = false; - - if (mat->flag[mUnit] &USEALPHA) { - alphaOp = GL_ONE_MINUS_SRC_ALPHA; - using_alpha=true; - } - else if (mat->flag[mUnit] &USENEGALPHA) { - alphaOp = GL_SRC_ALPHA; - using_alpha = true; - } - - switch (mat->blend_mode[mUnit]) { - case BLEND_MIX: - { - // ------------------------------ - if (!using_alpha) { - GLfloat base_col[4]; - base_col[0] = base_col[1] = base_col[2] = 0.f; - base_col[3] = 1.f-mat->color_blend[mUnit]; - glTexEnvfv( GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR,base_col ); - } - glTexEnvf( GL_TEXTURE_ENV, combiner, GL_INTERPOLATE_ARB); - glTexEnvf( GL_TEXTURE_ENV, source0, GL_PREVIOUS_ARB); - glTexEnvf( GL_TEXTURE_ENV, op0, blend_operand_prev ); - glTexEnvf( GL_TEXTURE_ENV, source1, GL_TEXTURE ); - glTexEnvf( GL_TEXTURE_ENV, op1, blend_operand); - if (!using_alpha) - glTexEnvf( GL_TEXTURE_ENV, source2, GL_CONSTANT_ARB ); - else - glTexEnvf( GL_TEXTURE_ENV, source2, GL_TEXTURE ); - - glTexEnvf( GL_TEXTURE_ENV, op2, alphaOp); - }break; - case BLEND_MUL: - { - // ------------------------------ - glTexEnvf( GL_TEXTURE_ENV, combiner, GL_MODULATE); - glTexEnvf( GL_TEXTURE_ENV, source0, GL_PREVIOUS_ARB); - glTexEnvf( GL_TEXTURE_ENV, op0, blend_operand_prev); - glTexEnvf( GL_TEXTURE_ENV, source1, GL_TEXTURE ); - if (using_alpha) - glTexEnvf( GL_TEXTURE_ENV, op1, alphaOp); - else - glTexEnvf( GL_TEXTURE_ENV, op1, blend_operand); - }break; - case BLEND_ADD: - { - // ------------------------------ - glTexEnvf( GL_TEXTURE_ENV, combiner, GL_ADD_SIGNED_ARB); - glTexEnvf( GL_TEXTURE_ENV, source0, GL_PREVIOUS_ARB ); - glTexEnvf( GL_TEXTURE_ENV, op0, blend_operand_prev ); - glTexEnvf( GL_TEXTURE_ENV, source1, GL_TEXTURE ); - if (using_alpha) - glTexEnvf( GL_TEXTURE_ENV, op1, alphaOp); - else - glTexEnvf( GL_TEXTURE_ENV, op1, blend_operand); - }break; - case BLEND_SUB: - { - // ------------------------------ - glTexEnvf( GL_TEXTURE_ENV, combiner, GL_SUBTRACT_ARB); - glTexEnvf( GL_TEXTURE_ENV, source0, GL_PREVIOUS_ARB ); - glTexEnvf( GL_TEXTURE_ENV, op0, blend_operand_prev ); - glTexEnvf( GL_TEXTURE_ENV, source1, GL_TEXTURE ); - glTexEnvf( GL_TEXTURE_ENV, op1, blend_operand); - }break; - case BLEND_SCR: - { - // ------------------------------ - glTexEnvf( GL_TEXTURE_ENV, combiner, GL_ADD); - glTexEnvf( GL_TEXTURE_ENV, source0, GL_PREVIOUS_ARB ); - glTexEnvf( GL_TEXTURE_ENV, op0, blend_operand_prev ); - glTexEnvf( GL_TEXTURE_ENV, source1, GL_TEXTURE ); - if (using_alpha) - glTexEnvf( GL_TEXTURE_ENV, op1, alphaOp); - else - glTexEnvf( GL_TEXTURE_ENV, op1, blend_operand); - } break; - } - glTexEnvf( GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1.0f); - - glEndList(); -} - -int BL_Texture::GetPow2(int n) -{ - if (!is_power_of_2_i(n)) - n = power_of_2_min_i(n); - - return n; -} - -void BL_Texture::SplitEnvMap(EnvMap *map) -{ - if (!map || !map->ima || (map->ima && !map->ima->ok)) return; - ImBuf *ibuf= BKE_image_acquire_ibuf(map->ima, NULL, NULL); - if (ibuf) { - my_envmap_split_ima(map, ibuf); - BKE_image_release_ibuf(map->ima, ibuf, NULL); - } -} - -unsigned int BL_Texture::mDisableState = 0; - -extern "C" { - -void my_envmap_split_ima(EnvMap *env, ImBuf *ibuf) -{ - int dx, part; - - my_free_envmapdata(env); - - dx= ibuf->y; - dx/= 2; - if (3*dx != ibuf->x) { - printf("Incorrect envmap size\n"); - env->ok= 0; - env->ima->ok= 0; - } - else { - for (part=0; part<6; part++) { - env->cube[part] = IMB_allocImBuf(dx, dx, 24, IB_rect); - } - IMB_rectcpy(env->cube[0], ibuf, - 0, 0, 0, 0, dx, dx); - IMB_rectcpy(env->cube[1], ibuf, - 0, 0, dx, 0, dx, dx); - IMB_rectcpy(env->cube[2], ibuf, - 0, 0, 2*dx, 0, dx, dx); - IMB_rectcpy(env->cube[3], ibuf, - 0, 0, 0, dx, dx, dx); - IMB_rectcpy(env->cube[4], ibuf, - 0, 0, dx, dx, dx, dx); - IMB_rectcpy(env->cube[5], ibuf, - 0, 0, 2*dx, dx, dx, dx); - - env->ok= 2;// ENV_OSA - } -} - - -void my_free_envmapdata(EnvMap *env) -{ - unsigned int part; - - for (part=0; part<6; part++) { - ImBuf *ibuf= env->cube[part]; - if (ibuf) { - IMB_freeImBuf(ibuf); - env->cube[part] = NULL; - } - } - env->ok= 0; -} - - -} // extern C - diff --git a/source/gameengine/Ketsji/BL_Texture.h b/source/gameengine/Ketsji/BL_Texture.h deleted file mode 100644 index cd18ef93822..00000000000 --- a/source/gameengine/Ketsji/BL_Texture.h +++ /dev/null @@ -1,82 +0,0 @@ - -/** \file BL_Texture.h - * \ingroup ketsji - */ - -#ifndef __BL_TEXTURE_H__ -#define __BL_TEXTURE_H__ - -// #include -// #include - -#include "MT_Matrix4x4.h" -#include "KX_Camera.h" - -// -- -struct Image; -struct EnvMap; -class BL_Material; -class RAS_Rect; -class RAS_ICanvas; -//class RTData; - -#include "STR_String.h" - -class BL_Texture -{ -private: - unsigned int mTexture; // Bound texture unit data - bool mOk; // ... - bool mNeedsDeleted; // If generated - unsigned int mType; // enum TEXTURE_2D | CUBE_MAP - int mUnit; // Texture unit associated with mTexture - unsigned int mEnvState; // cache textureEnv - static unsigned int mDisableState; // speed up disabling calls - - void InitNonPow2Tex(unsigned int *p,int x,int y,bool mipmap ); - void InitGLTex(unsigned int *p,int x,int y,bool mipmap ); - void InitGLCompressedTex(struct ImBuf *p, bool mipmap); -public: - BL_Texture(); - ~BL_Texture( ); - - bool Ok(); - int GetUnit() {return mUnit;} - void SetUnit(int unit) {mUnit = unit;} - - unsigned int GetTextureType() const; - void DeleteTex(); - - bool InitFromImage(int unit, Image *img, bool mipmap); - bool InitCubeMap(int unit,EnvMap *cubemap ); - - bool IsValid(); - void Validate(); - - static void ActivateFirst(); - static void DisableAllTextures(); - static void ActivateUnit(int unit); - static int GetMaxUnits(); - static int GetPow2(int x); - static void SplitEnvMap(EnvMap *map); - - - void ActivateTexture(); - void SetMapping(int mode); - void DisableUnit(); - void setTexEnv(BL_Material *mat, bool modulate=false); - unsigned int swapTexture (unsigned int newTex) { - // swap texture codes - unsigned int tmp = mTexture; - mTexture = newTex; - // return original texture code - return tmp; - } - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_Texture") -#endif -}; - -#endif /* __BL_TEXTURE_H__ */ diff --git a/source/gameengine/Ketsji/CMakeLists.txt b/source/gameengine/Ketsji/CMakeLists.txt deleted file mode 100644 index cb7c0180f30..00000000000 --- a/source/gameengine/Ketsji/CMakeLists.txt +++ /dev/null @@ -1,265 +0,0 @@ -# ***** BEGIN GPL LICENSE BLOCK ***** -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; either version 2 -# of the License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software Foundation, -# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -# -# The Original Code is Copyright (C) 2006, Blender Foundation -# All rights reserved. -# -# The Original Code is: all of this file. -# -# Contributor(s): Jacques Beaurain. -# -# ***** END GPL LICENSE BLOCK ***** - -set(INC - . - KXNetwork - ../BlenderRoutines - ../Converter - ../Expressions - ../GameLogic - ../Network - ../Network/LoopBackNetwork - ../Physics/common - ../Rasterizer - ../Rasterizer/RAS_OpenGLRasterizer - ../SceneGraph - ../../blender - ../../blender/blenfont - ../../blender/blenkernel - ../../blender/blenlib - ../../blender/blenloader - ../../blender/gpu - ../../blender/imbuf - ../../blender/makesdna - ../../blender/makesrna - ../../blender/python - ../../blender/python/generic - ../../blender/python/mathutils - ../../../intern/container - ../../../intern/glew-mx - ../../../intern/guardedalloc - ../../../intern/string -) - -set(INC_SYS - ../../../intern/moto/include - ../../../extern/recastnavigation/Recast/Include - ../../../extern/recastnavigation/Detour/Include - ${PTHREADS_INCLUDE_DIRS} - ${GLEW_INCLUDE_PATH} - ${BOOST_INCLUDE_DIR} -) - -set(SRC - BL_Action.cpp - BL_ActionManager.cpp - BL_BlenderShader.cpp - BL_Material.cpp - BL_Shader.cpp - BL_Texture.cpp - KX_ArmatureSensor.cpp - KX_BlenderMaterial.cpp - KX_Camera.cpp - KX_CameraActuator.cpp - KX_CameraIpoSGController.cpp - KX_CharacterWrapper.cpp - KX_ConstraintActuator.cpp - KX_ConstraintWrapper.cpp - KX_Dome.cpp - KX_EmptyObject.cpp - KX_FontObject.cpp - KX_GameActuator.cpp - KX_GameObject.cpp - KX_IpoConvert.cpp - KX_IPO_SGController.cpp - KX_KetsjiEngine.cpp - KX_Light.cpp - KX_LightIpoSGController.cpp - KX_MaterialIpoController.cpp - KX_MeshProxy.cpp - KX_MotionState.cpp - KX_MouseActuator.cpp - KX_MouseFocusSensor.cpp - KX_NavMeshObject.cpp - KX_NearSensor.cpp - KX_ObColorIpoSGController.cpp - KX_ObjectActuator.cpp - KX_ObstacleSimulation.cpp - KX_OrientationInterpolator.cpp - KX_ParentActuator.cpp - KX_PolyProxy.cpp - KX_PositionInterpolator.cpp - KX_PyConstraintBinding.cpp - KX_PyMath.cpp - KX_PythonInit.cpp - KX_PythonInitTypes.cpp - KX_PythonMain.cpp - KX_RadarSensor.cpp - KX_RayCast.cpp - KX_RayEventManager.cpp - KX_RaySensor.cpp - KX_SCA_AddObjectActuator.cpp - KX_SCA_DynamicActuator.cpp - KX_SCA_EndObjectActuator.cpp - KX_SCA_ReplaceMeshActuator.cpp - KX_SG_BoneParentNodeRelationship.cpp - KX_SG_NodeRelationships.cpp - KX_ScalarInterpolator.cpp - KX_ScalingInterpolator.cpp - KX_Scene.cpp - KX_SceneActuator.cpp - KX_SoundActuator.cpp - KX_StateActuator.cpp - KX_SteeringActuator.cpp - KX_TimeCategoryLogger.cpp - KX_TimeLogger.cpp - KX_TouchEventManager.cpp - KX_TouchSensor.cpp - KX_TrackToActuator.cpp - KX_VehicleWrapper.cpp - KX_VertexProxy.cpp - KX_VisibilityActuator.cpp - KX_WorldInfo.cpp - KX_WorldIpoController.cpp - - BL_Action.h - BL_ActionManager.h - BL_BlenderShader.h - BL_Material.h - BL_Shader.h - BL_Texture.h - KX_ArmatureSensor.h - KX_BlenderMaterial.h - KX_Camera.h - KX_CameraActuator.h - KX_CameraIpoSGController.h - KX_CharacterWrapper.h - KX_ClientObjectInfo.h - KX_ConstraintActuator.h - KX_ConstraintWrapper.h - KX_Dome.h - KX_EmptyObject.h - KX_FontObject.h - KX_GameActuator.h - KX_GameObject.h - KX_IInterpolator.h - KX_IpoConvert.h - KX_IPOTransform.h - KX_IPO_SGController.h - KX_IScalarInterpolator.h - KX_ISceneConverter.h - KX_ISystem.h - KX_KetsjiEngine.h - KX_Light.h - KX_LightIpoSGController.h - KX_MaterialIpoController.h - KX_MeshProxy.h - KX_MotionState.h - KX_MouseActuator.h - KX_MouseFocusSensor.h - KX_NavMeshObject.h - KX_NearSensor.h - KX_ObColorIpoSGController.h - KX_ObjectActuator.h - KX_ObstacleSimulation.h - KX_OrientationInterpolator.h - KX_ParentActuator.h - KX_PhysicsEngineEnums.h - KX_PolyProxy.h - KX_PositionInterpolator.h - KX_PyConstraintBinding.h - KX_PyMath.h - KX_PythonInit.h - KX_PythonInitTypes.h - KX_PythonMain.h - KX_RadarSensor.h - KX_RayCast.h - KX_RayEventManager.h - KX_RaySensor.h - KX_SCA_AddObjectActuator.h - KX_SCA_DynamicActuator.h - KX_SCA_EndObjectActuator.h - KX_SCA_ReplaceMeshActuator.h - KX_SG_BoneParentNodeRelationship.h - KX_SG_NodeRelationships.h - KX_ScalarInterpolator.h - KX_ScalingInterpolator.h - KX_Scene.h - KX_SceneActuator.h - KX_SoundActuator.h - KX_StateActuator.h - KX_SteeringActuator.h - KX_TimeCategoryLogger.h - KX_TimeLogger.h - KX_TouchEventManager.h - KX_TouchSensor.h - KX_TrackToActuator.h - KX_VehicleWrapper.h - KX_VertexProxy.h - KX_VisibilityActuator.h - KX_WorldInfo.h - KX_WorldIpoController.h - - # orphan headers (not apart of a library) - ../Physics/common/PHY_DynamicTypes.h - ../Physics/common/PHY_ICharacter.h - ../Physics/common/PHY_IController.h - ../Physics/common/PHY_IGraphicController.h - ../Physics/common/PHY_IMotionState.h - ../Physics/common/PHY_IPhysicsController.h - ../Physics/common/PHY_IPhysicsEnvironment.h - ../Physics/common/PHY_IVehicle.h - ../Physics/common/PHY_Pro.h - -) - -add_definitions(${GL_DEFINITIONS}) - -if(WITH_IMAGE_DDS) - add_definitions(-DWITH_DDS) -endif() - -if(WITH_SDL) - list(APPEND INC_SYS - ${SDL_INCLUDE_DIR} - ) - add_definitions(-DWITH_SDL) -endif() - -if(WITH_CODEC_FFMPEG) - add_definitions(-DWITH_FFMPEG) -endif() - -if(WITH_AUDASPACE) - add_definitions(-DWITH_AUDASPACE) - - list(APPEND INC_SYS - ${AUDASPACE_C_INCLUDE_DIRS} - ${AUDASPACE_PY_INCLUDE_DIRS} - ) -endif() - -if(WITH_BULLET) - list(APPEND INC - ../Physics/Bullet - ) - list(APPEND INC_SYS - ${BULLET_INCLUDE_DIRS} - ) - add_definitions(-DWITH_BULLET) -endif() - -blender_add_lib(ge_logic_ketsji "${SRC}" "${INC}" "${INC_SYS}") diff --git a/source/gameengine/Ketsji/KXNetwork/CMakeLists.txt b/source/gameengine/Ketsji/KXNetwork/CMakeLists.txt deleted file mode 100644 index cfc6ded4e65..00000000000 --- a/source/gameengine/Ketsji/KXNetwork/CMakeLists.txt +++ /dev/null @@ -1,56 +0,0 @@ -# ***** BEGIN GPL LICENSE BLOCK ***** -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; either version 2 -# of the License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software Foundation, -# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -# -# The Original Code is Copyright (C) 2006, Blender Foundation -# All rights reserved. -# -# The Original Code is: all of this file. -# -# Contributor(s): Jacques Beaurain. -# -# ***** END GPL LICENSE BLOCK ***** - -set(INC - . - .. - ../../Expressions - ../../GameLogic - ../../Network - ../../SceneGraph - ../../../blender/blenlib - ../../../../intern/container - ../../../../intern/string -) - -set(INC_SYS - ../../../../intern/moto/include -) - -set(SRC - KX_NetworkEventManager.cpp - KX_NetworkMessageActuator.cpp - KX_NetworkMessageSensor.cpp - KX_NetworkObjectActuator.cpp - KX_NetworkObjectSensor.cpp - - KX_NetworkEventManager.h - KX_NetworkMessageActuator.h - KX_NetworkMessageSensor.h - KX_NetworkObjectActuator.h - KX_NetworkObjectSensor.h -) - -blender_add_lib(ge_logic_network "${SRC}" "${INC}" "${INC_SYS}") diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.cpp b/source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.cpp deleted file mode 100644 index 8c6392ee825..00000000000 --- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.cpp +++ /dev/null @@ -1,77 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - * Ketsji Logic Extension: Network Event Manager generic implementation - */ - -/** \file gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.cpp - * \ingroup ketsjinet - */ - - -// Ketsji specific sensor part -#include "SCA_ISensor.h" - -// Ketsji specific network part -#include "KX_NetworkEventManager.h" - -// Network module specific -#include "NG_NetworkDeviceInterface.h" -#include "NG_NetworkMessage.h" -#include "NG_NetworkObject.h" - -KX_NetworkEventManager::KX_NetworkEventManager(class SCA_LogicManager* -logicmgr, class NG_NetworkDeviceInterface *ndi) : -SCA_EventManager(logicmgr, NETWORK_EVENTMGR), m_ndi(ndi) -{ - //printf("KX_NetworkEventManager constructor\n"); -} - -KX_NetworkEventManager::~KX_NetworkEventManager() -{ - //printf("KX_NetworkEventManager destructor\n"); -} - -void KX_NetworkEventManager::NextFrame() -{ -// printf("KX_NetworkEventManager::proceed %.2f - %.2f\n", curtime, deltatime); - // each frame, the logicmanager will call the network - // eventmanager to look for network events, and process it's - // 'network' sensors - SG_DList::iterator it(m_sensors); - for (it.begin();!it.end();++it) - { -// printf("KX_NetworkEventManager::proceed sensor %.2f\n", curtime); - // process queue - (*it)->Activate(m_logicmgr); - } - - // now a list of triggerer sensors has been built -} - -void KX_NetworkEventManager::EndFrame() -{ -} - diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.h b/source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.h deleted file mode 100644 index 9a13b6d53e2..00000000000 --- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkEventManager.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_NetworkEventManager.h - * \ingroup ketsjinet - * \brief Ketsji Logic Extension: Network Event Manager class - */ - -#ifndef __KX_NETWORKEVENTMANAGER_H__ -#define __KX_NETWORKEVENTMANAGER_H__ - -#include "SCA_EventManager.h" - -class KX_NetworkEventManager : public SCA_EventManager -{ - class NG_NetworkDeviceInterface* m_ndi; - -public: - KX_NetworkEventManager(class SCA_LogicManager* logicmgr, - class NG_NetworkDeviceInterface *ndi); - virtual ~KX_NetworkEventManager (); - - virtual void NextFrame(); - virtual void EndFrame(); - - SCA_LogicManager* GetLogicManager() { return m_logicmgr; } - class NG_NetworkDeviceInterface* GetNetworkDevice() { - return m_ndi; } -}; - -#endif /* __KX_NETWORKEVENTMANAGER_H__ */ diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.cpp b/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.cpp deleted file mode 100644 index 2741907bfe6..00000000000 --- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.cpp +++ /dev/null @@ -1,139 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - * Ketsji Logic Extension: Network Message Actuator generic implementation - */ - -/** \file gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.cpp - * \ingroup ketsjinet - */ - - -#include - -#include "NG_NetworkScene.h" -#include "KX_NetworkMessageActuator.h" - -KX_NetworkMessageActuator::KX_NetworkMessageActuator( - SCA_IObject* gameobj, // the actuator controlling object - NG_NetworkScene* networkscene, // needed for replication - const STR_String &toPropName, - const STR_String &subject, - int bodyType, - const STR_String &body) : - SCA_IActuator(gameobj, KX_ACT_MESSAGE), - m_networkscene(networkscene), - m_toPropName(toPropName), - m_subject(subject), - m_bPropBody(bodyType), - m_body(body) -{ -} - -KX_NetworkMessageActuator::~KX_NetworkMessageActuator() -{ -} - -// returns true if the actuators needs to be running over several frames -bool KX_NetworkMessageActuator::Update() -{ - //printf("update messageactuator\n"); - bool bNegativeEvent = IsNegativeEvent(); - RemoveAllEvents(); - - if (bNegativeEvent) { - return false; // do nothing on negative events - //printf("messageactuator false event\n"); - } - //printf("messageactuator true event\n"); - - if (m_bPropBody) // ACT_MESG_PROP in DNA_actuator_types.h - { - m_networkscene->SendMessage( - m_toPropName, - GetParent()->GetName(), - m_subject, - GetParent()->GetPropertyText(m_body)); - } else - { - m_networkscene->SendMessage( - m_toPropName, - GetParent()->GetName(), - m_subject, - m_body); - } - return false; -} - -CValue* KX_NetworkMessageActuator::GetReplica() -{ - KX_NetworkMessageActuator* replica = new KX_NetworkMessageActuator(*this); - replica->ProcessReplica(); - - return replica; -} - -#ifdef WITH_PYTHON - -/* -------------------------------------------------------------------- */ -/* Python interface --------------------------------------------------- */ -/* -------------------------------------------------------------------- */ - -/* Integration hooks -------------------------------------------------- */ -PyTypeObject KX_NetworkMessageActuator::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_NetworkMessageActuator", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &SCA_IActuator::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_NetworkMessageActuator::Methods[] = { - {NULL,NULL} // Sentinel -}; - -PyAttributeDef KX_NetworkMessageActuator::Attributes[] = { - KX_PYATTRIBUTE_STRING_RW("propName", 0, MAX_PROP_NAME, false, KX_NetworkMessageActuator, m_toPropName), - KX_PYATTRIBUTE_STRING_RW("subject", 0, 100, false, KX_NetworkMessageActuator, m_subject), - KX_PYATTRIBUTE_BOOL_RW("usePropBody", KX_NetworkMessageActuator, m_bPropBody), - KX_PYATTRIBUTE_STRING_RW("body", 0, 16384, false, KX_NetworkMessageActuator, m_body), - { NULL } //Sentinel -}; - -#endif // WITH_PYTHON diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.h b/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.h deleted file mode 100644 index 325a7be9bd7..00000000000 --- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageActuator.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_NetworkMessageActuator.h - * \ingroup ketsjinet - * \brief Ketsji Logic Extension: Network Message Actuator class - */ - -#ifndef __KX_NETWORKMESSAGEACTUATOR_H__ -#define __KX_NETWORKMESSAGEACTUATOR_H__ - -#include "STR_String.h" -#include "SCA_IActuator.h" -#include "NG_NetworkMessage.h" - -class KX_NetworkMessageActuator : public SCA_IActuator -{ - Py_Header - bool m_lastEvent; - class NG_NetworkScene* m_networkscene; // needed for replication - STR_String m_toPropName; - STR_String m_subject; - bool m_bPropBody; - STR_String m_body; -public: - KX_NetworkMessageActuator( - SCA_IObject* gameobj, - NG_NetworkScene* networkscene, - const STR_String &toPropName, - const STR_String &subject, - int bodyType, - const STR_String &body); - virtual ~KX_NetworkMessageActuator(); - - virtual bool Update(); - virtual CValue* GetReplica(); - virtual void Replace_NetworkScene(NG_NetworkScene *val) - { - m_networkscene= val; - }; - - /* ------------------------------------------------------------ */ - /* Python interface ------------------------------------------- */ - /* ------------------------------------------------------------ */ - -}; - -#endif /* __KX_NETWORKMESSAGEACTUATOR_H__ */ diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.cpp b/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.cpp deleted file mode 100644 index 1fadd9382e0..00000000000 --- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.cpp +++ /dev/null @@ -1,224 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - * Ketsji Logic Extension: Network Message Sensor generic implementation - */ - -/** \file gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.cpp - * \ingroup ketsjinet - */ - - -#include - -#include "KX_NetworkMessageSensor.h" -#include "KX_NetworkEventManager.h" -#include "NG_NetworkMessage.h" -#include "NG_NetworkScene.h" -#include "NG_NetworkObject.h" -#include "SCA_IObject.h" -#include "EXP_InputParser.h" -#include "EXP_ListValue.h" -#include "EXP_StringValue.h" - -#ifdef NAN_NET_DEBUG - #include -#endif - -KX_NetworkMessageSensor::KX_NetworkMessageSensor( - class KX_NetworkEventManager* eventmgr, // our eventmanager - class NG_NetworkScene *NetworkScene, // our scene - SCA_IObject* gameobj, // the sensor controlling object - const STR_String &subject - ) : - SCA_ISensor(gameobj,eventmgr), - m_NetworkScene(NetworkScene), - m_subject(subject), - m_frame_message_count (0), - m_BodyList(NULL), - m_SubjectList(NULL) -{ - Init(); -} - -void KX_NetworkMessageSensor::Init() -{ - m_IsUp = false; -} - -KX_NetworkMessageSensor::~KX_NetworkMessageSensor() -{ -} - -CValue* KX_NetworkMessageSensor::GetReplica() -{ - // This is the standard sensor implementation of GetReplica - // There may be more network message sensor specific stuff to do here. - CValue* replica = new KX_NetworkMessageSensor(*this); - - if (replica == NULL) return NULL; - replica->ProcessReplica(); - - return replica; -} - -// Return true only for flank (UP and DOWN) -bool KX_NetworkMessageSensor::Evaluate() -{ - bool result = false; - bool WasUp = m_IsUp; - - m_IsUp = false; - - if (m_BodyList) { - m_BodyList->Release(); - m_BodyList = NULL; - } - - if (m_SubjectList) { - m_SubjectList->Release(); - m_SubjectList = NULL; - } - - STR_String& toname=GetParent()->GetName(); - STR_String& subject = this->m_subject; - - vector messages = - m_NetworkScene->FindMessages(toname,"",subject,true); - - m_frame_message_count = messages.size(); - - if (!messages.empty()) { -#ifdef NAN_NET_DEBUG - printf("KX_NetworkMessageSensor found one or more messages\n"); -#endif - m_IsUp = true; - m_BodyList = new CListValue(); - m_SubjectList = new CListValue(); - } - - vector::iterator mesit; - for (mesit=messages.begin();mesit!=messages.end();mesit++) - { - // save the body - const STR_String& body = (*mesit)->GetMessageText(); - // save the subject - const STR_String& messub = (*mesit)->GetSubject(); -#ifdef NAN_NET_DEBUG - if (body) { - cout << "body [" << body << "]\n"; - } -#endif - m_BodyList->Add(new CStringValue(body,"body")); - // Store Subject - m_SubjectList->Add(new CStringValue(messub,"subject")); - - // free the message - (*mesit)->Release(); - } - messages.clear(); - - result = (WasUp != m_IsUp); - - // Return always true if a message was received otherwise we can loose messages - if (m_IsUp) - return true; - // Is it useful to return also true when the first frame without a message?? - // This will cause a fast on/off cycle that seems useless! - return result; -} - -// return true for being up (no flank needed) -bool KX_NetworkMessageSensor::IsPositiveTrigger() -{ -// printf("KX_NetworkMessageSensor IsPositiveTrigger\n"); - //attempt to fix [ #3809 ] IPO Actuator does not work with some Sensors - //a better solution is to properly introduce separate Edge and Level triggering concept - - return m_IsUp; -} - -#ifdef WITH_PYTHON - -/* --------------------------------------------------------------------- */ -/* Python interface ---------------------------------------------------- */ -/* --------------------------------------------------------------------- */ - -/* Integration hooks --------------------------------------------------- */ -PyTypeObject KX_NetworkMessageSensor::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_NetworkMessageSensor", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &SCA_ISensor::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_NetworkMessageSensor::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_NetworkMessageSensor::Attributes[] = { - KX_PYATTRIBUTE_STRING_RW("subject", 0, 100, false, KX_NetworkMessageSensor, m_subject), - KX_PYATTRIBUTE_INT_RO("frameMessageCount", KX_NetworkMessageSensor, m_frame_message_count), - KX_PYATTRIBUTE_RO_FUNCTION("bodies", KX_NetworkMessageSensor, pyattr_get_bodies), - KX_PYATTRIBUTE_RO_FUNCTION("subjects", KX_NetworkMessageSensor, pyattr_get_subjects), - { NULL } //Sentinel -}; - -PyObject *KX_NetworkMessageSensor::pyattr_get_bodies(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_NetworkMessageSensor *self = static_cast(self_v); - if (self->m_BodyList) { - return self->m_BodyList->GetProxy(); - } else { - return (new CListValue())->NewProxy(true); - } -} - -PyObject *KX_NetworkMessageSensor::pyattr_get_subjects(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_NetworkMessageSensor *self = static_cast(self_v); - if (self->m_SubjectList) { - return self->m_SubjectList->GetProxy(); - } else { - return (new CListValue())->NewProxy(true); - } -} - -#endif // WITH_PYTHON diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.h b/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.h deleted file mode 100644 index a1f0692b7b3..00000000000 --- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkMessageSensor.h +++ /dev/null @@ -1,90 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_NetworkMessageSensor.h - * \ingroup ketsjinet - * \brief Ketsji Logic Extension: Network Message Sensor class - */ -#ifndef __KX_NETWORKMESSAGESENSOR_H__ -#define __KX_NETWORKMESSAGESENSOR_H__ - -#include "SCA_ISensor.h" - -class KX_NetworkEventManager; -class NG_NetworkScene; - -class KX_NetworkMessageSensor : public SCA_ISensor -{ - // note: Py_Header MUST BE the first listed here - Py_Header - NG_NetworkScene *m_NetworkScene; - - // The subject we filter on. - STR_String m_subject; - - // The number of messages caught since the last frame. - int m_frame_message_count; - - bool m_IsUp; - - class CListValue* m_BodyList; - class CListValue* m_SubjectList; -public: - KX_NetworkMessageSensor( - KX_NetworkEventManager* eventmgr, // our eventmanager - NG_NetworkScene *NetworkScene, // our scene - SCA_IObject* gameobj, // the sensor controlling object - const STR_String &subject - ); - virtual ~KX_NetworkMessageSensor(); - - virtual CValue* GetReplica(); - virtual bool Evaluate(); - virtual bool IsPositiveTrigger(); - virtual void Init(); - void EndFrame(); - - virtual void Replace_NetworkScene(NG_NetworkScene *val) - { - m_NetworkScene= val; - }; - -#ifdef WITH_PYTHON - - /* ------------------------------------------------------------- */ - /* Python interface -------------------------------------------- */ - /* ------------------------------------------------------------- */ - - /* attributes */ - static PyObject* pyattr_get_bodies(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_subjects(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - -#endif /* WITH_PYTHON */ - -}; - -#endif /* __KX_NETWORKMESSAGESENSOR_H__ */ diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectActuator.cpp b/source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectActuator.cpp deleted file mode 100644 index b8032f8e037..00000000000 --- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectActuator.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KXNetwork/KX_NetworkObjectActuator.cpp - * \ingroup ketsjinet - */ - diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectActuator.h b/source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectActuator.h deleted file mode 100644 index 36e0e6c39ec..00000000000 --- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectActuator.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KXNetwork/KX_NetworkObjectActuator.h - * \ingroup ketsjinet - */ - - diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectSensor.cpp b/source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectSensor.cpp deleted file mode 100644 index bc6da2e4143..00000000000 --- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectSensor.cpp +++ /dev/null @@ -1,32 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KXNetwork/KX_NetworkObjectSensor.cpp - * \ingroup ketsjinet - */ - - diff --git a/source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectSensor.h b/source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectSensor.h deleted file mode 100644 index 00aa53feb27..00000000000 --- a/source/gameengine/Ketsji/KXNetwork/KX_NetworkObjectSensor.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KXNetwork/KX_NetworkObjectSensor.h - * \ingroup ketsjinet - */ - - diff --git a/source/gameengine/Ketsji/KX_ArmatureSensor.cpp b/source/gameengine/Ketsji/KX_ArmatureSensor.cpp deleted file mode 100644 index c111a4de0eb..00000000000 --- a/source/gameengine/Ketsji/KX_ArmatureSensor.cpp +++ /dev/null @@ -1,208 +0,0 @@ -/* - * Armature sensor - * - * - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_ArmatureSensor.cpp - * \ingroup ketsji - */ - - -#include "DNA_action_types.h" -#include "DNA_constraint_types.h" -#include "BKE_constraint.h" -#include "DNA_sensor_types.h" - -#include "BL_ArmatureObject.h" -#include "KX_ArmatureSensor.h" -#include "SCA_EventManager.h" -#include "SCA_LogicManager.h" - -KX_ArmatureSensor::KX_ArmatureSensor(class SCA_EventManager* eventmgr, - SCA_IObject* gameobj, - const char *posechannel, - const char *constraintname, - int type, - float value) - : SCA_ISensor(gameobj,eventmgr), - m_constraint(NULL), - m_posechannel(posechannel), - m_constraintname(constraintname), - m_type(type), - m_value(value) -{ - FindConstraint(); -} - -void KX_ArmatureSensor::Init() -{ - m_lastresult = m_invert?true:false; - m_result = false; - m_reset = true; -} - -void KX_ArmatureSensor::FindConstraint() -{ - m_constraint = NULL; - - if (m_gameobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE) { - BL_ArmatureObject* armobj = (BL_ArmatureObject*)m_gameobj; - // get the persistent pose structure - bPose* pose = armobj->GetOrigPose(); - bPoseChannel* pchan; - bConstraint* pcon; - // and locate the constraint - for (pchan = (bPoseChannel*)pose->chanbase.first; pchan; pchan=(bPoseChannel*)pchan->next) { - if (!strcmp(pchan->name, m_posechannel)) { - // now locate the constraint - for (pcon = (bConstraint *)pchan->constraints.first; pcon; pcon = (bConstraint *)pcon->next) { - if (!strcmp(pcon->name, m_constraintname)) { - if (pcon->flag & CONSTRAINT_DISABLE) - /* this constraint is not valid, can't use it */ - break; - m_constraint = pcon; - break; - } - } - break; - } - } - } -} - - -CValue* KX_ArmatureSensor::GetReplica() -{ - KX_ArmatureSensor* replica = new KX_ArmatureSensor(*this); - // m_range_expr must be recalculated on replica! - replica->ProcessReplica(); - return replica; -} - -void KX_ArmatureSensor::ReParent(SCA_IObject* parent) -{ - SCA_ISensor::ReParent(parent); - // must remap the constraint - FindConstraint(); -} - -bool KX_ArmatureSensor::IsPositiveTrigger() -{ - return (m_invert) ? !m_result : m_result; -} - - -KX_ArmatureSensor::~KX_ArmatureSensor() -{ -} - -bool KX_ArmatureSensor::Evaluate() -{ - bool reset = m_reset && m_level; - - m_reset = false; - if (!m_constraint) - return false; - switch (m_type) { - case SENS_ARM_STATE_CHANGED: - m_result = !(m_constraint->flag & CONSTRAINT_OFF); - break; - case SENS_ARM_LIN_ERROR_BELOW: - m_result = (m_constraint->lin_error < m_value); - break; - case SENS_ARM_LIN_ERROR_ABOVE: - m_result = (m_constraint->lin_error > m_value); - break; - case SENS_ARM_ROT_ERROR_BELOW: - m_result = (m_constraint->rot_error < m_value); - break; - case SENS_ARM_ROT_ERROR_ABOVE: - m_result = (m_constraint->rot_error > m_value); - break; - } - if (m_lastresult!=m_result) - { - m_lastresult = m_result; - return true; - } - return (reset) ? true : false; -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject KX_ArmatureSensor::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_ArmatureSensor", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &SCA_ISensor::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_ArmatureSensor::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_ArmatureSensor::Attributes[] = { - KX_PYATTRIBUTE_RO_FUNCTION("constraint", KX_ArmatureSensor, pyattr_get_constraint), - KX_PYATTRIBUTE_FLOAT_RW("value",-FLT_MAX,FLT_MAX,KX_ArmatureSensor,m_value), - KX_PYATTRIBUTE_INT_RW("type",0,SENS_ARM_MAXTYPE,false,KX_ArmatureSensor,m_type), - { NULL } //Sentinel -}; - -PyObject *KX_ArmatureSensor::pyattr_get_constraint(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_ArmatureSensor* sensor = static_cast(self); - if (sensor->m_gameobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE) { - BL_ArmatureObject* armobj = (BL_ArmatureObject*)sensor->m_gameobj; - BL_ArmatureConstraint* constraint = armobj->GetConstraint(sensor->m_posechannel, sensor->m_constraintname); - if (constraint) - return constraint->GetProxy(); - } - Py_RETURN_NONE; -} - -#endif // WITH_PYTHON diff --git a/source/gameengine/Ketsji/KX_ArmatureSensor.h b/source/gameengine/Ketsji/KX_ArmatureSensor.h deleted file mode 100644 index b3ea905d198..00000000000 --- a/source/gameengine/Ketsji/KX_ArmatureSensor.h +++ /dev/null @@ -1,90 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_ArmatureSensor.h - * \ingroup ketsji - * \brief Property sensor - */ - -#ifndef __KX_ARMATURESENSOR_H__ -#define __KX_ARMATURESENSOR_H__ - -struct bConstraint; - -#include "SCA_ISensor.h" -#include "DNA_sensor_types.h" - -class KX_ArmatureSensor : public SCA_ISensor -{ - Py_Header - //class CExpression* m_rightexpr; - -protected: - -public: - KX_ArmatureSensor(class SCA_EventManager* eventmgr, - SCA_IObject* gameobj, - const char *posechannel, - const char *constraintname, - int type, - float value); - - /** - * For property sensor, it is used to release the pre-calculated expression - * so that self references are removed before the sensor itself is released - */ - virtual ~KX_ArmatureSensor(); - virtual CValue* GetReplica(); - virtual void ReParent(SCA_IObject* parent); - virtual void Init(); - virtual bool Evaluate(); - virtual bool IsPositiveTrigger(); - - // identify the constraint that this actuator controls - void FindConstraint(); - -#ifdef WITH_PYTHON - - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - static PyObject *pyattr_get_constraint(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - -#endif /* WITH_PYTHON */ - -private: - struct bConstraint* m_constraint; - STR_String m_posechannel; - STR_String m_constraintname; - int m_type; - float m_value; - bool m_result; - bool m_lastresult; -}; - -#endif - diff --git a/source/gameengine/Ketsji/KX_BlenderMaterial.cpp b/source/gameengine/Ketsji/KX_BlenderMaterial.cpp deleted file mode 100644 index 98d27ef3685..00000000000 --- a/source/gameengine/Ketsji/KX_BlenderMaterial.cpp +++ /dev/null @@ -1,1334 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_BlenderMaterial.cpp - * \ingroup ketsji - */ - -#include "GPU_glew.h" - -#include "KX_BlenderMaterial.h" -#include "BL_Material.h" -#include "KX_Scene.h" -#include "KX_Light.h" -#include "KX_GameObject.h" -#include "KX_MeshProxy.h" -#include "KX_PyMath.h" - -#include "MT_Vector3.h" -#include "MT_Vector4.h" -#include "MT_Matrix4x4.h" - -#include "RAS_BucketManager.h" -#include "RAS_MeshObject.h" -#include "RAS_IRasterizer.h" - -#include "GPU_draw.h" - -#include "STR_HashedString.h" - -// ------------------------------------ -#include "DNA_object_types.h" -#include "DNA_material_types.h" -#include "DNA_image_types.h" -#include "DNA_meshdata_types.h" -#include "BKE_mesh.h" -// ------------------------------------ -#include "BLI_utildefines.h" -#include "BLI_math.h" - -#define spit(x) std::cout << x << std::endl; - -BL_Shader *KX_BlenderMaterial::mLastShader = NULL; -BL_BlenderShader *KX_BlenderMaterial::mLastBlenderShader = NULL; - -//static PyObject *gTextureDict = 0; - -KX_BlenderMaterial::KX_BlenderMaterial() -: PyObjectPlus(), - RAS_IPolyMaterial(), - mMaterial(NULL), - mShader(0), - mBlenderShader(0), - mScene(NULL), - mUserDefBlend(0), - mModified(0), - mConstructed(false), - mPass(0) -{ -} - -void KX_BlenderMaterial::Initialize( - KX_Scene *scene, - BL_Material *data, - GameSettings *game, - int lightlayer) -{ - RAS_IPolyMaterial::Initialize( - data->texname[0], - data->matname, - data->materialindex, - data->tile, - data->tilexrep[0], - data->tileyrep[0], - data->alphablend, - ((data->ras_mode &ALPHA)!=0), - ((data->ras_mode &ZSORT)!=0), - ((data->ras_mode &USE_LIGHT)!=0), - ((data->ras_mode &TEX)), - game - ); - Material *ma = data->material; - - // Save material data to restore on exit - mSavedData.r = ma->r; - mSavedData.g = ma->g; - mSavedData.b = ma->b; - mSavedData.a = ma->alpha; - mSavedData.specr = ma->specr; - mSavedData.specg = ma->specg; - mSavedData.specb = ma->specb; - mSavedData.spec = ma->spec; - mSavedData.ref = ma->ref; - mSavedData.hardness = ma->har; - mSavedData.emit = ma->emit; - - mMaterial = data; - mShader = 0; - mBlenderShader = 0; - mScene = scene; - mUserDefBlend = 0; - mModified = 0; - mConstructed = false; - mPass = 0; - mLightLayer = lightlayer; - // -------------------------------- - // RAS_IPolyMaterial variables... - m_flag |= RAS_BLENDERMAT; - m_flag |= (mMaterial->IdMode>=ONETEX)? RAS_MULTITEX: 0; - m_flag |= ((mMaterial->ras_mode & USE_LIGHT)!=0)? RAS_MULTILIGHT: 0; - m_flag |= (mMaterial->glslmat)? RAS_BLENDERGLSL: 0; - m_flag |= ((mMaterial->ras_mode & CAST_SHADOW)!=0)? RAS_CASTSHADOW: 0; - m_flag |= ((mMaterial->ras_mode & ONLY_SHADOW)!=0)? RAS_ONLYSHADOW: 0; - - // test the sum of the various modes for equality - // so we can ether accept or reject this material - // as being equal, this is rather important to - // prevent material bleeding - for (int i=0; iflag[i] + mMaterial->blend_mode[i]); - } - m_multimode += mMaterial->IdMode+ (mMaterial->ras_mode & ~(USE_LIGHT)); -} - -KX_BlenderMaterial::~KX_BlenderMaterial() -{ - Material *ma = mMaterial->material; - // Restore Blender material data - ma->r = mSavedData.r; - ma->g = mSavedData.g; - ma->b = mSavedData.b; - ma->alpha = mSavedData.a; - ma->specr = mSavedData.specr; - ma->specg = mSavedData.specg; - ma->specb = mSavedData.specb; - ma->spec = mSavedData.spec; - ma->ref = mSavedData.ref; - ma->har = mSavedData.hardness; - ma->emit = mSavedData.emit; - - // cleanup work - if (mConstructed) - // clean only if material was actually used - OnExit(); -} - -unsigned int* KX_BlenderMaterial::GetMCol() const -{ - // fonts on polys - return mMaterial->rgb; -} - -void KX_BlenderMaterial::GetMaterialRGBAColor(unsigned char *rgba) const -{ - if (mMaterial) { - *rgba++ = (unsigned char)(mMaterial->matcolor[0] * 255.0f); - *rgba++ = (unsigned char)(mMaterial->matcolor[1] * 255.0f); - *rgba++ = (unsigned char)(mMaterial->matcolor[2] * 255.0f); - *rgba++ = (unsigned char)(mMaterial->matcolor[3] * 255.0f); - } else - RAS_IPolyMaterial::GetMaterialRGBAColor(rgba); -} - -Material *KX_BlenderMaterial::GetBlenderMaterial() const -{ - return mMaterial->material; -} - -Image *KX_BlenderMaterial::GetBlenderImage() const -{ - return mMaterial->material ? mMaterial->material->edit_image : NULL; -} - -Scene* KX_BlenderMaterial::GetBlenderScene() const -{ - return mScene->GetBlenderScene(); -} - -void KX_BlenderMaterial::ReleaseMaterial() -{ - if (mBlenderShader) - mBlenderShader->ReloadMaterial(); -} - -void KX_BlenderMaterial::InitTextures() -{ - // for each unique material... - int i; - for (i=0; imapping[i].mapping & USEENV ) { - if (!GLEW_ARB_texture_cube_map) { - spit("CubeMap textures not supported"); - continue; - } - if (!mTextures[i].InitCubeMap(i, mMaterial->cubemap[i] ) ) - spit("unable to initialize image("<matname<< ", image will not be available"); - } - /* If we're using glsl materials, the textures are handled by bf_gpu, so don't load them twice! - * However, if we're using a custom shader, then we still need to load the textures ourselves. */ - else if (!mMaterial->glslmat || mShader) { - if ( mMaterial->img[i] ) { - if ( ! mTextures[i].InitFromImage(i, mMaterial->img[i], (mMaterial->flag[i] &MIPMAP)!=0 )) - spit("unable to initialize image("<matname<< ", image will not be available"); - } - } - } -} - -void KX_BlenderMaterial::OnConstruction() -{ - if (mConstructed) - // when material are reused between objects - return; - - if (mMaterial->glslmat) - SetBlenderGLSLShader(); - - InitTextures(); - - mBlendFunc[0] =0; - mBlendFunc[1] =0; - mConstructed = true; -} - -void KX_BlenderMaterial::EndFrame() -{ - if (mLastBlenderShader) { - mLastBlenderShader->SetProg(false); - mLastBlenderShader = NULL; - } - - if (mLastShader) { - mLastShader->SetProg(false); - mLastShader = NULL; - } -} - -void KX_BlenderMaterial::OnExit() -{ - if ( mShader ) { - //note, the shader here is allocated, per unique material - //and this function is called per face - if (mShader == mLastShader) { - mShader->SetProg(false); - mLastShader = NULL; - } - - delete mShader; - mShader = 0; - } - - if ( mBlenderShader ) { - if (mBlenderShader == mLastBlenderShader) { - mBlenderShader->SetProg(false); - mLastBlenderShader = NULL; - } - - delete mBlenderShader; - mBlenderShader = 0; - } - - BL_Texture::ActivateFirst(); - for (int i=0; iOk() ) { - // frame cleanup. - if (mShader == mLastShader) { - mShader->SetProg(false); - mLastShader = NULL; - } - - ras->SetAlphaBlend(GPU_BLEND_SOLID); - BL_Texture::DisableAllTextures(); - return; - } - - BL_Texture::DisableAllTextures(); - mShader->SetProg(true); - mLastShader = mShader; - - BL_Texture::ActivateFirst(); - - mShader->ApplyShader(); - - // for each enabled unit - for (i=0; imapping[i].mapping); - } - - if (!mUserDefBlend) { - ras->SetAlphaBlend(mMaterial->alphablend); - } - else { - ras->SetAlphaBlend(GPU_BLEND_SOLID); - ras->SetAlphaBlend(-1); // indicates custom mode - - // tested to be valid enums - glEnable(GL_BLEND); - glBlendFunc(mBlendFunc[0], mBlendFunc[1]); - } -} - -void KX_BlenderMaterial::setBlenderShaderData( bool enable, RAS_IRasterizer *ras) -{ - if ( !enable || !mBlenderShader->Ok() ) { - ras->SetAlphaBlend(GPU_BLEND_SOLID); - - // frame cleanup. - if (mLastBlenderShader) { - mLastBlenderShader->SetProg(false); - mLastBlenderShader= NULL; - } - else - BL_Texture::DisableAllTextures(); - - return; - } - - if (!mBlenderShader->Equals(mLastBlenderShader)) { - ras->SetAlphaBlend(mMaterial->alphablend); - - if (mLastBlenderShader) - mLastBlenderShader->SetProg(false); - else - BL_Texture::DisableAllTextures(); - - mBlenderShader->SetProg(true, ras->GetTime(), ras); - mLastBlenderShader= mBlenderShader; - } -} - -void KX_BlenderMaterial::setTexData( bool enable, RAS_IRasterizer *ras) -{ - BL_Texture::DisableAllTextures(); - - if ( !enable ) { - ras->SetAlphaBlend(GPU_BLEND_SOLID); - return; - } - - BL_Texture::ActivateFirst(); - - if ( mMaterial->IdMode == DEFAULT_BLENDER ) { - ras->SetAlphaBlend(mMaterial->alphablend); - return; - } - - if ( mMaterial->IdMode == TEXFACE ) { - // no material connected to the object - if ( mTextures[0].Ok() ) { - mTextures[0].ActivateTexture(); - mTextures[0].setTexEnv(0, true); - mTextures[0].SetMapping(mMaterial->mapping[0].mapping); - ras->SetAlphaBlend(mMaterial->alphablend); - } - return; - } - - int mode = 0,i=0; - for (i=0; imapping[i].mapping; - - if (mode &USEOBJ) - setObjectMatrixData(i, ras); - else - mTextures[i].SetMapping(mode); - - if (!(mode &USEOBJ)) - setTexMatrixData( i ); - } - - if (!mUserDefBlend) { - ras->SetAlphaBlend(mMaterial->alphablend); - } - else { - ras->SetAlphaBlend(GPU_BLEND_SOLID); - ras->SetAlphaBlend(-1); // indicates custom mode - - glEnable(GL_BLEND); - glBlendFunc(mBlendFunc[0], mBlendFunc[1]); - } -} - -void -KX_BlenderMaterial::ActivatShaders( - RAS_IRasterizer* rasty, - TCachingInfo& cachingInfo)const -{ - KX_BlenderMaterial *tmp = const_cast(this); - - // reset... - if (tmp->mMaterial->IsShared()) - cachingInfo =0; - - if (mLastBlenderShader) { - mLastBlenderShader->SetProg(false); - mLastBlenderShader= NULL; - } - - if (GetCachingInfo() != cachingInfo) { - - if (!cachingInfo) - tmp->setShaderData(false, rasty); - - cachingInfo = GetCachingInfo(); - - if (rasty->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED) - tmp->setShaderData(true, rasty); - else if (rasty->GetDrawingMode() == RAS_IRasterizer::KX_SHADOW && mMaterial->alphablend != GEMAT_SOLID && !rasty->GetUsingOverrideShader()) - tmp->setShaderData(true, rasty); - else - tmp->setShaderData(false, rasty); - - if (mMaterial->ras_mode &TWOSIDED) - rasty->SetCullFace(false); - else - rasty->SetCullFace(true); - - if ((mMaterial->ras_mode &WIRE) || - (rasty->GetDrawingMode() <= RAS_IRasterizer::KX_WIREFRAME)) - { - if (mMaterial->ras_mode &WIRE) - rasty->SetCullFace(false); - rasty->SetLines(true); - } - else - rasty->SetLines(false); - ActivatGLMaterials(rasty); - ActivateTexGen(rasty); - } - - //ActivatGLMaterials(rasty); - //ActivateTexGen(rasty); -} - -void -KX_BlenderMaterial::ActivateBlenderShaders( - RAS_IRasterizer* rasty, - TCachingInfo& cachingInfo)const -{ - KX_BlenderMaterial *tmp = const_cast(this); - - if (mLastShader) { - mLastShader->SetProg(false); - mLastShader= NULL; - } - - if (GetCachingInfo() != cachingInfo) { - if (!cachingInfo) - tmp->setBlenderShaderData(false, rasty); - - cachingInfo = GetCachingInfo(); - - if (rasty->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED) - tmp->setBlenderShaderData(true, rasty); - else if (rasty->GetDrawingMode() == RAS_IRasterizer::KX_SHADOW && mMaterial->alphablend != GEMAT_SOLID && !rasty->GetUsingOverrideShader()) - tmp->setBlenderShaderData(true, rasty); - else - tmp->setBlenderShaderData(false, rasty); - - if (mMaterial->ras_mode &TWOSIDED) - rasty->SetCullFace(false); - else - rasty->SetCullFace(true); - - if ((mMaterial->ras_mode &WIRE) || - (rasty->GetDrawingMode() <= RAS_IRasterizer::KX_WIREFRAME)) - { - if (mMaterial->ras_mode &WIRE) - rasty->SetCullFace(false); - rasty->SetLines(true); - } - else - rasty->SetLines(false); - - ActivatGLMaterials(rasty); - mBlenderShader->SetAttribs(rasty, mMaterial); - } -} - -void -KX_BlenderMaterial::ActivateMat( - RAS_IRasterizer* rasty, - TCachingInfo& cachingInfo - )const -{ - KX_BlenderMaterial *tmp = const_cast(this); - - if (mLastShader) { - mLastShader->SetProg(false); - mLastShader= NULL; - } - - if (mLastBlenderShader) { - mLastBlenderShader->SetProg(false); - mLastBlenderShader= NULL; - } - - if (GetCachingInfo() != cachingInfo) { - if (!cachingInfo) - tmp->setTexData( false,rasty ); - - cachingInfo = GetCachingInfo(); - - if (rasty->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED) - tmp->setTexData( true,rasty ); - else if (rasty->GetDrawingMode() == RAS_IRasterizer::KX_SHADOW && mMaterial->alphablend != GEMAT_SOLID && !rasty->GetUsingOverrideShader()) - tmp->setTexData(true, rasty); - else - tmp->setTexData( false,rasty); - - if (mMaterial->ras_mode &TWOSIDED) - rasty->SetCullFace(false); - else - rasty->SetCullFace(true); - - if ((mMaterial->ras_mode &WIRE) || - (rasty->GetDrawingMode() <= RAS_IRasterizer::KX_WIREFRAME)) - { - if (mMaterial->ras_mode &WIRE) - rasty->SetCullFace(false); - rasty->SetLines(true); - } - else - rasty->SetLines(false); - ActivatGLMaterials(rasty); - ActivateTexGen(rasty); - } - - //ActivatGLMaterials(rasty); - //ActivateTexGen(rasty); -} - -bool -KX_BlenderMaterial::Activate( - RAS_IRasterizer* rasty, - TCachingInfo& cachingInfo - )const -{ - if (GLEW_ARB_shader_objects && (mShader && mShader->Ok())) { - if ((mPass++) < mShader->getNumPass() ) { - ActivatShaders(rasty, cachingInfo); - return true; - } - else { - if (mShader == mLastShader) { - mShader->SetProg(false); - mLastShader = NULL; - } - mPass = 0; - return false; - } - } - else if ( GLEW_ARB_shader_objects && (mBlenderShader && mBlenderShader->Ok() ) ) { - if (mPass++ == 0) { - ActivateBlenderShaders(rasty, cachingInfo); - return true; - } - else { - mPass = 0; - return false; - } - } - else { - if (mPass++ == 0) { - ActivateMat(rasty, cachingInfo); - return true; - } - else { - mPass = 0; - return false; - } - } -} - -bool KX_BlenderMaterial::UsesLighting(RAS_IRasterizer *rasty) const -{ - if (!RAS_IPolyMaterial::UsesLighting(rasty)) - return false; - - if (mShader && mShader->Ok()) - return true; - else if (mBlenderShader && mBlenderShader->Ok()) - return false; - else - return true; -} - -void KX_BlenderMaterial::ActivateMeshSlot(const RAS_MeshSlot & ms, RAS_IRasterizer* rasty) const -{ - if (mShader && GLEW_ARB_shader_objects) { - mShader->Update(ms, rasty); - } - else if (mBlenderShader && GLEW_ARB_shader_objects) { - int alphablend; - - mBlenderShader->Update(ms, rasty); - - /* we do blend modes here, because they can change per object - * with the same material due to obcolor/obalpha */ - alphablend = mBlenderShader->GetAlphaBlend(); - if (ELEM(alphablend, GEMAT_SOLID, GEMAT_ALPHA, GEMAT_ALPHA_SORT) && mMaterial->alphablend != GEMAT_SOLID) - alphablend = mMaterial->alphablend; - - rasty->SetAlphaBlend(alphablend); - } -} - -void KX_BlenderMaterial::ActivatGLMaterials( RAS_IRasterizer* rasty )const -{ - if (mShader || !mBlenderShader) { - rasty->SetSpecularity( - mMaterial->speccolor[0]*mMaterial->spec_f, - mMaterial->speccolor[1]*mMaterial->spec_f, - mMaterial->speccolor[2]*mMaterial->spec_f, - mMaterial->spec_f - ); - - rasty->SetShinyness( mMaterial->hard ); - - rasty->SetDiffuse( - mMaterial->matcolor[0]*mMaterial->ref+mMaterial->emit, - mMaterial->matcolor[1]*mMaterial->ref+mMaterial->emit, - mMaterial->matcolor[2]*mMaterial->ref+mMaterial->emit, - 1.0f); - - rasty->SetEmissive( - mMaterial->matcolor[0]*mMaterial->emit, - mMaterial->matcolor[1]*mMaterial->emit, - mMaterial->matcolor[2]*mMaterial->emit, - 1.0f ); - - rasty->SetAmbient(mMaterial->amb); - } - - if (mMaterial->material) - rasty->SetPolygonOffset(-mMaterial->material->zoffs, 0.0f); -} - - -void KX_BlenderMaterial::ActivateTexGen(RAS_IRasterizer *ras) const -{ - if (ras->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED || - (ras->GetDrawingMode() == RAS_IRasterizer::KX_SHADOW && mMaterial->alphablend != GEMAT_SOLID && !ras->GetUsingOverrideShader())) { - ras->SetAttribNum(0); - if (mShader && GLEW_ARB_shader_objects) { - if (mShader->GetAttribute() == BL_Shader::SHD_TANGENT) { - ras->SetAttrib(RAS_IRasterizer::RAS_TEXCO_DISABLE, 0); - ras->SetAttrib(RAS_IRasterizer::RAS_TEXTANGENT, 1); - ras->SetAttribNum(2); - } - } - - ras->SetTexCoordNum(mMaterial->num_enabled); - - for (int i=0; imapping[i].mapping; - - if ( mode &(USEREFL|USEOBJ)) - ras->SetTexCoord(RAS_IRasterizer::RAS_TEXCO_GEN, i); - else if (mode &USEORCO) - ras->SetTexCoord(RAS_IRasterizer::RAS_TEXCO_ORCO, i); - else if (mode &USENORM) - ras->SetTexCoord(RAS_IRasterizer::RAS_TEXCO_NORM, i); - else if (mode &USEUV) - ras->SetTexCoord(RAS_IRasterizer::RAS_TEXCO_UV, i); - else if (mode &USETANG) - ras->SetTexCoord(RAS_IRasterizer::RAS_TEXTANGENT, i); - else - ras->SetTexCoord(RAS_IRasterizer::RAS_TEXCO_DISABLE, i); - } - } -} - -void KX_BlenderMaterial::setTexMatrixData(int i) -{ - glMatrixMode(GL_TEXTURE); - glLoadIdentity(); - - if ( GLEW_ARB_texture_cube_map && - mTextures[i].GetTextureType() == GL_TEXTURE_CUBE_MAP_ARB && - mMaterial->mapping[i].mapping & USEREFL) { - glScalef( - mMaterial->mapping[i].scale[0], - -mMaterial->mapping[i].scale[1], - -mMaterial->mapping[i].scale[2] - ); - } - else - { - glScalef( - mMaterial->mapping[i].scale[0], - mMaterial->mapping[i].scale[1], - mMaterial->mapping[i].scale[2] - ); - } - glTranslatef( - mMaterial->mapping[i].offsets[0], - mMaterial->mapping[i].offsets[1], - mMaterial->mapping[i].offsets[2] - ); - - glMatrixMode(GL_MODELVIEW); - -} - -static void GetProjPlane(BL_Material *mat, int index,int num, float*param) -{ - param[0]=param[1]=param[2]=param[3]=0.f; - if ( mat->mapping[index].projplane[num] == PROJX ) - param[0] = 1.f; - else if ( mat->mapping[index].projplane[num] == PROJY ) - param[1] = 1.f; - else if ( mat->mapping[index].projplane[num] == PROJZ) - param[2] = 1.f; -} - -void KX_BlenderMaterial::setObjectMatrixData(int i, RAS_IRasterizer *ras) -{ - KX_GameObject *obj = - (KX_GameObject*) - mScene->GetObjectList()->FindValue(mMaterial->mapping[i].objconame); - - if (!obj) return; - - glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR ); - glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR ); - glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR ); - - GLenum plane = GL_EYE_PLANE; - - // figure plane gen - float proj[4] = {0.f,0.f,0.f,0.f}; - GetProjPlane(mMaterial, i, 0, proj); - glTexGenfv(GL_S, plane, proj); - - GetProjPlane(mMaterial, i, 1, proj); - glTexGenfv(GL_T, plane, proj); - - GetProjPlane(mMaterial, i, 2, proj); - glTexGenfv(GL_R, plane, proj); - - glEnable(GL_TEXTURE_GEN_S); - glEnable(GL_TEXTURE_GEN_T); - glEnable(GL_TEXTURE_GEN_R); - - const MT_Matrix4x4& mvmat = ras->GetViewMatrix(); - - glMatrixMode(GL_TEXTURE); - glLoadIdentity(); - glScalef( - mMaterial->mapping[i].scale[0], - mMaterial->mapping[i].scale[1], - mMaterial->mapping[i].scale[2] - ); - - MT_Point3 pos = obj->NodeGetWorldPosition(); - MT_Vector4 matmul = MT_Vector4(pos[0], pos[1], pos[2], 1.f); - MT_Vector4 t = mvmat*matmul; - - glTranslatef( (float)(-t[0]), (float)(-t[1]), (float)(-t[2]) ); - - glMatrixMode(GL_MODELVIEW); - -} - -// ------------------------------------ -void KX_BlenderMaterial::UpdateIPO( - MT_Vector4 rgba, - MT_Vector3 specrgb, - MT_Scalar hard, - MT_Scalar spec, - MT_Scalar ref, - MT_Scalar emit, - MT_Scalar alpha - ) -{ - // only works one deep now - - // GLSL Multitexture Input - mMaterial->material->specr = mMaterial->speccolor[0] = (float)(specrgb)[0]; - mMaterial->material->specg = mMaterial->speccolor[1] = (float)(specrgb)[1]; - mMaterial->material->specb = mMaterial->speccolor[2] = (float)(specrgb)[2]; - mMaterial->material->r = mMaterial->matcolor[0] = (float)(rgba[0]); - mMaterial->material->g = mMaterial->matcolor[1] = (float)(rgba[1]); - mMaterial->material->b = mMaterial->matcolor[2] = (float)(rgba[2]); - mMaterial->material->alpha = mMaterial->alpha = (float)(rgba[3]); - mMaterial->material->har = mMaterial->hard = (float)(hard); - mMaterial->material->emit = mMaterial->emit = (float)(emit); - mMaterial->material->spec = mMaterial->spec_f = (float)(spec); - mMaterial->material->ref = mMaterial->ref = (float)(ref); -} - -void KX_BlenderMaterial::Replace_IScene(SCA_IScene *val) -{ - mScene= static_cast(val); - - OnConstruction(); -} - -BL_Material *KX_BlenderMaterial::GetBLMaterial() -{ - return mMaterial; -} - -void KX_BlenderMaterial::SetBlenderGLSLShader() -{ - if (!mBlenderShader) - mBlenderShader = new BL_BlenderShader(mScene, mMaterial->material, mLightLayer); - - if (!mBlenderShader->Ok()) { - delete mBlenderShader; - mBlenderShader = 0; - } -} - -#ifdef USE_MATHUTILS - -#define MATHUTILS_COL_CB_MATERIAL_SPECULAR_COLOR 1 -#define MATHUTILS_COL_CB_MATERIAL_DIFFUSE_COLOR 2 - -static unsigned char mathutils_kxblendermaterial_color_cb_index = -1; /* index for our callbacks */ - -static int mathutils_kxblendermaterial_generic_check(BaseMathObject *bmo) -{ - KX_BlenderMaterial *self = static_castBGE_PROXY_REF(bmo->cb_user); - if (!self) - return -1; - - return 0; -} - -static int mathutils_kxblendermaterial_color_get(BaseMathObject *bmo, int subtype) -{ - KX_BlenderMaterial *self = static_castBGE_PROXY_REF(bmo->cb_user); - if (!self) - return -1; - - switch (subtype) { - case MATHUTILS_COL_CB_MATERIAL_DIFFUSE_COLOR: - { - copy_v3_v3(bmo->data, self->GetBLMaterial()->matcolor); - break; - } - case MATHUTILS_COL_CB_MATERIAL_SPECULAR_COLOR: - { - copy_v3_v3(bmo->data, self->GetBLMaterial()->speccolor); - break; - } - } - - return 0; -} - -static int mathutils_kxblendermaterial_color_set(BaseMathObject *bmo, int subtype) -{ - KX_BlenderMaterial *self = static_castBGE_PROXY_REF(bmo->cb_user); - if (!self) - return -1; - - switch (subtype) { - case MATHUTILS_COL_CB_MATERIAL_DIFFUSE_COLOR: - { - BL_Material *mat = self->GetBLMaterial(); - copy_v3_v3(mat->matcolor, bmo->data); - mat->material->r = bmo->data[0]; - mat->material->g = bmo->data[1]; - mat->material->b = bmo->data[2]; - break; - } - case MATHUTILS_COL_CB_MATERIAL_SPECULAR_COLOR: - { - BL_Material *mat = self->GetBLMaterial(); - copy_v3_v3(mat->speccolor, bmo->data); - mat->material->specr = bmo->data[0]; - mat->material->specg = bmo->data[1]; - mat->material->specb = bmo->data[2]; - break; - } - } - - return 0; -} - -static int mathutils_kxblendermaterial_color_get_index(BaseMathObject *bmo, int subtype, int index) -{ - /* lazy, avoid repeteing the case statement */ - if (mathutils_kxblendermaterial_color_get(bmo, subtype) == -1) - return -1; - return 0; -} - -static int mathutils_kxblendermaterial_color_set_index(BaseMathObject *bmo, int subtype, int index) -{ - float f = bmo->data[index]; - - /* lazy, avoid repeateing the case statement */ - if (mathutils_kxblendermaterial_color_get(bmo, subtype) == -1) - return -1; - - bmo->data[index] = f; - return mathutils_kxblendermaterial_color_set(bmo, subtype); -} - -static Mathutils_Callback mathutils_kxblendermaterial_color_cb = { - mathutils_kxblendermaterial_generic_check, - mathutils_kxblendermaterial_color_get, - mathutils_kxblendermaterial_color_set, - mathutils_kxblendermaterial_color_get_index, - mathutils_kxblendermaterial_color_set_index -}; - - -void KX_BlenderMaterial_Mathutils_Callback_Init() -{ - // register mathutils callbacks, ok to run more than once. - mathutils_kxblendermaterial_color_cb_index = Mathutils_RegisterCallback(&mathutils_kxblendermaterial_color_cb); -} - -#endif // USE_MATHUTILS - -#ifdef WITH_PYTHON - -PyMethodDef KX_BlenderMaterial::Methods[] = -{ - KX_PYMETHODTABLE( KX_BlenderMaterial, getShader ), - KX_PYMETHODTABLE( KX_BlenderMaterial, getMaterialIndex ), - KX_PYMETHODTABLE( KX_BlenderMaterial, getTextureBindcode ), - KX_PYMETHODTABLE( KX_BlenderMaterial, setBlending ), - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_BlenderMaterial::Attributes[] = { - KX_PYATTRIBUTE_RO_FUNCTION("shader", KX_BlenderMaterial, pyattr_get_shader), - KX_PYATTRIBUTE_RO_FUNCTION("material_index", KX_BlenderMaterial, pyattr_get_materialIndex), - KX_PYATTRIBUTE_RW_FUNCTION("blending", KX_BlenderMaterial, pyattr_get_blending, pyattr_set_blending), - KX_PYATTRIBUTE_RW_FUNCTION("alpha", KX_BlenderMaterial, pyattr_get_alpha, pyattr_set_alpha), - KX_PYATTRIBUTE_RW_FUNCTION("hardness", KX_BlenderMaterial, pyattr_get_hardness, pyattr_set_hardness), - KX_PYATTRIBUTE_RW_FUNCTION("specularIntensity", KX_BlenderMaterial, pyattr_get_specular_intensity, pyattr_set_specular_intensity), - KX_PYATTRIBUTE_RW_FUNCTION("specularColor", KX_BlenderMaterial, pyattr_get_specular_color, pyattr_set_specular_color), - KX_PYATTRIBUTE_RW_FUNCTION("diffuseIntensity", KX_BlenderMaterial, pyattr_get_diffuse_intensity, pyattr_set_diffuse_intensity), - KX_PYATTRIBUTE_RW_FUNCTION("diffuseColor", KX_BlenderMaterial, pyattr_get_diffuse_color, pyattr_set_diffuse_color), - KX_PYATTRIBUTE_RW_FUNCTION("emit", KX_BlenderMaterial, pyattr_get_emit, pyattr_set_emit), - - { NULL } //Sentinel -}; - -PyTypeObject KX_BlenderMaterial::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_BlenderMaterial", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &PyObjectPlus::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyObject *KX_BlenderMaterial::pyattr_get_shader(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_BlenderMaterial* self = static_cast(self_v); - return self->PygetShader(NULL, NULL); -} - -PyObject *KX_BlenderMaterial::pyattr_get_materialIndex(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_BlenderMaterial* self = static_cast(self_v); - return PyLong_FromLong(self->GetMaterialIndex()); -} - -PyObject *KX_BlenderMaterial::pyattr_get_blending(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_BlenderMaterial* self = static_cast(self_v); - unsigned int* bfunc = self->getBlendFunc(); - return Py_BuildValue("(ll)", (long int)bfunc[0], (long int)bfunc[1]); -} - -PyObject *KX_BlenderMaterial::pyattr_get_alpha(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_BlenderMaterial *self = static_cast(self_v); - return PyFloat_FromDouble(self->GetBLMaterial()->alpha); -} - -int KX_BlenderMaterial::pyattr_set_alpha(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_BlenderMaterial *self = static_cast(self_v); - float val = PyFloat_AsDouble(value); - - if (val == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_AttributeError, "material.%s = float: KX_BlenderMaterial, expected a float", attrdef->m_name); - return PY_SET_ATTR_FAIL; - } - - CLAMP(val, 0.0f, 1.0f); - - BL_Material *mat = self->GetBLMaterial(); - mat->alpha = mat->material->alpha = val; - return PY_SET_ATTR_SUCCESS; -} -PyObject *KX_BlenderMaterial::pyattr_get_hardness(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_BlenderMaterial *self = static_cast(self_v); - return PyLong_FromLong(self->GetBLMaterial()->hard); -} - -int KX_BlenderMaterial::pyattr_set_hardness(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_BlenderMaterial *self = static_cast(self_v); - int val = PyLong_AsLong(value); - - if (val == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_AttributeError, "material.%s = int: KX_BlenderMaterial, expected a int", attrdef->m_name); - return PY_SET_ATTR_FAIL; - } - - CLAMP(val, 1, 511); - - BL_Material *mat = self->GetBLMaterial(); - mat->hard = mat->material->har = val; - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_BlenderMaterial::pyattr_get_specular_intensity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_BlenderMaterial *self = static_cast(self_v); - return PyFloat_FromDouble(self->GetBLMaterial()->spec_f); -} - -int KX_BlenderMaterial::pyattr_set_specular_intensity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_BlenderMaterial *self = static_cast(self_v); - float val = PyFloat_AsDouble(value); - - if (val == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_AttributeError, "material.%s = float: KX_BlenderMaterial, expected a float", attrdef->m_name); - return PY_SET_ATTR_FAIL; - } - - CLAMP(val, 0.0f, 1.0f); - - BL_Material *mat = self->GetBLMaterial(); - mat->spec_f = mat->material->spec = val; - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_BlenderMaterial::pyattr_get_specular_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ -#ifdef USE_MATHUTILS - return Color_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), mathutils_kxblendermaterial_color_cb_index, MATHUTILS_COL_CB_MATERIAL_SPECULAR_COLOR); -#else - KX_BlenderMaterial *self = static_cast(self_v); - return PyColorFromVector(MT_Vector3(self->GetBLMaterial()->speccolor)); -#endif -} - -int KX_BlenderMaterial::pyattr_set_specular_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_BlenderMaterial *self = static_cast(self_v); - MT_Vector3 color; - if (!PyVecTo(value, color)) - return PY_SET_ATTR_FAIL; - - BL_Material *mat = self->GetBLMaterial(); - color.getValue(mat->speccolor); - mat->material->specr = color[0]; - mat->material->specg = color[1]; - mat->material->specb = color[2]; - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_BlenderMaterial::pyattr_get_diffuse_intensity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_BlenderMaterial *self = static_cast(self_v); - return PyFloat_FromDouble(self->GetBLMaterial()->ref); -} - -int KX_BlenderMaterial::pyattr_set_diffuse_intensity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_BlenderMaterial *self = static_cast(self_v); - float val = PyFloat_AsDouble(value); - - if (val == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_AttributeError, "material.%s = float: KX_BlenderMaterial, expected a float", attrdef->m_name); - return PY_SET_ATTR_FAIL; - } - - CLAMP(val, 0.0f, 1.0f); - - BL_Material *mat = self->GetBLMaterial(); - mat->ref = mat->material->ref = val; - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_BlenderMaterial::pyattr_get_diffuse_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ -#ifdef USE_MATHUTILS - return Color_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), mathutils_kxblendermaterial_color_cb_index, MATHUTILS_COL_CB_MATERIAL_DIFFUSE_COLOR); -#else - KX_BlenderMaterial *self = static_cast(self_v); - return PyColorFromVector(MT_Vector3(self->GetBLMaterial()->matcolor)); -#endif -} - -int KX_BlenderMaterial::pyattr_set_diffuse_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_BlenderMaterial *self = static_cast(self_v); - MT_Vector3 color; - if (!PyVecTo(value, color)) - return PY_SET_ATTR_FAIL; - - BL_Material *mat = self->GetBLMaterial(); - color.getValue(mat->matcolor); - mat->material->r = color[0]; - mat->material->g = color[1]; - mat->material->b = color[2]; - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_BlenderMaterial::pyattr_get_emit(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_BlenderMaterial *self = static_cast(self_v); - return PyFloat_FromDouble(self->GetBLMaterial()->emit); -} - -int KX_BlenderMaterial::pyattr_set_emit(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_BlenderMaterial *self = static_cast(self_v); - float val = PyFloat_AsDouble(value); - - if (val == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_AttributeError, "material.%s = float: KX_BlenderMaterial, expected a float", attrdef->m_name); - return PY_SET_ATTR_FAIL; - } - - CLAMP(val, 0.0f, 2.0f); - - BL_Material *mat = self->GetBLMaterial(); - mat->emit = mat->material->emit = val; - return PY_SET_ATTR_SUCCESS; -} - -int KX_BlenderMaterial::pyattr_set_blending(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_BlenderMaterial* self = static_cast(self_v); - PyObject *obj = self->PysetBlending(value, NULL); - if (obj) - { - Py_DECREF(obj); - return 0; - } - return -1; -} - -KX_PYMETHODDEF_DOC( KX_BlenderMaterial, getShader , "getShader()") -{ - if ( !GLEW_ARB_fragment_shader) { - if (!mModified) - spit("Fragment shaders not supported"); - - mModified = true; - Py_RETURN_NONE; - } - - if ( !GLEW_ARB_vertex_shader) { - if (!mModified) - spit("Vertex shaders not supported"); - - mModified = true; - Py_RETURN_NONE; - } - - if (!GLEW_ARB_shader_objects) { - if (!mModified) - spit("GLSL not supported"); - mModified = true; - Py_RETURN_NONE; - } - else { - // returns Py_None on error - // the calling script will need to check - - if (!mShader && !mModified) { - mShader = new BL_Shader(); - mModified = true; - - // Using a custom shader, make sure to initialize textures - InitTextures(); - } - - if (mShader && !mShader->GetError()) { - m_flag &= ~RAS_BLENDERGLSL; - mMaterial->SetSharedMaterial(true); - mScene->GetBucketManager()->ReleaseDisplayLists(this); - return mShader->GetProxy(); - } - else { - // decref all references to the object - // then delete it! - // We will then go back to fixed functionality - // for this material - if (mShader) { - delete mShader; /* will handle python de-referencing */ - mShader=0; - } - } - Py_RETURN_NONE; - } - PyErr_SetString(PyExc_ValueError, "material.getShader(): KX_BlenderMaterial, GLSL Error"); - return NULL; -} - -KX_PYMETHODDEF_DOC( KX_BlenderMaterial, getMaterialIndex, "getMaterialIndex()") -{ - return PyLong_FromLong(GetMaterialIndex()); -} - -KX_PYMETHODDEF_DOC( KX_BlenderMaterial, getTexture, "getTexture( index )" ) -{ - // TODO: enable python switching - return NULL; -} - -KX_PYMETHODDEF_DOC( KX_BlenderMaterial, setTexture , "setTexture( index, tex)") -{ - // TODO: enable python switching - return NULL; -} - -static const unsigned int GL_array[11] = { - GL_ZERO, - GL_ONE, - GL_SRC_COLOR, - GL_ONE_MINUS_SRC_COLOR, - GL_DST_COLOR, - GL_ONE_MINUS_DST_COLOR, - GL_SRC_ALPHA, - GL_ONE_MINUS_SRC_ALPHA, - GL_DST_ALPHA, - GL_ONE_MINUS_DST_ALPHA, - GL_SRC_ALPHA_SATURATE -}; - -KX_PYMETHODDEF_DOC( KX_BlenderMaterial, setBlending , "setBlending( bge.logic.src, bge.logic.dest)") -{ - unsigned int b[2]; - if (PyArg_ParseTuple(args, "ii:setBlending", &b[0], &b[1])) - { - bool value_found[2] = {false, false}; - for (int i=0; i<11; i++) - { - if (b[0] == GL_array[i]) { - value_found[0] = true; - mBlendFunc[0] = b[0]; - } - if (b[1] == GL_array[i]) { - value_found[1] = true; - mBlendFunc[1] = b[1]; - } - if (value_found[0] && value_found[1]) break; - } - if (!value_found[0] || !value_found[1]) { - PyErr_SetString(PyExc_ValueError, "material.setBlending(int, int): KX_BlenderMaterial, invalid enum."); - return NULL; - } - mUserDefBlend = true; - Py_RETURN_NONE; - } - return NULL; -} - -KX_PYMETHODDEF_DOC(KX_BlenderMaterial, getTextureBindcode, "getTextureBindcode(texslot)") -{ - unsigned int texslot; - if (!PyArg_ParseTuple(args, "i:texslot", &texslot)) { - PyErr_SetString(PyExc_ValueError, "material.getTextureBindcode(texslot): KX_BlenderMaterial, expected an int."); - return NULL; - } - Image *ima = getImage(texslot); - if (ima) { - unsigned int *bindcode = ima->bindcode; - return PyLong_FromLong(*bindcode); - } - PyErr_SetString(PyExc_ValueError, "material.getTextureBindcode(texslot): KX_BlenderMaterial, invalid texture slot."); - return NULL; -} - -#endif // WITH_PYTHON diff --git a/source/gameengine/Ketsji/KX_BlenderMaterial.h b/source/gameengine/Ketsji/KX_BlenderMaterial.h deleted file mode 100644 index c562ee0c583..00000000000 --- a/source/gameengine/Ketsji/KX_BlenderMaterial.h +++ /dev/null @@ -1,200 +0,0 @@ - -/** \file KX_BlenderMaterial.h - * \ingroup ketsji - */ - -#ifndef __KX_BLENDERMATERIAL_H__ -#define __KX_BLENDERMATERIAL_H__ - -#include - - -#include "RAS_IPolygonMaterial.h" -#include "BL_Material.h" -#include "BL_Texture.h" -#include "BL_Shader.h" -#include "BL_BlenderShader.h" - -#include "EXP_PyObjectPlus.h" - -#include "MT_Vector3.h" -#include "MT_Vector4.h" - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -#include "SCA_IScene.h" /* only for Replace_IScene */ -#include "KX_Scene.h" - -struct MTFace; -class KX_Scene; - - -#ifdef USE_MATHUTILS -void KX_BlenderMaterial_Mathutils_Callback_Init(void); -#endif - -class KX_BlenderMaterial : public PyObjectPlus, public RAS_IPolyMaterial -{ - Py_Header -public: - // -------------------------------- - KX_BlenderMaterial(); - void Initialize( - class KX_Scene* scene, - BL_Material* mat, - GameSettings* game, - int lightlayer - ); - - virtual ~KX_BlenderMaterial(); - - // -------------------------------- - virtual TCachingInfo GetCachingInfo(void) const { - return (void*) this; - } - - virtual - bool Activate( - RAS_IRasterizer* rasty, - TCachingInfo& cachingInfo - ) const; - - virtual - void ActivateMeshSlot( - const RAS_MeshSlot & ms, - RAS_IRasterizer* rasty - ) const; - - void ActivateMat( - RAS_IRasterizer* rasty, - TCachingInfo& cachingInfo - )const; - - void ActivatShaders( - RAS_IRasterizer* rasty, - TCachingInfo& cachingInfo - )const; - - void ActivateBlenderShaders( - RAS_IRasterizer* rasty, - TCachingInfo& cachingInfo - )const; - - Material* GetBlenderMaterial() const; - Image* GetBlenderImage() const; - unsigned int* GetMCol() const; - BL_Texture * getTex (unsigned int idx) { - return (idx < MAXTEX) ? mTextures + idx : NULL; - } - Image * getImage (unsigned int idx) { - return (idx < MAXTEX && mMaterial) ? mMaterial->img[idx] : NULL; - } - unsigned int* getBlendFunc() { - return mBlendFunc; - } - // for ipos - void UpdateIPO( - MT_Vector4 rgba, MT_Vector3 specrgb, - MT_Scalar hard, MT_Scalar spec, - MT_Scalar ref, MT_Scalar emit, MT_Scalar alpha - ); - - virtual void Replace_IScene(SCA_IScene *val); - - BL_Material *GetBLMaterial(); - -#ifdef WITH_PYTHON - // -------------------------------- - virtual PyObject *py_repr(void) { return PyUnicode_From_STR_String(mMaterial->matname); } - - static PyObject *pyattr_get_shader(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_materialIndex(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_blending(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_blending(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject *pyattr_get_alpha(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_alpha(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject *pyattr_get_hardness(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_hardness(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject *pyattr_get_specular_intensity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_specular_intensity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject *pyattr_get_specular_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_specular_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject *pyattr_get_diffuse_intensity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_diffuse_intensity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject *pyattr_get_diffuse_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_diffuse_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject *pyattr_get_emit(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_emit(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - - KX_PYMETHOD_DOC(KX_BlenderMaterial, getShader); - KX_PYMETHOD_DOC(KX_BlenderMaterial, getMaterialIndex); - KX_PYMETHOD_DOC(KX_BlenderMaterial, getTexture); - KX_PYMETHOD_DOC(KX_BlenderMaterial, setTexture); - KX_PYMETHOD_DOC(KX_BlenderMaterial, getTextureBindcode); - - KX_PYMETHOD_DOC(KX_BlenderMaterial, setBlending); -#endif /* WITH_PYTHON */ - - // -------------------------------- - // pre calculate to avoid pops/lag at startup - virtual void OnConstruction(); - - static void EndFrame(); - -private: - BL_Material* mMaterial; - BL_Shader* mShader; - BL_BlenderShader* mBlenderShader; - KX_Scene* mScene; - BL_Texture mTextures[MAXTEX]; // texture array - bool mUserDefBlend; - unsigned int mBlendFunc[2]; - bool mModified; - bool mConstructed; // if false, don't clean on exit - int mLightLayer; - - struct { - float r, g, b, a; - float specr, specg, specb; - float spec; - float ref; - float hardness; - float emit; - } mSavedData; - - void InitTextures(); - - void SetBlenderGLSLShader(); - - void ActivatGLMaterials( RAS_IRasterizer* rasty )const; - void ActivateTexGen( RAS_IRasterizer *ras ) const; - - bool UsesLighting(RAS_IRasterizer *rasty) const; - void GetMaterialRGBAColor(unsigned char *rgba) const; - Scene* GetBlenderScene() const; - void ReleaseMaterial(); - - // message centers - void setTexData( bool enable,RAS_IRasterizer *ras); - void setBlenderShaderData( bool enable, RAS_IRasterizer *ras); - void setShaderData( bool enable, RAS_IRasterizer *ras); - - void setObjectMatrixData(int i, RAS_IRasterizer *ras); - void setTexMatrixData(int i); - - void setLightData(); - - // cleanup stuff - void OnExit(); - - // shader chacing - static BL_BlenderShader *mLastBlenderShader; - static BL_Shader *mLastShader; - - mutable int mPass; -}; - - -#endif diff --git a/source/gameengine/Ketsji/KX_Camera.cpp b/source/gameengine/Ketsji/KX_Camera.cpp deleted file mode 100644 index b22873aa862..00000000000 --- a/source/gameengine/Ketsji/KX_Camera.cpp +++ /dev/null @@ -1,1166 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - * Camera in the gameengine. Cameras are also used for views. - */ - -/** \file gameengine/Ketsji/KX_Camera.cpp - * \ingroup ketsji - */ - -#include "GPU_glew.h" -#include "GPU_matrix.h" -#include "KX_Camera.h" -#include "KX_Scene.h" -#include "KX_PythonInit.h" -#include "EXP_Python.h" -#include "KX_PyMath.h" - -#include "RAS_ICanvas.h" - -KX_Camera::KX_Camera(void* sgReplicationInfo, - SG_Callbacks callbacks, - const RAS_CameraData& camdata, - bool frustum_culling, - bool delete_node) - : - KX_GameObject(sgReplicationInfo,callbacks), - m_camdata(camdata), - m_dirty(true), - m_normalized(false), - m_frustum_culling(frustum_culling), - m_set_projection_matrix(false), - m_set_frustum_center(false), - m_delete_node(delete_node) -{ - // setting a name would be nice... - m_name = "cam"; - m_projection_matrix.setIdentity(); - m_modelview_matrix.setIdentity(); -} - - -KX_Camera::~KX_Camera() -{ - if (m_delete_node && m_pSGNode) - { - // for shadow camera, avoids memleak - delete m_pSGNode; - m_pSGNode = NULL; - } -} - - -CValue* KX_Camera::GetReplica() -{ - KX_Camera* replica = new KX_Camera(*this); - - // this will copy properties and so on... - replica->ProcessReplica(); - - return replica; -} - -void KX_Camera::ProcessReplica() -{ - KX_GameObject::ProcessReplica(); - // replicated camera are always registered in the scene - m_delete_node = false; -} - -MT_Transform KX_Camera::GetWorldToCamera() const -{ - MT_Transform camtrans; - camtrans.invert(MT_Transform(NodeGetWorldPosition(), NodeGetWorldOrientation())); - - return camtrans; -} - - - -MT_Transform KX_Camera::GetCameraToWorld() const -{ - return MT_Transform(NodeGetWorldPosition(), NodeGetWorldOrientation()); -} - - - -void KX_Camera::CorrectLookUp(MT_Scalar speed) -{ -} - - - -const MT_Point3 KX_Camera::GetCameraLocation() const -{ - /* this is the camera locatio in cam coords... */ - //return m_trans1.getOrigin(); - //return MT_Point3(0,0,0); <----- - /* .... I want it in world coords */ - //MT_Transform trans; - //trans.setBasis(NodeGetWorldOrientation()); - - return NodeGetWorldPosition(); -} - - - -/* I want the camera orientation as well. */ -const MT_Quaternion KX_Camera::GetCameraOrientation() const -{ - return NodeGetWorldOrientation().getRotation(); -} - - - -/** - * Sets the projection matrix that is used by the rasterizer. - */ -void KX_Camera::SetProjectionMatrix(const MT_Matrix4x4 & mat) -{ - m_projection_matrix = mat; - m_dirty = true; - m_set_projection_matrix = true; - m_set_frustum_center = false; -} - - - -/** - * Sets the modelview matrix that is used by the rasterizer. - */ -void KX_Camera::SetModelviewMatrix(const MT_Matrix4x4 & mat) -{ - m_modelview_matrix = mat; - m_dirty = true; - m_set_frustum_center = false; -} - - - -/** - * Gets the projection matrix that is used by the rasterizer. - */ -const MT_Matrix4x4& KX_Camera::GetProjectionMatrix() const -{ - return m_projection_matrix; -} - - - -/** - * Gets the modelview matrix that is used by the rasterizer. - */ -const MT_Matrix4x4& KX_Camera::GetModelviewMatrix() const -{ - return m_modelview_matrix; -} - - -bool KX_Camera::hasValidProjectionMatrix() const -{ - return m_set_projection_matrix; -} - -void KX_Camera::InvalidateProjectionMatrix(bool valid) -{ - m_set_projection_matrix = valid; -} - - -/** - * These getters retrieve the clip data and the focal length - */ -float KX_Camera::GetLens() const -{ - return m_camdata.m_lens; -} - -float KX_Camera::GetScale() const -{ - return m_camdata.m_scale; -} - -/** - * Gets the horizontal size of the sensor - for camera matching. - */ -float KX_Camera::GetSensorWidth() const -{ - return m_camdata.m_sensor_x; -} - -/** - * Gets the vertical size of the sensor - for camera matching. - */ -float KX_Camera::GetSensorHeight() const -{ - return m_camdata.m_sensor_y; -} -/** Gets the mode FOV is calculating from sensor dimensions */ -short KX_Camera::GetSensorFit() const -{ - return m_camdata.m_sensor_fit; -} - -/** - * Gets the horizontal shift of the sensor - for camera matching. - */ -float KX_Camera::GetShiftHorizontal() const -{ - return m_camdata.m_shift_x; -} - -/** - * Gets the vertical shift of the sensor - for camera matching. - */ -float KX_Camera::GetShiftVertical() const -{ - return m_camdata.m_shift_y; -} - -float KX_Camera::GetCameraNear() const -{ - return m_camdata.m_clipstart; -} - - - -float KX_Camera::GetCameraFar() const -{ - return m_camdata.m_clipend; -} - -float KX_Camera::GetFocalLength() const -{ - return m_camdata.m_focallength; -} - - - -RAS_CameraData* KX_Camera::GetCameraData() -{ - return &m_camdata; -} - -void KX_Camera::ExtractClipPlanes() -{ - if (!m_dirty) - return; - - MT_Matrix4x4 m = m_projection_matrix * m_modelview_matrix; - // Left clip plane - m_planes[0] = m[3] + m[0]; - // Right clip plane - m_planes[1] = m[3] - m[0]; - // Top clip plane - m_planes[2] = m[3] - m[1]; - // Bottom clip plane - m_planes[3] = m[3] + m[1]; - // Near clip plane - m_planes[4] = m[3] + m[2]; - // Far clip plane - m_planes[5] = m[3] - m[2]; - - m_dirty = false; - m_normalized = false; -} - -void KX_Camera::NormalizeClipPlanes() -{ - if (m_normalized) - return; - - for (unsigned int p = 0; p < 6; p++) - { - MT_Scalar factor = sqrtf(m_planes[p][0]*m_planes[p][0] + m_planes[p][1]*m_planes[p][1] + m_planes[p][2]*m_planes[p][2]); - if (!MT_fuzzyZero(factor)) - m_planes[p] /= factor; - } - - m_normalized = true; -} - -void KX_Camera::ExtractFrustumSphere() -{ - if (m_set_frustum_center) - return; - - // compute sphere for the general case and not only symmetric frustum: - // the mirror code in ImageRender can use very asymmetric frustum. - // We will put the sphere center on the line that goes from origin to the center of the far clipping plane - // This is the optimal position if the frustum is symmetric or very asymmetric and probably close - // to optimal for the general case. The sphere center position is computed so that the distance to - // the near and far extreme frustum points are equal. - - // get the transformation matrix from device coordinate to camera coordinate - MT_Matrix4x4 clip_camcs_matrix = m_projection_matrix; - clip_camcs_matrix.invert(); - - if (m_projection_matrix[3][3] == MT_Scalar(0.0f)) - { - // frustum projection - // detect which of the corner of the far clipping plane is the farthest to the origin - MT_Vector4 nfar; // far point in device normalized coordinate - MT_Point3 farpoint; // most extreme far point in camera coordinate - MT_Point3 nearpoint;// most extreme near point in camera coordinate - MT_Point3 farcenter(0.0f, 0.0f, 0.0f);// center of far cliping plane in camera coordinate - MT_Scalar F=-1.0f, N; // square distance of far and near point to origin - MT_Scalar f, n; // distance of far and near point to z axis. f is always > 0 but n can be < 0 - MT_Scalar e, s; // far and near clipping distance (<0) - MT_Scalar c; // slope of center line = distance of far clipping center to z axis / far clipping distance - MT_Scalar z; // projection of sphere center on z axis (<0) - // tmp value - MT_Vector4 npoint(1.0f, 1.0f, 1.0f, 1.0f); - MT_Vector4 hpoint; - MT_Point3 point; - MT_Scalar len; - for (int i=0; i<4; i++) - { - hpoint = clip_camcs_matrix*npoint; - point.setValue(hpoint[0]/hpoint[3], hpoint[1]/hpoint[3], hpoint[2]/hpoint[3]); - len = point.dot(point); - if (len > F) - { - nfar = npoint; - farpoint = point; - F = len; - } - // rotate by 90 degree along the z axis to walk through the 4 extreme points of the far clipping plane - len = npoint[0]; - npoint[0] = -npoint[1]; - npoint[1] = len; - farcenter += point; - } - // the far center is the average of the far clipping points - farcenter *= 0.25f; - // the extreme near point is the opposite point on the near clipping plane - nfar.setValue(-nfar[0], -nfar[1], -1.0f, 1.0f); - nfar = clip_camcs_matrix*nfar; - nearpoint.setValue(nfar[0]/nfar[3], nfar[1]/nfar[3], nfar[2]/nfar[3]); - // this is a frustum projection - N = nearpoint.dot(nearpoint); - e = farpoint[2]; - s = nearpoint[2]; - // projection on XY plane for distance to axis computation - MT_Point2 farxy(farpoint[0], farpoint[1]); - // f is forced positive by construction - f = farxy.length(); - // get corresponding point on the near plane - farxy *= s/e; - // this formula preserve the sign of n - n = f*s/e - MT_Point2(nearpoint[0]-farxy[0], nearpoint[1]-farxy[1]).length(); - c = MT_Point2(farcenter[0], farcenter[1]).length()/e; - // the big formula, it simplifies to (F-N)/(2(e-s)) for the symmetric case - z = (F-N)/(2.0f*(e-s+c*(f-n))); - m_frustum_center = MT_Point3(farcenter[0]*z/e, farcenter[1]*z/e, z); - m_frustum_radius = m_frustum_center.distance(farpoint); - } - else - { - // orthographic projection - // The most extreme points on the near and far plane. (normalized device coords) - MT_Vector4 hnear(1.0f, 1.0f, 1.0f, 1.0f), hfar(-1.0f, -1.0f, -1.0f, 1.0f); - - // Transform to hom camera local space - hnear = clip_camcs_matrix*hnear; - hfar = clip_camcs_matrix*hfar; - - // Tranform to 3d camera local space. - MT_Point3 nearpoint(hnear[0]/hnear[3], hnear[1]/hnear[3], hnear[2]/hnear[3]); - MT_Point3 farpoint(hfar[0]/hfar[3], hfar[1]/hfar[3], hfar[2]/hfar[3]); - - // just use mediant point - m_frustum_center = (farpoint + nearpoint)*0.5f; - m_frustum_radius = m_frustum_center.distance(farpoint); - } - // Transform to world space. - m_frustum_center = GetCameraToWorld()(m_frustum_center); - m_frustum_radius /= fabsf(NodeGetWorldScaling()[NodeGetWorldScaling().closestAxis()]); - - m_set_frustum_center = true; -} - -bool KX_Camera::PointInsideFrustum(const MT_Point3& x) -{ - ExtractClipPlanes(); - - for ( unsigned int i = 0; i < 6 ; i++ ) - { - if (m_planes[i][0] * x[0] + m_planes[i][1] * x[1] + m_planes[i][2] * x[2] + m_planes[i][3] < 0.0f) - return false; - } - return true; -} - -int KX_Camera::BoxInsideFrustum(const MT_Point3 *box) -{ - ExtractClipPlanes(); - - unsigned int insideCount = 0; - // 6 view frustum planes - for ( unsigned int p = 0; p < 6 ; p++ ) - { - unsigned int behindCount = 0; - // 8 box vertices. - for (unsigned int v = 0; v < 8 ; v++) - { - if (m_planes[p][0] * box[v][0] + m_planes[p][1] * box[v][1] + m_planes[p][2] * box[v][2] + m_planes[p][3] < 0.0f) - behindCount++; - } - - // 8 points behind this plane - if (behindCount == 8) - return OUTSIDE; - - // Every box vertex is on the front side of this plane - if (!behindCount) - insideCount++; - } - - // All box vertices are on the front side of all frustum planes. - if (insideCount == 6) - return INSIDE; - - return INTERSECT; -} - -int KX_Camera::SphereInsideFrustum(const MT_Point3& center, const MT_Scalar &radius) -{ - ExtractFrustumSphere(); - if (center.distance2(m_frustum_center) > (radius + m_frustum_radius)*(radius + m_frustum_radius)) - return OUTSIDE; - - unsigned int p; - ExtractClipPlanes(); - NormalizeClipPlanes(); - - MT_Scalar distance; - int intersect = INSIDE; - // distance: <-------- OUTSIDE -----|----- INTERSECT -----0----- INTERSECT -----|----- INSIDE --------> - // -radius radius - for (p = 0; p < 6; p++) - { - distance = m_planes[p][0]*center[0] + m_planes[p][1]*center[1] + m_planes[p][2]*center[2] + m_planes[p][3]; - if (fabsf(distance) <= radius) - intersect = INTERSECT; - else if (distance < -radius) - return OUTSIDE; - } - - return intersect; -} - -bool KX_Camera::GetFrustumCulling() const -{ - return m_frustum_culling; -} - -void KX_Camera::EnableViewport(bool viewport) -{ - InvalidateProjectionMatrix(false); // We need to reset projection matrix - m_camdata.m_viewport = viewport; -} - -void KX_Camera::SetViewport(int left, int bottom, int right, int top) -{ - m_camdata.m_viewportleft = left; - m_camdata.m_viewportbottom = bottom; - m_camdata.m_viewportright = right; - m_camdata.m_viewporttop = top; -} - -bool KX_Camera::GetViewport() const -{ - return m_camdata.m_viewport; -} - -int KX_Camera::GetViewportLeft() const -{ - return m_camdata.m_viewportleft; -} - -int KX_Camera::GetViewportBottom() const -{ - return m_camdata.m_viewportbottom; -} - -int KX_Camera::GetViewportRight() const -{ - return m_camdata.m_viewportright; -} - -int KX_Camera::GetViewportTop() const -{ - return m_camdata.m_viewporttop; -} - -#ifdef WITH_PYTHON -//---------------------------------------------------------------------------- -//Python - - -PyMethodDef KX_Camera::Methods[] = { - KX_PYMETHODTABLE(KX_Camera, sphereInsideFrustum), - KX_PYMETHODTABLE_O(KX_Camera, boxInsideFrustum), - KX_PYMETHODTABLE_O(KX_Camera, pointInsideFrustum), - KX_PYMETHODTABLE_NOARGS(KX_Camera, getCameraToWorld), - KX_PYMETHODTABLE_NOARGS(KX_Camera, getWorldToCamera), - KX_PYMETHODTABLE(KX_Camera, setViewport), - KX_PYMETHODTABLE_NOARGS(KX_Camera, setOnTop), - KX_PYMETHODTABLE_O(KX_Camera, getScreenPosition), - KX_PYMETHODTABLE(KX_Camera, getScreenVect), - KX_PYMETHODTABLE(KX_Camera, getScreenRay), - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_Camera::Attributes[] = { - - KX_PYATTRIBUTE_BOOL_RW("frustum_culling", KX_Camera, m_frustum_culling), - KX_PYATTRIBUTE_RW_FUNCTION("perspective", KX_Camera, pyattr_get_perspective, pyattr_set_perspective), - - KX_PYATTRIBUTE_RW_FUNCTION("lens", KX_Camera, pyattr_get_lens, pyattr_set_lens), - KX_PYATTRIBUTE_RW_FUNCTION("fov", KX_Camera, pyattr_get_fov, pyattr_set_fov), - KX_PYATTRIBUTE_RW_FUNCTION("ortho_scale", KX_Camera, pyattr_get_ortho_scale, pyattr_set_ortho_scale), - KX_PYATTRIBUTE_RW_FUNCTION("near", KX_Camera, pyattr_get_near, pyattr_set_near), - KX_PYATTRIBUTE_RW_FUNCTION("far", KX_Camera, pyattr_get_far, pyattr_set_far), - KX_PYATTRIBUTE_RW_FUNCTION("shift_x", KX_Camera, pyattr_get_shift_x, pyattr_set_shift_x), - KX_PYATTRIBUTE_RW_FUNCTION("shift_y", KX_Camera, pyattr_get_shift_y, pyattr_set_shift_y), - - KX_PYATTRIBUTE_RW_FUNCTION("useViewport", KX_Camera, pyattr_get_use_viewport, pyattr_set_use_viewport), - - KX_PYATTRIBUTE_RW_FUNCTION("projection_matrix", KX_Camera, pyattr_get_projection_matrix, pyattr_set_projection_matrix), - KX_PYATTRIBUTE_RO_FUNCTION("modelview_matrix", KX_Camera, pyattr_get_modelview_matrix), - KX_PYATTRIBUTE_RO_FUNCTION("camera_to_world", KX_Camera, pyattr_get_camera_to_world), - KX_PYATTRIBUTE_RO_FUNCTION("world_to_camera", KX_Camera, pyattr_get_world_to_camera), - - /* Grrr, functions for constants? */ - KX_PYATTRIBUTE_RO_FUNCTION("INSIDE", KX_Camera, pyattr_get_INSIDE), - KX_PYATTRIBUTE_RO_FUNCTION("OUTSIDE", KX_Camera, pyattr_get_OUTSIDE), - KX_PYATTRIBUTE_RO_FUNCTION("INTERSECT", KX_Camera, pyattr_get_INTERSECT), - - { NULL } //Sentinel -}; - -PyTypeObject KX_Camera::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_Camera", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0, - &KX_GameObject::Sequence, - &KX_GameObject::Mapping, - 0,0,0, - NULL, - NULL, - 0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &KX_GameObject::Type, - 0,0,0,0,0,0, - py_base_new -}; - -KX_PYMETHODDEF_DOC_VARARGS(KX_Camera, sphereInsideFrustum, -"sphereInsideFrustum(center, radius) -> Integer\n" -"\treturns INSIDE, OUTSIDE or INTERSECT if the given sphere is\n" -"\tinside/outside/intersects this camera's viewing frustum.\n\n" -"\tcenter = the center of the sphere (in world coordinates.)\n" -"\tradius = the radius of the sphere\n\n" -"\tExample:\n" -"\timport bge.logic\n\n" -"\tco = bge.logic.getCurrentController()\n" -"\tcam = co.GetOwner()\n\n" -"\t# A sphere of radius 4.0 located at [x, y, z] = [1.0, 1.0, 1.0]\n" -"\tif (cam.sphereInsideFrustum([1.0, 1.0, 1.0], 4) != cam.OUTSIDE):\n" -"\t\t# Sphere is inside frustum !\n" -"\t\t# Do something useful !\n" -"\telse:\n" -"\t\t# Sphere is outside frustum\n" -) -{ - PyObject *pycenter; - float radius; - if (PyArg_ParseTuple(args, "Of:sphereInsideFrustum", &pycenter, &radius)) - { - MT_Point3 center; - if (PyVecTo(pycenter, center)) - { - return PyLong_FromLong(SphereInsideFrustum(center, radius)); /* new ref */ - } - } - - PyErr_SetString(PyExc_TypeError, "camera.sphereInsideFrustum(center, radius): KX_Camera, expected arguments: (center, radius)"); - - return NULL; -} - -KX_PYMETHODDEF_DOC_O(KX_Camera, boxInsideFrustum, -"boxInsideFrustum(box) -> Integer\n" -"\treturns INSIDE, OUTSIDE or INTERSECT if the given box is\n" -"\tinside/outside/intersects this camera's viewing frustum.\n\n" -"\tbox = a list of the eight (8) corners of the box (in world coordinates.)\n\n" -"\tExample:\n" -"\timport bge.logic\n\n" -"\tco = bge.logic.getCurrentController()\n" -"\tcam = co.GetOwner()\n\n" -"\tbox = []\n" -"\tbox.append([-1.0, -1.0, -1.0])\n" -"\tbox.append([-1.0, -1.0, 1.0])\n" -"\tbox.append([-1.0, 1.0, -1.0])\n" -"\tbox.append([-1.0, 1.0, 1.0])\n" -"\tbox.append([ 1.0, -1.0, -1.0])\n" -"\tbox.append([ 1.0, -1.0, 1.0])\n" -"\tbox.append([ 1.0, 1.0, -1.0])\n" -"\tbox.append([ 1.0, 1.0, 1.0])\n\n" -"\tif (cam.boxInsideFrustum(box) != cam.OUTSIDE):\n" -"\t\t# Box is inside/intersects frustum !\n" -"\t\t# Do something useful !\n" -"\telse:\n" -"\t\t# Box is outside the frustum !\n" -) -{ - unsigned int num_points = PySequence_Size(value); - if (num_points != 8) - { - PyErr_Format(PyExc_TypeError, "camera.boxInsideFrustum(box): KX_Camera, expected eight (8) points, got %d", num_points); - return NULL; - } - - MT_Point3 box[8]; - for (unsigned int p = 0; p < 8 ; p++) - { - PyObject *item = PySequence_GetItem(value, p); /* new ref */ - bool error = !PyVecTo(item, box[p]); - Py_DECREF(item); - if (error) - return NULL; - } - - return PyLong_FromLong(BoxInsideFrustum(box)); /* new ref */ -} - -KX_PYMETHODDEF_DOC_O(KX_Camera, pointInsideFrustum, -"pointInsideFrustum(point) -> Bool\n" -"\treturns 1 if the given point is inside this camera's viewing frustum.\n\n" -"\tpoint = The point to test (in world coordinates.)\n\n" -"\tExample:\n" -"\timport bge.logic\n\n" -"\tco = bge.logic.getCurrentController()\n" -"\tcam = co.GetOwner()\n\n" -"\t# Test point [0.0, 0.0, 0.0]" -"\tif (cam.pointInsideFrustum([0.0, 0.0, 0.0])):\n" -"\t\t# Point is inside frustum !\n" -"\t\t# Do something useful !\n" -"\telse:\n" -"\t\t# Box is outside the frustum !\n" -) -{ - MT_Point3 point; - if (PyVecTo(value, point)) - { - return PyLong_FromLong(PointInsideFrustum(point)); /* new ref */ - } - - PyErr_SetString(PyExc_TypeError, "camera.pointInsideFrustum(point): KX_Camera, expected point argument."); - return NULL; -} - -KX_PYMETHODDEF_DOC_NOARGS(KX_Camera, getCameraToWorld, -"getCameraToWorld() -> Matrix4x4\n" -"\treturns the camera to world transformation matrix, as a list of four lists of four values.\n\n" -"\tie: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]])\n" -) -{ - return PyObjectFrom(GetCameraToWorld()); /* new ref */ -} - -KX_PYMETHODDEF_DOC_NOARGS(KX_Camera, getWorldToCamera, -"getWorldToCamera() -> Matrix4x4\n" -"\treturns the world to camera transformation matrix, as a list of four lists of four values.\n\n" -"\tie: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]])\n" -) -{ - return PyObjectFrom(GetWorldToCamera()); /* new ref */ -} - -KX_PYMETHODDEF_DOC_VARARGS(KX_Camera, setViewport, -"setViewport(left, bottom, right, top)\n" -"Sets this camera's viewport\n") -{ - int left, bottom, right, top; - if (!PyArg_ParseTuple(args,"iiii:setViewport",&left, &bottom, &right, &top)) - return NULL; - - SetViewport(left, bottom, right, top); - Py_RETURN_NONE; -} - -KX_PYMETHODDEF_DOC_NOARGS(KX_Camera, setOnTop, -"setOnTop()\n" -"Sets this camera's viewport on top\n") -{ - class KX_Scene* scene = KX_GetActiveScene(); - scene->SetCameraOnTop(this); - Py_RETURN_NONE; -} - -PyObject *KX_Camera::pyattr_get_perspective(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_Camera* self = static_cast(self_v); - return PyBool_FromLong(self->m_camdata.m_perspective); -} - -int KX_Camera::pyattr_set_perspective(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_Camera* self = static_cast(self_v); - int param = PyObject_IsTrue( value ); - if (param == -1) { - PyErr_SetString(PyExc_AttributeError, "camera.perspective = bool: KX_Camera, expected True/False or 0/1"); - return PY_SET_ATTR_FAIL; - } - - self->m_camdata.m_perspective= param; - self->InvalidateProjectionMatrix(); - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_Camera::pyattr_get_lens(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_Camera* self = static_cast(self_v); - return PyFloat_FromDouble(self->m_camdata.m_lens); -} - -int KX_Camera::pyattr_set_lens(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_Camera* self = static_cast(self_v); - float param = PyFloat_AsDouble(value); - if (param == -1) { - PyErr_SetString(PyExc_AttributeError, "camera.lens = float: KX_Camera, expected a float greater than zero"); - return PY_SET_ATTR_FAIL; - } - - self->m_camdata.m_lens= param; - self->m_set_projection_matrix = false; - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_Camera::pyattr_get_fov(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_Camera* self = static_cast(self_v); - - float lens = self->m_camdata.m_lens; - float width = self->m_camdata.m_sensor_x; - float fov = 2.0f * atanf(0.5f * width / lens); - - return PyFloat_FromDouble(fov * MT_DEGS_PER_RAD); -} - -int KX_Camera::pyattr_set_fov(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_Camera* self = static_cast(self_v); - float fov = PyFloat_AsDouble(value); - if (fov <= 0.0f) { - PyErr_SetString(PyExc_AttributeError, "camera.fov = float: KX_Camera, expected a float greater than zero"); - return PY_SET_ATTR_FAIL; - } - - fov *= MT_RADS_PER_DEG; - float width = self->m_camdata.m_sensor_x; - float lens = width / (2.0f * tanf(0.5f * fov)); - - self->m_camdata.m_lens= lens; - self->m_set_projection_matrix = false; - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_Camera::pyattr_get_ortho_scale(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_Camera* self = static_cast(self_v); - return PyFloat_FromDouble(self->m_camdata.m_scale); -} - -int KX_Camera::pyattr_set_ortho_scale(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_Camera* self = static_cast(self_v); - float param = PyFloat_AsDouble(value); - if (param == -1) { - PyErr_SetString(PyExc_AttributeError, "camera.ortho_scale = float: KX_Camera, expected a float greater than zero"); - return PY_SET_ATTR_FAIL; - } - - self->m_camdata.m_scale= param; - self->m_set_projection_matrix = false; - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_Camera::pyattr_get_near(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_Camera* self = static_cast(self_v); - return PyFloat_FromDouble(self->m_camdata.m_clipstart); -} - -int KX_Camera::pyattr_set_near(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_Camera* self = static_cast(self_v); - float param = PyFloat_AsDouble(value); - if (param == -1) { - PyErr_SetString(PyExc_AttributeError, "camera.near = float: KX_Camera, expected a float greater than zero"); - return PY_SET_ATTR_FAIL; - } - - self->m_camdata.m_clipstart= param; - self->m_set_projection_matrix = false; - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_Camera::pyattr_get_far(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_Camera* self = static_cast(self_v); - return PyFloat_FromDouble(self->m_camdata.m_clipend); -} - -int KX_Camera::pyattr_set_far(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_Camera* self = static_cast(self_v); - float param = PyFloat_AsDouble(value); - if (param == -1) { - PyErr_SetString(PyExc_AttributeError, "camera.far = float: KX_Camera, expected a float greater than zero"); - return PY_SET_ATTR_FAIL; - } - - self->m_camdata.m_clipend= param; - self->m_set_projection_matrix = false; - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_Camera::pyattr_get_shift_x(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_Camera* self = static_cast(self_v); - return PyFloat_FromDouble(self->m_camdata.m_shift_x); -} - -int KX_Camera::pyattr_set_shift_x(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_Camera* self = static_cast(self_v); - float param = PyFloat_AsDouble(value); - if (param == -1) { - PyErr_SetString(PyExc_AttributeError, "camera.shift_x = float: KX_Camera, expected a float greater than zero"); - return PY_SET_ATTR_FAIL; - } - - self->m_camdata.m_shift_x = param; - self->m_set_projection_matrix = false; - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_Camera::pyattr_get_shift_y(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_Camera* self = static_cast(self_v); - return PyFloat_FromDouble(self->m_camdata.m_shift_y); -} - -int KX_Camera::pyattr_set_shift_y(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_Camera* self = static_cast(self_v); - float param = PyFloat_AsDouble(value); - if (param == -1) { - PyErr_SetString(PyExc_AttributeError, "camera.shift_y = float: KX_Camera, expected a float greater than zero"); - return PY_SET_ATTR_FAIL; - } - - self->m_camdata.m_shift_y = param; - self->m_set_projection_matrix = false; - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_Camera::pyattr_get_use_viewport(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_Camera* self = static_cast(self_v); - return PyBool_FromLong(self->GetViewport()); -} - -int KX_Camera::pyattr_set_use_viewport(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_Camera* self = static_cast(self_v); - int param = PyObject_IsTrue( value ); - if (param == -1) { - PyErr_SetString(PyExc_AttributeError, "camera.useViewport = bool: KX_Camera, expected True or False"); - return PY_SET_ATTR_FAIL; - } - self->EnableViewport((bool)param); - return PY_SET_ATTR_SUCCESS; -} - - -PyObject *KX_Camera::pyattr_get_projection_matrix(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_Camera* self = static_cast(self_v); - return PyObjectFrom(self->GetProjectionMatrix()); -} - -int KX_Camera::pyattr_set_projection_matrix(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_Camera* self = static_cast(self_v); - MT_Matrix4x4 mat; - if (!PyMatTo(value, mat)) - return PY_SET_ATTR_FAIL; - - self->SetProjectionMatrix(mat); - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_Camera::pyattr_get_modelview_matrix(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_Camera* self = static_cast(self_v); - return PyObjectFrom(self->GetWorldToCamera()); -} - -PyObject *KX_Camera::pyattr_get_camera_to_world(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_Camera* self = static_cast(self_v); - return PyObjectFrom(self->GetCameraToWorld()); -} - -PyObject *KX_Camera::pyattr_get_world_to_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_Camera* self = static_cast(self_v); - return PyObjectFrom(self->GetWorldToCamera()); -} - - -PyObject *KX_Camera::pyattr_get_INSIDE(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ return PyLong_FromLong(INSIDE); } -PyObject *KX_Camera::pyattr_get_OUTSIDE(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ return PyLong_FromLong(OUTSIDE); } -PyObject *KX_Camera::pyattr_get_INTERSECT(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ return PyLong_FromLong(INTERSECT); } - - -bool ConvertPythonToCamera(PyObject *value, KX_Camera **object, bool py_none_ok, const char *error_prefix) -{ - if (value==NULL) { - PyErr_Format(PyExc_TypeError, "%s, python pointer NULL, should never happen", error_prefix); - *object = NULL; - return false; - } - - if (value==Py_None) { - *object = NULL; - - if (py_none_ok) { - return true; - } else { - PyErr_Format(PyExc_TypeError, "%s, expected KX_Camera or a KX_Camera name, None is invalid", error_prefix); - return false; - } - } - - if (PyUnicode_Check(value)) { - STR_String value_str = _PyUnicode_AsString(value); - *object = KX_GetActiveScene()->FindCamera(value_str); - - if (*object) { - return true; - } else { - PyErr_Format(PyExc_ValueError, - "%s, requested name \"%s\" did not match any KX_Camera in this scene", - error_prefix, _PyUnicode_AsString(value)); - return false; - } - } - - if (PyObject_TypeCheck(value, &KX_Camera::Type)) { - *object = static_castBGE_PROXY_REF(value); - - /* sets the error */ - if (*object==NULL) { - PyErr_Format(PyExc_SystemError, "%s, " BGE_PROXY_ERROR_MSG, error_prefix); - return false; - } - - return true; - } - - *object = NULL; - - if (py_none_ok) { - PyErr_Format(PyExc_TypeError, "%s, expect a KX_Camera, a string or None", error_prefix); - } else { - PyErr_Format(PyExc_TypeError, "%s, expect a KX_Camera or a string", error_prefix); - } - - return false; -} - -KX_PYMETHODDEF_DOC_O(KX_Camera, getScreenPosition, -"getScreenPosition()\n" -) - -{ - MT_Vector3 vect; - KX_GameObject *obj = NULL; - - if (!PyVecTo(value, vect)) - { - PyErr_Clear(); - - if (ConvertPythonToGameObject(GetScene()->GetLogicManager(), value, &obj, true, "")) - { - PyErr_Clear(); - vect = MT_Vector3(obj->NodeGetWorldPosition()); - } - else - { - PyErr_SetString(PyExc_TypeError, "Error in getScreenPosition. Expected a Vector3 or a KX_GameObject or a string for a name of a KX_GameObject"); - return NULL; - } - } - - const GLint *viewport; - GLfloat vec[3]; - GLfloat win[3]; - GLfloat modelmatrix[4][4]; - GLfloat projmatrix[4][4]; - - MT_Matrix4x4 m_modelmatrix = this->GetWorldToCamera(); - MT_Matrix4x4 m_projmatrix = this->GetProjectionMatrix(); - - vect.getValue(vec); - m_modelmatrix.getValue((float*) modelmatrix); - m_projmatrix.getValue((float*) projmatrix); - - viewport = KX_GetActiveEngine()->GetCanvas()->GetViewPort(); - - gpuProject(vec, modelmatrix, projmatrix, viewport, win); - - vect[0] = (win[0] - viewport[0]) / viewport[2]; - vect[1] = (win[1] - viewport[1]) / viewport[3]; - - vect[1] = 1.0f - vect[1]; //to follow Blender window coordinate system (Top-Down) - - PyObject *ret = PyTuple_New(2); - if (ret) { - PyTuple_SET_ITEM(ret, 0, PyFloat_FromDouble(vect[0])); - PyTuple_SET_ITEM(ret, 1, PyFloat_FromDouble(vect[1])); - return ret; - } - - return NULL; -} - -KX_PYMETHODDEF_DOC_VARARGS(KX_Camera, getScreenVect, -"getScreenVect()\n" -) -{ - double x,y; - if (!PyArg_ParseTuple(args,"dd:getScreenVect",&x,&y)) - return NULL; - - y = 1.0 - y; //to follow Blender window coordinate system (Top-Down) - - const GLint *viewport; - GLfloat vec[3]; - GLfloat win[3]; - GLfloat modelmatrix[4][4]; - GLfloat projmatrix[4][4]; - - MT_Matrix4x4 m_modelmatrix = this->GetWorldToCamera(); - MT_Matrix4x4 m_projmatrix = this->GetProjectionMatrix(); - - m_modelmatrix.getValue((float*) modelmatrix); - m_projmatrix.getValue((float*) projmatrix); - - viewport = KX_GetActiveEngine()->GetCanvas()->GetViewPort(); - - vec[0] = x * viewport[2]; - vec[1] = y * viewport[3]; - - vec[0] += viewport[0]; - vec[1] += viewport[1]; - - vec[2] = 0.f; - - gpuUnProject(vec, modelmatrix, projmatrix, viewport, win); - - MT_Point3 campos = this->GetCameraLocation(); - MT_Point3 screenpos(win[0], win[1], win[2]); - MT_Vector3 vect = campos - screenpos; - vect.normalize(); - return PyObjectFrom(vect); -} - -KX_PYMETHODDEF_DOC_VARARGS(KX_Camera, getScreenRay, -"getScreenRay()\n" -) -{ - MT_Vector3 vect; - double x,y,dist; - char *propName = NULL; - - if (!PyArg_ParseTuple(args,"ddd|s:getScreenRay",&x,&y,&dist,&propName)) - return NULL; - - PyObject *argValue = PyTuple_New(2); - PyTuple_SET_ITEM(argValue, 0, PyFloat_FromDouble(x)); - PyTuple_SET_ITEM(argValue, 1, PyFloat_FromDouble(y)); - - if (!PyVecTo(PygetScreenVect(argValue), vect)) - { - Py_DECREF(argValue); - PyErr_SetString(PyExc_TypeError, - "Error in getScreenRay. Invalid 2D coordinate. " - "Expected a normalized 2D screen coordinate, " - "a distance and an optional property argument"); - return NULL; - } - Py_DECREF(argValue); - - dist = -dist; - vect += this->GetCameraLocation(); - - argValue = (propName?PyTuple_New(3):PyTuple_New(2)); - if (argValue) { - PyTuple_SET_ITEM(argValue, 0, PyObjectFrom(vect)); - PyTuple_SET_ITEM(argValue, 1, PyFloat_FromDouble(dist)); - if (propName) - PyTuple_SET_ITEM(argValue, 2, PyUnicode_FromString(propName)); - - PyObject *ret= this->PyrayCastTo(argValue,NULL); - Py_DECREF(argValue); - return ret; - } - - return NULL; -} -#endif diff --git a/source/gameengine/Ketsji/KX_Camera.h b/source/gameengine/Ketsji/KX_Camera.h deleted file mode 100644 index 8addf0b7aed..00000000000 --- a/source/gameengine/Ketsji/KX_Camera.h +++ /dev/null @@ -1,334 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_Camera.h - * \ingroup ketsji - * \brief Camera in the gameengine. Cameras are also used for views. - */ - -#ifndef __KX_CAMERA_H__ -#define __KX_CAMERA_H__ - - -#include "MT_Transform.h" -#include "MT_Matrix3x3.h" -#include "MT_Matrix4x4.h" -#include "MT_Vector3.h" -#include "MT_Point3.h" -#include "KX_GameObject.h" -#include "EXP_IntValue.h" -#include "RAS_CameraData.h" - -#ifdef WITH_PYTHON -/* utility conversion function */ -bool ConvertPythonToCamera(PyObject *value, KX_Camera **object, bool py_none_ok, const char *error_prefix); -#endif - -class KX_Camera : public KX_GameObject -{ - Py_Header -protected: - friend class KX_Scene; - /** Camera parameters (clips distances, focal length). These - * params are closely tied to Blender. In the gameengine, only the - * projection and modelview matrices are relevant. There's a - * conversion being done in the engine class. Why is it stored - * here? It doesn't really have a function here. */ - RAS_CameraData m_camdata; - - // Never used, I think... -// void MoveTo(const MT_Point3& movevec) -// { -#if 0 - MT_Transform camtrans; - camtrans.invert(m_trans1); - MT_Matrix3x3 camorient = camtrans.getBasis(); - camtrans.translate(camorient.inverse()*movevec); - m_trans1.invert(camtrans); -#endif -// } - - /** - * Storage for the projection matrix that is passed to the - * rasterizer. */ - MT_Matrix4x4 m_projection_matrix; - //MT_Matrix4x4 m_projection_matrix1; - - /** - * Storage for the modelview matrix that is passed to the - * rasterizer. */ - MT_Matrix4x4 m_modelview_matrix; - - /** - * true if the view frustum (modelview/projection matrix) - * has changed - the clip planes (m_planes) will have to be - * regenerated. - */ - bool m_dirty; - /** - * true if the frustum planes have been normalized. - */ - bool m_normalized; - - /** - * View Frustum clip planes. - */ - MT_Vector4 m_planes[6]; - - /** - * This camera is frustum culling. - * Some cameras (ie if the game was started from a non camera view should not cull.) - */ - bool m_frustum_culling; - - /** - * true if this camera has a valid projection matrix. - */ - bool m_set_projection_matrix; - - /** - * The center point of the frustum. - */ - MT_Point3 m_frustum_center; - MT_Scalar m_frustum_radius; - bool m_set_frustum_center; - - /** - * whether the camera should delete the node itself (only for shadow camera) - */ - bool m_delete_node; - - /** - * Extracts the camera clip frames from the projection and world-to-camera matrices. - */ - void ExtractClipPlanes(); - /** - * Normalize the camera clip frames. - */ - void NormalizeClipPlanes(); - /** - * Extracts the bound sphere of the view frustum. - */ - void ExtractFrustumSphere(); - /** - * return the clip plane - */ - MT_Vector4 *GetNormalizedClipPlanes() - { - ExtractClipPlanes(); - NormalizeClipPlanes(); - return m_planes; - } - -public: - - enum { INSIDE, INTERSECT, OUTSIDE }; - - KX_Camera(void* sgReplicationInfo,SG_Callbacks callbacks,const RAS_CameraData& camdata, bool frustum_culling = true, bool delete_node = false); - virtual ~KX_Camera(); - - /** - * Inherited from CValue -- return a new copy of this - * instance allocated on the heap. Ownership of the new - * object belongs with the caller. - */ - virtual CValue* - GetReplica( - ); - virtual void ProcessReplica(); - - MT_Transform GetWorldToCamera() const; - MT_Transform GetCameraToWorld() const; - - /** - * Not implemented. - */ - void CorrectLookUp(MT_Scalar speed); - const MT_Point3 GetCameraLocation() const; - - /* I want the camera orientation as well. */ - const MT_Quaternion GetCameraOrientation() const; - - /** Sets the projection matrix that is used by the rasterizer. */ - void SetProjectionMatrix(const MT_Matrix4x4 & mat); - - /** Sets the modelview matrix that is used by the rasterizer. */ - void SetModelviewMatrix(const MT_Matrix4x4 & mat); - - /** Gets the projection matrix that is used by the rasterizer. */ - const MT_Matrix4x4& GetProjectionMatrix() const; - - /** returns true if this camera has been set a projection matrix. */ - bool hasValidProjectionMatrix() const; - - /** Sets the validity of the projection matrix. Call this if you change camera - * data (eg lens, near plane, far plane) and require the projection matrix to be - * recalculated. - */ - void InvalidateProjectionMatrix(bool valid = false); - - /** Gets the modelview matrix that is used by the rasterizer. - * \warning If the Camera is a dynamic object then this method may return garbage. Use GetWorldToCamera() instead. - */ - const MT_Matrix4x4& GetModelviewMatrix() const; - - /** Gets the aperture. */ - float GetLens() const; - /** Gets the ortho scale. */ - float GetScale() const; - /** Gets the horizontal size of the sensor - for camera matching */ - float GetSensorWidth() const; - /** Gets the vertical size of the sensor - for camera matching */ - float GetSensorHeight() const; - /** Gets the mode FOV is calculating from sensor dimensions */ - short GetSensorFit() const; - /** Gets the horizontal shift of the sensor - for camera matching */ - float GetShiftHorizontal() const; - /** Gets the vertical shift of the sensor - for camera matching */ - float GetShiftVertical() const; - /** Gets the near clip distance. */ - float GetCameraNear() const; - /** Gets the far clip distance. */ - float GetCameraFar() const; - /** Gets the focal length (only used for stereo rendering) */ - float GetFocalLength() const; - /** Gets all camera data. */ - RAS_CameraData* GetCameraData(); - - /** - * Tests if the given sphere is inside this camera's view frustum. - * - * \param center The center of the sphere, in world coordinates. - * \param radius The radius of the sphere. - * \return INSIDE, INTERSECT, or OUTSIDE depending on the sphere's relation to the frustum. - */ - int SphereInsideFrustum(const MT_Point3& center, const MT_Scalar &radius); - /** - * Tests the given eight corners of a box with the view frustum. - * - * \param box a pointer to eight MT_Point3 representing the world coordinates of the corners of the box. - * \return INSIDE, INTERSECT, or OUTSIDE depending on the box's relation to the frustum. - */ - int BoxInsideFrustum(const MT_Point3 *box); - /** - * Tests the given point against the view frustum. - * \return true if the given point is inside or on the view frustum; false if it is outside. - */ - bool PointInsideFrustum(const MT_Point3& x); - - /** - * Gets this camera's culling status. - */ - bool GetFrustumCulling() const; - - /** - * Sets this camera's viewport status. - */ - void EnableViewport(bool viewport); - - /** - * Sets this camera's viewport. - */ - void SetViewport(int left, int bottom, int right, int top); - - /** - * Gets this camera's viewport status. - */ - bool GetViewport() const; - - /** - * Gets this camera's viewport left. - */ - int GetViewportLeft() const; - - /** - * Gets this camera's viewport bottom. - */ - int GetViewportBottom() const; - - /** - * Gets this camera's viewport right. - */ - int GetViewportRight() const; - - /** - * Gets this camera's viewport top. - */ - int GetViewportTop() const; - - virtual int GetGameObjectType() { return OBJ_CAMERA; } - -#ifdef WITH_PYTHON - KX_PYMETHOD_DOC_VARARGS(KX_Camera, sphereInsideFrustum); - KX_PYMETHOD_DOC_O(KX_Camera, boxInsideFrustum); - KX_PYMETHOD_DOC_O(KX_Camera, pointInsideFrustum); - - KX_PYMETHOD_DOC_NOARGS(KX_Camera, getCameraToWorld); - KX_PYMETHOD_DOC_NOARGS(KX_Camera, getWorldToCamera); - - KX_PYMETHOD_DOC_VARARGS(KX_Camera, setViewport); - KX_PYMETHOD_DOC_NOARGS(KX_Camera, setOnTop); - - KX_PYMETHOD_DOC_O(KX_Camera, getScreenPosition); - KX_PYMETHOD_DOC_VARARGS(KX_Camera, getScreenVect); - KX_PYMETHOD_DOC_VARARGS(KX_Camera, getScreenRay); - - static PyObject* pyattr_get_perspective(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_perspective(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - - static PyObject* pyattr_get_lens(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_lens(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_fov(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_fov(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_ortho_scale(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_ortho_scale(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_near(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_near(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_far(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_far(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_shift_x(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_shift_x(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_shift_y(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_shift_y(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - - static PyObject* pyattr_get_use_viewport(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_use_viewport(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - - static PyObject* pyattr_get_projection_matrix(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_projection_matrix(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - - static PyObject* pyattr_get_modelview_matrix(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_camera_to_world(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_world_to_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - - static PyObject* pyattr_get_INSIDE(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_OUTSIDE(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_INTERSECT(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); -#endif -}; - -#endif /* __KX_CAMERA_H__ */ diff --git a/source/gameengine/Ketsji/KX_CameraActuator.cpp b/source/gameengine/Ketsji/KX_CameraActuator.cpp deleted file mode 100644 index e488bf3c30a..00000000000 --- a/source/gameengine/Ketsji/KX_CameraActuator.cpp +++ /dev/null @@ -1,428 +0,0 @@ -/* - * KX_CameraActuator.cpp - * - * - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - * - */ - -/** \file gameengine/Ketsji/KX_CameraActuator.cpp - * \ingroup ketsji - */ - -#include "BLI_math_vector.h" - -#include "KX_CameraActuator.h" -#include -#include -#include "KX_GameObject.h" - -#include "EXP_PyObjectPlus.h" - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -KX_CameraActuator::KX_CameraActuator( - SCA_IObject* gameobj, - SCA_IObject *obj, - float hght, - float minhght, - float maxhght, - short axis, - float damping -): - SCA_IActuator(gameobj, KX_ACT_CAMERA), - m_ob (obj), - m_height (hght), - m_minHeight (minhght), - m_maxHeight (maxhght), - m_axis(axis), - m_damping (damping) -{ - if (m_ob) - m_ob->RegisterActuator(this); -} - -KX_CameraActuator::~KX_CameraActuator() -{ - if (m_ob) - m_ob->UnregisterActuator(this); -} - - CValue* -KX_CameraActuator:: -GetReplica( -) { - KX_CameraActuator* replica = new KX_CameraActuator(*this); - replica->ProcessReplica(); - return replica; -}; - -void KX_CameraActuator::ProcessReplica() -{ - if (m_ob) - m_ob->RegisterActuator(this); - SCA_IActuator::ProcessReplica(); -} - -bool KX_CameraActuator::UnlinkObject(SCA_IObject* clientobj) -{ - if (clientobj == m_ob) - { - // this object is being deleted, we cannot continue to track it. - m_ob = NULL; - return true; - } - return false; -} - - -void KX_CameraActuator::Relink(CTR_Map *obj_map) -{ - void **h_obj = (*obj_map)[m_ob]; - if (h_obj) { - if (m_ob) - m_ob->UnregisterActuator(this); - m_ob = (SCA_IObject*)(*h_obj); - m_ob->RegisterActuator(this); - } -} - -/* copied from blender BLI_math ... don't know if there's an equivalent */ - -static void Kx_VecUpMat3(float vec[3], float mat[3][3], short axis) -{ - - // Construct a camera matrix s.t. the specified axis - - // maps to the given vector (*vec). Also defines the rotation - - // about this axis by mapping one of the other axis to the y-axis. - - - float inp; - short cox = 0, coy = 0, coz = 0; - - /* up range has no meaning, is not really up! - * see: VecUpMat3old - */ - - if (axis==0) { - cox= 0; coy= 1; coz= 2; /* Y up Z tr */ - } - if (axis==1) { - cox= 1; coy= 2; coz= 0; /* Z up X tr */ - } - if (axis==2) { - cox= 2; coy= 0; coz= 1; /* X up Y tr */ - } - if (axis==3) { - cox= 0; coy= 1; coz= 2; /* Y op -Z tr */ - vec[0] = -vec[0]; - vec[1] = -vec[1]; - vec[2] = -vec[2]; - } - if (axis==4) { - cox= 1; coy= 0; coz= 2; /* */ - } - if (axis==5) { - cox= 2; coy= 1; coz= 0; /* Y up X tr */ - } - - mat[coz][0] = vec[0]; - mat[coz][1] = vec[1]; - mat[coz][2] = vec[2]; - if (normalize_v3((float *)mat[coz]) == 0.f) { - /* this is a very abnormal situation: the camera has reach the object center exactly - * We will choose a completely arbitrary direction */ - mat[coz][0] = 1.0f; - mat[coz][1] = 0.0f; - mat[coz][2] = 0.0f; - } - - inp = mat[coz][2]; - mat[coy][0] = - inp * mat[coz][0]; - mat[coy][1] = - inp * mat[coz][1]; - mat[coy][2] = 1.0f - inp * mat[coz][2]; - - if (normalize_v3((float *)mat[coy]) == 0.f) { - /* the camera is vertical, chose the y axis arbitrary */ - mat[coy][0] = 0.f; - mat[coy][1] = 1.f; - mat[coy][2] = 0.f; - } - - cross_v3_v3v3(mat[cox], mat[coy], mat[coz]); -} - -bool KX_CameraActuator::Update(double curtime, bool frame) -{ - /* wondering... is it really necessary/desirable to suppress negative */ - /* events here? */ - bool bNegativeEvent = IsNegativeEvent(); - RemoveAllEvents(); - - if (bNegativeEvent || !m_ob) - return false; - - KX_GameObject *obj = (KX_GameObject*) GetParent(); - MT_Point3 from = obj->NodeGetWorldPosition(); - MT_Matrix3x3 frommat = obj->NodeGetWorldOrientation(); - /* These casts are _very_ dangerous!!! */ - MT_Point3 lookat = ((KX_GameObject*)m_ob)->NodeGetWorldPosition(); - MT_Matrix3x3 actormat = ((KX_GameObject*)m_ob)->NodeGetWorldOrientation(); - - float fp1[3]={0}, fp2[3]={0}, rc[3]; - float inp, fac; //, factor = 0.0; /* some factor... */ - float mindistsq, maxdistsq, distsq; - float mat[3][3]; - - /* The rules: */ - /* CONSTRAINT 1: not implemented */ - /* CONSTRAINT 2: can camera see actor? */ - /* CONSTRAINT 3: fixed height relative to floor below actor. */ - /* CONSTRAINT 4: camera rotates behind actor */ - /* CONSTRAINT 5: minimum / maximum distance */ - /* CONSTRAINT 6: again: fixed height relative to floor below actor */ - /* CONSTRAINT 7: track to floor below actor */ - /* CONSTRAINT 8: look a little bit left or right, depending on how the - * - * character is looking (horizontal x) - */ - - /* ...and then set the camera position. Since we assume the parent of */ - /* this actuator is always a camera, just set the parent position and */ - /* rotation. We do not check whether we really have a camera as parent. */ - /* It may be better to turn this into a general tracking actuator later */ - /* on, since lots of plausible relations can be filled in here. */ - - /* ... set up some parameters ... */ - /* missing here: the 'floorloc' of the actor's shadow */ - - mindistsq= m_minHeight*m_minHeight; - maxdistsq= m_maxHeight*m_maxHeight; - - /* C1: not checked... is a future option */ - - /* C2: blender test_visibility function. Can this be a ray-test? */ - - /* C3: fixed height */ - from[2] = (15.0f * from[2] + lookat[2] + m_height) / 16.0f; - - - /* C4: camera behind actor */ - switch (m_axis) { - case OB_POSX: - /* X */ - fp1[0] = actormat[0][0]; - fp1[1] = actormat[1][0]; - fp1[2] = actormat[2][0]; - - fp2[0] = frommat[0][0]; - fp2[1] = frommat[1][0]; - fp2[2] = frommat[2][0]; - break; - case OB_POSY: - /* Y */ - fp1[0] = actormat[0][1]; - fp1[1] = actormat[1][1]; - fp1[2] = actormat[2][1]; - - fp2[0] = frommat[0][1]; - fp2[1] = frommat[1][1]; - fp2[2] = frommat[2][1]; - break; - case OB_NEGX: - /* -X */ - fp1[0] = -actormat[0][0]; - fp1[1] = -actormat[1][0]; - fp1[2] = -actormat[2][0]; - - fp2[0] = frommat[0][0]; - fp2[1] = frommat[1][0]; - fp2[2] = frommat[2][0]; - break; - case OB_NEGY: - /* -Y */ - fp1[0] = -actormat[0][1]; - fp1[1] = -actormat[1][1]; - fp1[2] = -actormat[2][1]; - - fp2[0] = frommat[0][1]; - fp2[1] = frommat[1][1]; - fp2[2] = frommat[2][1]; - break; - default: - assert(0); - break; - } - - inp = fp1[0]*fp2[0] + fp1[1]*fp2[1] + fp1[2]*fp2[2]; - fac = (-1.0f + inp) * m_damping; - - from[0] += fac * fp1[0]; - from[1] += fac * fp1[1]; - from[2] += fac * fp1[2]; - - /* only for it lies: cross test and perpendicular bites up */ - if (inp < 0.0f) { - /* Don't do anything if the cross product is too small. - * The camera up-axis becomes unstable and starts to oscillate. - * The 0.01f threshold is arbitrary but seems to work well in practice. */ - float cross = fp1[0] * fp2[1] - fp1[1] * fp2[0]; - if (cross > 0.01f) { - from[0] -= fac * fp1[1]; - from[1] += fac * fp1[0]; - } - else if (cross < -0.01f) { - from[0] += fac * fp1[1]; - from[1] -= fac * fp1[0]; - } - } - - /* CONSTRAINT 5: minimum / maximum distance */ - - rc[0] = (lookat[0]-from[0]); - rc[1] = (lookat[1]-from[1]); - rc[2] = (lookat[2]-from[2]); - distsq = rc[0]*rc[0] + rc[1]*rc[1] + rc[2]*rc[2]; - - if (distsq > maxdistsq) { - distsq = 0.15f * (distsq - maxdistsq) / distsq; - - from[0] += distsq*rc[0]; - from[1] += distsq*rc[1]; - from[2] += distsq*rc[2]; - } - else if (distsq < mindistsq) { - distsq = 0.15f * (mindistsq - distsq) / mindistsq; - - from[0] -= distsq*rc[0]; - from[1] -= distsq*rc[1]; - from[2] -= distsq*rc[2]; - } - - - /* CONSTRAINT 7: track to floor below actor */ - rc[0] = (lookat[0]-from[0]); - rc[1] = (lookat[1]-from[1]); - rc[2] = (lookat[2]-from[2]); - Kx_VecUpMat3(rc, mat, 3); /* y up Track -z */ - - - - - /* now set the camera position and rotation */ - - obj->NodeSetLocalPosition(from); - - actormat[0][0] = mat[0][0]; actormat[0][1] = mat[1][0]; actormat[0][2] = mat[2][0]; - actormat[1][0] = mat[0][1]; actormat[1][1] = mat[1][1]; actormat[1][2] = mat[2][1]; - actormat[2][0] = mat[0][2]; actormat[2][1] = mat[1][2]; actormat[2][2] = mat[2][2]; - obj->NodeSetLocalOrientation(actormat); - - return true; -} - -CValue *KX_CameraActuator::findObject(const char *obName) -{ - /* hook to object system */ - return NULL; -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject KX_CameraActuator::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_CameraActuator", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &SCA_IActuator::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_CameraActuator::Methods[] = { - {NULL, NULL} //Sentinel -}; - -PyAttributeDef KX_CameraActuator::Attributes[] = { - KX_PYATTRIBUTE_FLOAT_RW("min",-FLT_MAX,FLT_MAX,KX_CameraActuator,m_minHeight), - KX_PYATTRIBUTE_FLOAT_RW("max",-FLT_MAX,FLT_MAX,KX_CameraActuator,m_maxHeight), - KX_PYATTRIBUTE_FLOAT_RW("height",-FLT_MAX,FLT_MAX,KX_CameraActuator,m_height), - KX_PYATTRIBUTE_SHORT_RW("axis", 0, 5, true, KX_CameraActuator, m_axis), - KX_PYATTRIBUTE_RW_FUNCTION("object", KX_CameraActuator, pyattr_get_object, pyattr_set_object), - KX_PYATTRIBUTE_FLOAT_RW("damping",0.f,10.f,KX_CameraActuator,m_damping), - {NULL} -}; - -PyObject *KX_CameraActuator::pyattr_get_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_CameraActuator* self = static_cast(self_v); - if (self->m_ob==NULL) - Py_RETURN_NONE; - else - return self->m_ob->GetProxy(); -} - -int KX_CameraActuator::pyattr_set_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_CameraActuator* self = static_cast(self_v); - KX_GameObject *gameobj; - - if (!ConvertPythonToGameObject(self->GetLogicManager(), value, &gameobj, true, "actuator.object = value: KX_CameraActuator")) - return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error - - if (self->m_ob) - self->m_ob->UnregisterActuator(self); - - if ((self->m_ob = (SCA_IObject*)gameobj)) - self->m_ob->RegisterActuator(self); - - return PY_SET_ATTR_SUCCESS; -} - -#endif // WITH_PYTHON - -/* eof */ diff --git a/source/gameengine/Ketsji/KX_CameraActuator.h b/source/gameengine/Ketsji/KX_CameraActuator.h deleted file mode 100644 index fb0a7d88dd9..00000000000 --- a/source/gameengine/Ketsji/KX_CameraActuator.h +++ /dev/null @@ -1,138 +0,0 @@ -/* - * KX_CameraActuator.h - * - * - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_CameraActuator.h - * \ingroup ketsji - */ - -#ifndef __KX_CAMERAACTUATOR_H__ -#define __KX_CAMERAACTUATOR_H__ - -#include "SCA_IActuator.h" -#include "MT_Scalar.h" -#include "SCA_LogicManager.h" - -/** - * The camera actuator does a Robbie Muller perspective for you. This is a - * weird set of rules that positions the camera sort of behind the object, - * tracking, while avoiding any objects between the 'ideal' position and the - * actor being tracked. - */ - - -class KX_CameraActuator : public SCA_IActuator -{ - Py_Header -private : - /** Object that will be tracked. */ - SCA_IObject *m_ob; - - /** height (float), */ - //const MT_Scalar m_height; - /** min (float), */ - //const MT_Scalar m_minHeight; - /** max (float), */ - //const MT_Scalar m_maxHeight; - - /** height (float), */ - float m_height; - - /** min (float), */ - float m_minHeight; - - /** max (float), */ - float m_maxHeight; - - /** axis the camera tries to get behind: +x/+y/-x/-y */ - short m_axis; - - /** damping (float), */ - float m_damping; - - /* get the KX_IGameObject with this name */ - CValue *findObject(const char *obName); - - /* parse x or y to a toggle pick */ - bool string2axischoice(const char *axisString); - - public: - static STR_String X_AXIS_STRING; - static STR_String Y_AXIS_STRING; - - /** - * Set the bool toggle to true to use x lock, false for y lock - */ - KX_CameraActuator( - - SCA_IObject *gameobj, - //const CValue *ob, - SCA_IObject *ob, - float hght, - float minhght, - float maxhght, - short axis, - float damping - ); - - - ~KX_CameraActuator(); - - - - /** Methods Inherited from CValue */ - CValue* GetReplica(); - virtual void ProcessReplica(); - - - /** Methods inherited from SCA_IActuator */ - virtual bool Update( - double curtime, - bool frame - ); - virtual bool UnlinkObject(SCA_IObject* clientobj); - - /** Methods inherited from SCA_ILogicBrick */ - virtual void Relink(CTR_Map *obj_map); - -#ifdef WITH_PYTHON - - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - - /* set object to look at */ - static PyObject* pyattr_get_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - -#endif /* WITH_PYTHON */ - -}; - -#endif /* __KX_CAMERAACTUATOR_H__ */ diff --git a/source/gameengine/Ketsji/KX_CameraIpoSGController.cpp b/source/gameengine/Ketsji/KX_CameraIpoSGController.cpp deleted file mode 100644 index a1c726209e1..00000000000 --- a/source/gameengine/Ketsji/KX_CameraIpoSGController.cpp +++ /dev/null @@ -1,126 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_CameraIpoSGController.cpp - * \ingroup ketsji - */ - - -#include "KX_CameraIpoSGController.h" -#include "KX_ScalarInterpolator.h" -#include "KX_Camera.h" -#include "RAS_CameraData.h" - -#if defined(_WIN64) -typedef unsigned __int64 uint_ptr; -#else -typedef unsigned long uint_ptr; -#endif - -bool KX_CameraIpoSGController::Update(double currentTime) -{ - if (m_modified) - { - T_InterpolatorList::iterator i; - for (i = m_interpolators.begin(); !(i == m_interpolators.end()); ++i) { - (*i)->Execute(m_ipotime); - } - - SG_Spatial* ob = (SG_Spatial*)m_pObject; - KX_Camera* kxcamera = (KX_Camera*) ob->GetSGClientObject(); - RAS_CameraData* camdata = kxcamera->GetCameraData(); - - if (m_modify_lens) - camdata->m_lens = m_lens; - - if (m_modify_clipstart ) - camdata->m_clipstart = m_clipstart; - - if (m_modify_clipend) - camdata->m_clipend = m_clipend; - - if (m_modify_lens || m_modify_clipstart || m_modify_clipend) - kxcamera->InvalidateProjectionMatrix(); - - m_modified=false; - } - return false; -} - - -void KX_CameraIpoSGController::AddInterpolator(KX_IInterpolator* interp) -{ - this->m_interpolators.push_back(interp); -} - -SG_Controller* KX_CameraIpoSGController::GetReplica(class SG_Node* destnode) -{ - KX_CameraIpoSGController* iporeplica = new KX_CameraIpoSGController(*this); - // clear object that ipo acts on - iporeplica->ClearObject(); - - // dirty hack, ask Gino for a better solution in the ipo implementation - // hacken en zagen, in what we call datahiding, not written for replication :( - - T_InterpolatorList oldlist = m_interpolators; - iporeplica->m_interpolators.clear(); - - T_InterpolatorList::iterator i; - for (i = oldlist.begin(); !(i == oldlist.end()); ++i) { - KX_ScalarInterpolator* copyipo = new KX_ScalarInterpolator(*((KX_ScalarInterpolator*)*i)); - iporeplica->AddInterpolator(copyipo); - - MT_Scalar* scaal = ((KX_ScalarInterpolator*)*i)->GetTarget(); - uint_ptr orgbase = (uint_ptr)this; - uint_ptr orgloc = (uint_ptr)scaal; - uint_ptr offset = orgloc-orgbase; - uint_ptr newaddrbase = (uint_ptr)iporeplica + offset; - MT_Scalar* blaptr = (MT_Scalar*) newaddrbase; - copyipo->SetNewTarget((MT_Scalar*)blaptr); - } - - return iporeplica; -} - -KX_CameraIpoSGController::~KX_CameraIpoSGController() -{ - - T_InterpolatorList::iterator i; - for (i = m_interpolators.begin(); !(i == m_interpolators.end()); ++i) { - delete (*i); - } - -} - - void -KX_CameraIpoSGController::SetOption( - int option, - int value) -{ - /* Setting options */ - -} diff --git a/source/gameengine/Ketsji/KX_CameraIpoSGController.h b/source/gameengine/Ketsji/KX_CameraIpoSGController.h deleted file mode 100644 index 1f6f211622c..00000000000 --- a/source/gameengine/Ketsji/KX_CameraIpoSGController.h +++ /dev/null @@ -1,97 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_CameraIpoSGController.h - * \ingroup ketsji - */ - -#ifndef __KX_CAMERAIPOSGCONTROLLER_H__ -#define __KX_CAMERAIPOSGCONTROLLER_H__ - -#include "SG_Controller.h" -#include "SG_Spatial.h" - -#include "KX_IInterpolator.h" - -struct RAS_CameraData; - -class KX_CameraIpoSGController : public SG_Controller -{ -public: - MT_Scalar m_lens; - MT_Scalar m_clipstart; - MT_Scalar m_clipend; - -private: - T_InterpolatorList m_interpolators; - unsigned short m_modify_lens : 1; - unsigned short m_modify_clipstart : 1; - unsigned short m_modify_clipend : 1; - bool m_modified; - - double m_ipotime; -public: - KX_CameraIpoSGController() : - m_modify_lens(false), - m_modify_clipstart(false), - m_modify_clipend(false), - m_modified(true), - m_ipotime(0.0) - {} - - ~KX_CameraIpoSGController(); - SG_Controller* GetReplica(class SG_Node* destnode); - bool Update(double time); - - void - SetOption( - int option, - int value - ); - - void SetSimulatedTime(double time) { - m_ipotime = time; - m_modified = true; - } - void SetModifyLens(bool modify) { - m_modify_lens = modify; - } - void SetModifyClipEnd(bool modify) { - m_modify_clipend = modify; - } - void SetModifyClipStart(bool modify) { - m_modify_clipstart = modify; - } - void AddInterpolator(KX_IInterpolator* interp); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_CameraIpoSGController") -#endif -}; - -#endif /* __KX_CAMERAIPOSGCONTROLLER_H__ */ diff --git a/source/gameengine/Ketsji/KX_CharacterWrapper.cpp b/source/gameengine/Ketsji/KX_CharacterWrapper.cpp deleted file mode 100644 index 44f06a9f1eb..00000000000 --- a/source/gameengine/Ketsji/KX_CharacterWrapper.cpp +++ /dev/null @@ -1,167 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_CharacterWrapper.cpp - * \ingroup ketsji - */ - -#include "KX_CharacterWrapper.h" -#include "PHY_ICharacter.h" -#include "KX_PyMath.h" -#include "BLI_utildefines.h" - -KX_CharacterWrapper::KX_CharacterWrapper(PHY_ICharacter* character) : - PyObjectPlus(), - m_character(character) -{ -} - -KX_CharacterWrapper::~KX_CharacterWrapper() -{ -} - -#ifdef WITH_PYTHON - -PyTypeObject KX_CharacterWrapper::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_CharacterWrapper", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &PyObjectPlus::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyAttributeDef KX_CharacterWrapper::Attributes[] = { - KX_PYATTRIBUTE_RO_FUNCTION("onGround", KX_CharacterWrapper, pyattr_get_onground), - KX_PYATTRIBUTE_RW_FUNCTION("gravity", KX_CharacterWrapper, pyattr_get_gravity, pyattr_set_gravity), - KX_PYATTRIBUTE_RW_FUNCTION("maxJumps", KX_CharacterWrapper, pyattr_get_max_jumps, pyattr_set_max_jumps), - KX_PYATTRIBUTE_RO_FUNCTION("jumpCount", KX_CharacterWrapper, pyattr_get_jump_count), - KX_PYATTRIBUTE_RW_FUNCTION("walkDirection", KX_CharacterWrapper, pyattr_get_walk_dir, pyattr_set_walk_dir), - { NULL } //Sentinel -}; - -PyObject *KX_CharacterWrapper::pyattr_get_onground(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_CharacterWrapper* self = static_cast(self_v); - - return PyBool_FromLong(self->m_character->OnGround()); -} - -PyObject *KX_CharacterWrapper::pyattr_get_gravity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_CharacterWrapper* self = static_cast(self_v); - - return PyFloat_FromDouble(self->m_character->GetGravity()); -} - -int KX_CharacterWrapper::pyattr_set_gravity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_CharacterWrapper* self = static_cast(self_v); - double param = PyFloat_AsDouble(value); - - if (param == -1) - { - PyErr_SetString(PyExc_ValueError, "KX_CharacterWrapper.gravity: expected a float"); - return PY_SET_ATTR_FAIL; - } - - self->m_character->SetGravity((float)param); - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_CharacterWrapper::pyattr_get_max_jumps(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_CharacterWrapper* self = static_cast(self_v); - - return PyLong_FromLong(self->m_character->GetMaxJumps()); -} - -int KX_CharacterWrapper::pyattr_set_max_jumps(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_CharacterWrapper* self = static_cast(self_v); - long param = PyLong_AsLong(value); - - if (param == -1) - { - PyErr_SetString(PyExc_ValueError, "KX_CharacterWrapper.maxJumps: expected an integer"); - return PY_SET_ATTR_FAIL; - } - - CLAMP(param, 0, 255); - - self->m_character->SetMaxJumps(param); - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_CharacterWrapper::pyattr_get_jump_count(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_CharacterWrapper* self = static_cast(self_v); - - return PyLong_FromLong(self->m_character->GetJumpCount()); -} - -PyObject *KX_CharacterWrapper::pyattr_get_walk_dir(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_CharacterWrapper* self = static_cast(self_v); - - return PyObjectFrom(self->m_character->GetWalkDirection()); -} - -int KX_CharacterWrapper::pyattr_set_walk_dir(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_CharacterWrapper* self = static_cast(self_v); - MT_Vector3 dir; - if (!PyVecTo(value, dir)) { - PyErr_SetString(PyExc_TypeError, "KX_CharacterWrapper.walkDirection: expected a vector"); - return PY_SET_ATTR_FAIL; - } - - self->m_character->SetWalkDirection(dir); - return PY_SET_ATTR_SUCCESS; -} - -PyMethodDef KX_CharacterWrapper::Methods[] = { - KX_PYMETHODTABLE_NOARGS(KX_CharacterWrapper, jump), - {NULL,NULL} //Sentinel -}; - -KX_PYMETHODDEF_DOC_NOARGS(KX_CharacterWrapper, jump, - "jump()\n" - "makes the character jump.\n") -{ - m_character->Jump(); - - Py_RETURN_NONE; -} - -#endif // WITH_PYTHON diff --git a/source/gameengine/Ketsji/KX_CharacterWrapper.h b/source/gameengine/Ketsji/KX_CharacterWrapper.h deleted file mode 100644 index dd7ba680ec7..00000000000 --- a/source/gameengine/Ketsji/KX_CharacterWrapper.h +++ /dev/null @@ -1,40 +0,0 @@ - -/** \file KX_CharacterWrapper.h - * \ingroup ketsji - */ - -#ifndef __KX_CHARACTERWRAPPER_H__ -#define __KX_CHARACTERWRAPPER_H__ - -#include "EXP_Value.h" -#include "PHY_DynamicTypes.h" -class PHY_ICharacter; - - -///Python interface to character physics -class KX_CharacterWrapper : public PyObjectPlus -{ - Py_Header - -public: - KX_CharacterWrapper(PHY_ICharacter* character); - virtual ~KX_CharacterWrapper(); -#ifdef WITH_PYTHON - KX_PYMETHOD_DOC_NOARGS(KX_CharacterWrapper, jump); - - static PyObject* pyattr_get_onground(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - - static PyObject* pyattr_get_gravity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_gravity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_max_jumps(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_max_jumps(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_jump_count(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_walk_dir(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_walk_dir(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); -#endif // WITH_PYTHON - -private: - PHY_ICharacter* m_character; -}; - -#endif /* __KX_CHARACTERWRAPPER_H__ */ diff --git a/source/gameengine/Ketsji/KX_ClientObjectInfo.h b/source/gameengine/Ketsji/KX_ClientObjectInfo.h deleted file mode 100644 index 81ae5b58009..00000000000 --- a/source/gameengine/Ketsji/KX_ClientObjectInfo.h +++ /dev/null @@ -1,84 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_ClientObjectInfo.h - * \ingroup ketsji - */ - -#ifndef __KX_CLIENTOBJECTINFO_H__ -#define __KX_CLIENTOBJECTINFO_H__ - -/* Note, the way this works with/without sumo is a bit odd */ - -#include - -class SCA_ISensor; -class KX_GameObject; -/** - * Client Type and Additional Info. This structure can be use instead of a bare void* pointer, for safeness, and additional info for callbacks - */ -struct KX_ClientObjectInfo -{ - enum clienttype { - STATIC, - ACTOR, - RESERVED1, - SENSOR, - OBSENSOR, - OBACTORSENSOR - } m_type; - KX_GameObject* m_gameobject; - std::list m_sensors; -public: - KX_ClientObjectInfo(KX_GameObject *gameobject, clienttype type = STATIC) : - m_type(type), - m_gameobject(gameobject) - {} - - KX_ClientObjectInfo(const KX_ClientObjectInfo ©) : - m_type(copy.m_type), - m_gameobject(copy.m_gameobject) - { - } - - virtual ~KX_ClientObjectInfo() {} - - virtual bool hasCollisionCallback() - { - return m_sensors.size() != 0; - } - - bool isActor() { return m_type <= ACTOR; } - bool isSensor() { return m_type >= SENSOR && m_type <= OBACTORSENSOR; } - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_ClientObjectInfo") -#endif -}; - -#endif /* __KX_CLIENTOBJECTINFO_H__ */ diff --git a/source/gameengine/Ketsji/KX_ConstraintActuator.cpp b/source/gameengine/Ketsji/KX_ConstraintActuator.cpp deleted file mode 100644 index 27c074393b4..00000000000 --- a/source/gameengine/Ketsji/KX_ConstraintActuator.cpp +++ /dev/null @@ -1,629 +0,0 @@ -/* - * Apply a constraint to a position or rotation value - * - * - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_ConstraintActuator.cpp - * \ingroup ketsji - */ - - -#include "SCA_IActuator.h" -#include "KX_ConstraintActuator.h" -#include "SCA_IObject.h" -#include "MT_Point3.h" -#include "MT_Matrix3x3.h" -#include "KX_GameObject.h" -#include "KX_RayCast.h" -#include "KX_PythonInit.h" // KX_GetActiveScene -#include "RAS_MeshObject.h" - -#include - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -KX_ConstraintActuator::KX_ConstraintActuator(SCA_IObject *gameobj, - int posDampTime, - int rotDampTime, - float minBound, - float maxBound, - float refDir[3], - int locrotxyz, - int time, - int option, - char *property) : - SCA_IActuator(gameobj, KX_ACT_CONSTRAINT), - m_refDirVector(refDir), - m_currentTime(0) -{ - m_refDirection[0] = refDir[0]; - m_refDirection[1] = refDir[1]; - m_refDirection[2] = refDir[2]; - m_posDampTime = posDampTime; - m_rotDampTime = rotDampTime; - m_locrot = locrotxyz; - m_option = option; - m_activeTime = time; - if (property) { - m_property = property; - } else { - m_property = ""; - } - /* The units of bounds are determined by the type of constraint. To */ - /* make the constraint application easier and more transparent later on, */ - /* I think converting the bounds to the applicable domain makes more */ - /* sense. */ - switch (m_locrot) { - case KX_ACT_CONSTRAINT_ORIX: - case KX_ACT_CONSTRAINT_ORIY: - case KX_ACT_CONSTRAINT_ORIZ: - { - MT_Scalar len = m_refDirVector.length(); - if (MT_fuzzyZero(len)) { - // missing a valid direction - std::cout << "WARNING: Constraint actuator " << GetName() << ": There is no valid reference direction!" << std::endl; - m_locrot = KX_ACT_CONSTRAINT_NODEF; - } else { - m_refDirection[0] /= len; - m_refDirection[1] /= len; - m_refDirection[2] /= len; - m_refDirVector /= len; - } - m_minimumBound = cosf(minBound); - m_maximumBound = cosf(maxBound); - m_minimumSine = sinf(minBound); - m_maximumSine = sinf(maxBound); - } - break; - default: - m_minimumBound = minBound; - m_maximumBound = maxBound; - m_minimumSine = 0.f; - m_maximumSine = 0.f; - break; - } - -} /* End of constructor */ - -KX_ConstraintActuator::~KX_ConstraintActuator() -{ - // there's nothing to be done here, really.... -} /* end of destructor */ - -bool KX_ConstraintActuator::RayHit(KX_ClientObjectInfo *client, KX_RayCast *result, void *UNUSED(data)) -{ - - m_hitObject = client->m_gameobject; - - bool bFound = false; - - if (m_property.IsEmpty()) - { - bFound = true; - } - else - { - if (m_option & KX_ACT_CONSTRAINT_MATERIAL) { - for (unsigned int i = 0; i < m_hitObject->GetMeshCount(); ++i) { - RAS_MeshObject *meshObj = m_hitObject->GetMesh(i); - for (unsigned int j = 0; j < meshObj->NumMaterials(); ++j) { - bFound = strcmp(m_property.ReadPtr(), meshObj->GetMaterialName(j).ReadPtr() + 2) == 0; - if (bFound) - break; - } - } - } - else { - bFound = m_hitObject->GetProperty(m_property) != NULL; - } - } - // update the hit status - result->m_hitFound = bFound; - // stop looking - return true; -} - -/* This function is used to pre-filter the object before casting the ray on them. - * This is useful for "X-Ray" option when we want to see "through" unwanted object. - */ -bool KX_ConstraintActuator::NeedRayCast(KX_ClientObjectInfo *client, void *UNUSED(data)) -{ - if (client->m_type > KX_ClientObjectInfo::ACTOR) - { - // Unknown type of object, skip it. - // Should not occur as the sensor objects are filtered in RayTest() - printf("Invalid client type %d found in ray casting\n", client->m_type); - return false; - } - // no X-Ray function yet - return true; -} - -bool KX_ConstraintActuator::Update(double curtime, bool frame) -{ - - bool result = false; - bool bNegativeEvent = IsNegativeEvent(); - RemoveAllEvents(); - - if (!bNegativeEvent) { - /* Constraint clamps the values to the specified range, with a sort of */ - /* low-pass filtered time response, if the damp time is unequal to 0. */ - - /* Having to retrieve location/rotation and setting it afterwards may not */ - /* be efficient enough... Something to look at later. */ - KX_GameObject *obj = (KX_GameObject*) GetParent(); - MT_Point3 position = obj->NodeGetWorldPosition(); - MT_Point3 newposition; - MT_Vector3 normal, direction, refDirection; - MT_Matrix3x3 rotation = obj->NodeGetWorldOrientation(); - MT_Scalar filter, newdistance, cosangle; - int axis, sign; - - if (m_posDampTime) { - filter = m_posDampTime/(1.0f+m_posDampTime); - } else { - filter = 0.0f; - } - switch (m_locrot) { - case KX_ACT_CONSTRAINT_ORIX: - case KX_ACT_CONSTRAINT_ORIY: - case KX_ACT_CONSTRAINT_ORIZ: - switch (m_locrot) { - case KX_ACT_CONSTRAINT_ORIX: - direction[0] = rotation[0][0]; - direction[1] = rotation[1][0]; - direction[2] = rotation[2][0]; - axis = 0; - break; - case KX_ACT_CONSTRAINT_ORIY: - direction[0] = rotation[0][1]; - direction[1] = rotation[1][1]; - direction[2] = rotation[2][1]; - axis = 1; - break; - default: - direction[0] = rotation[0][2]; - direction[1] = rotation[1][2]; - direction[2] = rotation[2][2]; - axis = 2; - break; - } - if ((m_maximumBound < (1.0f-FLT_EPSILON)) || (m_minimumBound < (1.0f-FLT_EPSILON))) { - // reference direction needs to be evaluated - // 1. get the cosine between current direction and target - cosangle = direction.dot(m_refDirVector); - if (cosangle >= (m_maximumBound-FLT_EPSILON) && cosangle <= (m_minimumBound+FLT_EPSILON)) { - // no change to do - result = true; - goto CHECK_TIME; - } - // 2. define a new reference direction - // compute local axis with reference direction as X and - // Y in direction X refDirection plane - MT_Vector3 zaxis = m_refDirVector.cross(direction); - if (MT_fuzzyZero2(zaxis.length2())) { - // direction and refDirection are identical, - // choose any other direction to define plane - if (direction[0] < 0.9999f) - zaxis = m_refDirVector.cross(MT_Vector3(1.0f,0.0f,0.0f)); - else - zaxis = m_refDirVector.cross(MT_Vector3(0.0f,1.0f,0.0f)); - } - MT_Vector3 yaxis = zaxis.cross(m_refDirVector); - yaxis.normalize(); - if (cosangle > m_minimumBound) { - // angle is too close to reference direction, - // choose a new reference that is exactly at minimum angle - refDirection = m_minimumBound * m_refDirVector + m_minimumSine * yaxis; - } else { - // angle is too large, choose new reference direction at maximum angle - refDirection = m_maximumBound * m_refDirVector + m_maximumSine * yaxis; - } - } else { - refDirection = m_refDirVector; - } - // apply damping on the direction - direction = filter*direction + (1.0f-filter)*refDirection; - obj->AlignAxisToVect(direction, axis); - result = true; - goto CHECK_TIME; - case KX_ACT_CONSTRAINT_DIRPX: - case KX_ACT_CONSTRAINT_DIRPY: - case KX_ACT_CONSTRAINT_DIRPZ: - case KX_ACT_CONSTRAINT_DIRNX: - case KX_ACT_CONSTRAINT_DIRNY: - case KX_ACT_CONSTRAINT_DIRNZ: - switch (m_locrot) { - case KX_ACT_CONSTRAINT_DIRPX: - normal[0] = rotation[0][0]; - normal[1] = rotation[1][0]; - normal[2] = rotation[2][0]; - axis = 0; // axis according to KX_GameObject::AlignAxisToVect() - sign = 0; // X axis will be parrallel to direction of ray - break; - case KX_ACT_CONSTRAINT_DIRPY: - normal[0] = rotation[0][1]; - normal[1] = rotation[1][1]; - normal[2] = rotation[2][1]; - axis = 1; - sign = 0; - break; - case KX_ACT_CONSTRAINT_DIRPZ: - normal[0] = rotation[0][2]; - normal[1] = rotation[1][2]; - normal[2] = rotation[2][2]; - axis = 2; - sign = 0; - break; - case KX_ACT_CONSTRAINT_DIRNX: - normal[0] = -rotation[0][0]; - normal[1] = -rotation[1][0]; - normal[2] = -rotation[2][0]; - axis = 0; - sign = 1; - break; - case KX_ACT_CONSTRAINT_DIRNY: - normal[0] = -rotation[0][1]; - normal[1] = -rotation[1][1]; - normal[2] = -rotation[2][1]; - axis = 1; - sign = 1; - break; - case KX_ACT_CONSTRAINT_DIRNZ: - normal[0] = -rotation[0][2]; - normal[1] = -rotation[1][2]; - normal[2] = -rotation[2][2]; - axis = 2; - sign = 1; - break; - } - normal.normalize(); - if (m_option & KX_ACT_CONSTRAINT_LOCAL) { - // direction of the ray is along the local axis - direction = normal; - } else { - switch (m_locrot) { - case KX_ACT_CONSTRAINT_DIRPX: - direction = MT_Vector3(1.0f,0.0f,0.0f); - break; - case KX_ACT_CONSTRAINT_DIRPY: - direction = MT_Vector3(0.0f,1.0f,0.0f); - break; - case KX_ACT_CONSTRAINT_DIRPZ: - direction = MT_Vector3(0.0f,0.0f,1.0f); - break; - case KX_ACT_CONSTRAINT_DIRNX: - direction = MT_Vector3(-1.0f,0.0f,0.0f); - break; - case KX_ACT_CONSTRAINT_DIRNY: - direction = MT_Vector3(0.0f,-1.0f,0.0f); - break; - case KX_ACT_CONSTRAINT_DIRNZ: - direction = MT_Vector3(0.0f,0.0f,-1.0f); - break; - } - } - { - MT_Point3 topoint = position + (m_maximumBound) * direction; - PHY_IPhysicsEnvironment* pe = KX_GetActiveScene()->GetPhysicsEnvironment(); - PHY_IPhysicsController *spc = obj->GetPhysicsController(); - - if (!pe) { - std::cout << "WARNING: Constraint actuator " << GetName() << ": There is no physics environment!" << std::endl; - goto CHECK_TIME; - } - if (!spc) { - // the object is not physical, we probably want to avoid hitting its own parent - KX_GameObject *parent = obj->GetParent(); - if (parent) { - spc = parent->GetPhysicsController(); - } - } - KX_RayCast::Callback callback(this,dynamic_cast(spc)); - result = KX_RayCast::RayTest(pe, position, topoint, callback); - if (result) { - MT_Vector3 newnormal = callback.m_hitNormal; - // compute new position & orientation - if ((m_option & (KX_ACT_CONSTRAINT_NORMAL|KX_ACT_CONSTRAINT_DISTANCE)) == 0) { - // if none option is set, the actuator does nothing but detect ray - // (works like a sensor) - goto CHECK_TIME; - } - if (m_option & KX_ACT_CONSTRAINT_NORMAL) { - MT_Scalar rotFilter; - // apply damping on the direction - if (m_rotDampTime) { - rotFilter = m_rotDampTime/(1.0f+m_rotDampTime); - } else { - rotFilter = filter; - } - newnormal = rotFilter*normal - (1.0f-rotFilter)*newnormal; - obj->AlignAxisToVect((sign)?-newnormal:newnormal, axis); - if (m_option & KX_ACT_CONSTRAINT_LOCAL) { - direction = newnormal; - direction.normalize(); - } - } - if (m_option & KX_ACT_CONSTRAINT_DISTANCE) { - if (m_posDampTime) { - newdistance = filter*(position-callback.m_hitPoint).length()+(1.0f-filter)*m_minimumBound; - } else { - newdistance = m_minimumBound; - } - // logically we should cancel the speed along the ray direction as we set the - // position along that axis - spc = obj->GetPhysicsController(); - if (spc && spc->IsDynamic()) { - MT_Vector3 linV = spc->GetLinearVelocity(); - // cancel the projection along the ray direction - MT_Scalar fallspeed = linV.dot(direction); - if (!MT_fuzzyZero(fallspeed)) - spc->SetLinearVelocity(linV-fallspeed*direction,false); - } - } else { - newdistance = (position-callback.m_hitPoint).length(); - } - newposition = callback.m_hitPoint-newdistance*direction; - } else if (m_option & KX_ACT_CONSTRAINT_PERMANENT) { - // no contact but still keep running - result = true; - goto CHECK_TIME; - } - } - break; - case KX_ACT_CONSTRAINT_FHPX: - case KX_ACT_CONSTRAINT_FHPY: - case KX_ACT_CONSTRAINT_FHPZ: - case KX_ACT_CONSTRAINT_FHNX: - case KX_ACT_CONSTRAINT_FHNY: - case KX_ACT_CONSTRAINT_FHNZ: - switch (m_locrot) { - case KX_ACT_CONSTRAINT_FHPX: - normal[0] = -rotation[0][0]; - normal[1] = -rotation[1][0]; - normal[2] = -rotation[2][0]; - direction = MT_Vector3(1.0f,0.0f,0.0f); - break; - case KX_ACT_CONSTRAINT_FHPY: - normal[0] = -rotation[0][1]; - normal[1] = -rotation[1][1]; - normal[2] = -rotation[2][1]; - direction = MT_Vector3(0.0f,1.0f,0.0f); - break; - case KX_ACT_CONSTRAINT_FHPZ: - normal[0] = -rotation[0][2]; - normal[1] = -rotation[1][2]; - normal[2] = -rotation[2][2]; - direction = MT_Vector3(0.0f,0.0f,1.0f); - break; - case KX_ACT_CONSTRAINT_FHNX: - normal[0] = rotation[0][0]; - normal[1] = rotation[1][0]; - normal[2] = rotation[2][0]; - direction = MT_Vector3(-1.0f,0.0f,0.0f); - break; - case KX_ACT_CONSTRAINT_FHNY: - normal[0] = rotation[0][1]; - normal[1] = rotation[1][1]; - normal[2] = rotation[2][1]; - direction = MT_Vector3(0.0f,-1.0f,0.0f); - break; - case KX_ACT_CONSTRAINT_FHNZ: - normal[0] = rotation[0][2]; - normal[1] = rotation[1][2]; - normal[2] = rotation[2][2]; - direction = MT_Vector3(0.0f,0.0f,-1.0f); - break; - } - normal.normalize(); - { - PHY_IPhysicsEnvironment* pe = KX_GetActiveScene()->GetPhysicsEnvironment(); - PHY_IPhysicsController *spc = obj->GetPhysicsController(); - - if (!pe) { - std::cout << "WARNING: Constraint actuator " << GetName() << ": There is no physics environment!" << std::endl; - goto CHECK_TIME; - } - if (!spc || !spc->IsDynamic()) { - // the object is not dynamic, it won't support setting speed - goto CHECK_TIME; - } - m_hitObject = NULL; - // distance of Fh area is stored in m_minimum - MT_Point3 topoint = position + (m_minimumBound+spc->GetRadius()) * direction; - KX_RayCast::Callback callback(this, spc); - result = KX_RayCast::RayTest(pe, position, topoint, callback); - // we expect a hit object - if (!m_hitObject) - result = false; - if (result) - { - MT_Vector3 newnormal = callback.m_hitNormal; - // compute new position & orientation - MT_Scalar distance = (callback.m_hitPoint-position).length()-spc->GetRadius(); - // estimate the velocity of the hit point - MT_Point3 relativeHitPoint; - relativeHitPoint = (callback.m_hitPoint-m_hitObject->NodeGetWorldPosition()); - MT_Vector3 velocityHitPoint = m_hitObject->GetVelocity(relativeHitPoint); - MT_Vector3 relativeVelocity = spc->GetLinearVelocity() - velocityHitPoint; - MT_Scalar relativeVelocityRay = direction.dot(relativeVelocity); - MT_Scalar springExtent = 1.0f - distance/m_minimumBound; - // Fh force is stored in m_maximum - MT_Scalar springForce = springExtent * m_maximumBound; - // damping is stored in m_refDirection [0] = damping, [1] = rot damping - MT_Scalar springDamp = relativeVelocityRay * m_refDirVector[0]; - MT_Vector3 newVelocity = spc->GetLinearVelocity()-(springForce+springDamp)*direction; - if (m_option & KX_ACT_CONSTRAINT_NORMAL) - { - newVelocity+=(springForce+springDamp)*(newnormal-newnormal.dot(direction)*direction); - } - spc->SetLinearVelocity(newVelocity, false); - if (m_option & KX_ACT_CONSTRAINT_DOROTFH) - { - MT_Vector3 angSpring = (normal.cross(newnormal))*m_maximumBound; - MT_Vector3 angVelocity = spc->GetAngularVelocity(); - // remove component that is parallel to normal - angVelocity -= angVelocity.dot(newnormal)*newnormal; - MT_Vector3 angDamp = angVelocity * ((m_refDirVector[1]>MT_EPSILON)?m_refDirVector[1]:m_refDirVector[0]); - spc->SetAngularVelocity(spc->GetAngularVelocity()+(angSpring-angDamp), false); - } - } else if (m_option & KX_ACT_CONSTRAINT_PERMANENT) { - // no contact but still keep running - result = true; - } - // don't set the position with this constraint - goto CHECK_TIME; - } - break; - case KX_ACT_CONSTRAINT_LOCX: - case KX_ACT_CONSTRAINT_LOCY: - case KX_ACT_CONSTRAINT_LOCZ: - newposition = position = obj->GetSGNode()->GetLocalPosition(); - switch (m_locrot) { - case KX_ACT_CONSTRAINT_LOCX: - Clamp(newposition[0], m_minimumBound, m_maximumBound); - break; - case KX_ACT_CONSTRAINT_LOCY: - Clamp(newposition[1], m_minimumBound, m_maximumBound); - break; - case KX_ACT_CONSTRAINT_LOCZ: - Clamp(newposition[2], m_minimumBound, m_maximumBound); - break; - } - result = true; - if (m_posDampTime) { - newposition = filter*position + (1.0f-filter)*newposition; - } - obj->NodeSetLocalPosition(newposition); - goto CHECK_TIME; - } - if (result) { - // set the new position but take into account parent if any - obj->NodeSetWorldPosition(newposition); - } - CHECK_TIME: - if (result && m_activeTime > 0 ) { - if (++m_currentTime >= m_activeTime) - result = false; - } - } - if (!result) { - m_currentTime = 0; - } - return result; -} /* end of KX_ConstraintActuator::Update(double curtime,double deltatime) */ - -void KX_ConstraintActuator::Clamp(MT_Scalar &var, - float min, - float max) { - if (var < min) { - var = min; - } else if (var > max) { - var = max; - } -} - - -bool KX_ConstraintActuator::IsValidMode(KX_ConstraintActuator::KX_CONSTRAINTTYPE m) -{ - bool res = false; - - if ( (m > KX_ACT_CONSTRAINT_NODEF) && (m < KX_ACT_CONSTRAINT_MAX)) { - res = true; - } - - return res; -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject KX_ConstraintActuator::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_ConstraintActuator", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &SCA_IActuator::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_ConstraintActuator::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_ConstraintActuator::Attributes[] = { - KX_PYATTRIBUTE_INT_RW("damp",0,100,true,KX_ConstraintActuator,m_posDampTime), - KX_PYATTRIBUTE_INT_RW("rotDamp",0,100,true,KX_ConstraintActuator,m_rotDampTime), - KX_PYATTRIBUTE_FLOAT_ARRAY_RW_CHECK("direction",-FLT_MAX,FLT_MAX,KX_ConstraintActuator,m_refDirection,3,pyattr_check_direction), - KX_PYATTRIBUTE_INT_RW("option",0,0xFFFF,false,KX_ConstraintActuator,m_option), - KX_PYATTRIBUTE_INT_RW("time",0,1000,true,KX_ConstraintActuator,m_activeTime), - KX_PYATTRIBUTE_STRING_RW("propName",0,MAX_PROP_NAME,true,KX_ConstraintActuator,m_property), - KX_PYATTRIBUTE_FLOAT_RW("min",-FLT_MAX,FLT_MAX,KX_ConstraintActuator,m_minimumBound), - KX_PYATTRIBUTE_FLOAT_RW("distance",-FLT_MAX,FLT_MAX,KX_ConstraintActuator,m_minimumBound), - KX_PYATTRIBUTE_FLOAT_RW("max",-FLT_MAX,FLT_MAX,KX_ConstraintActuator,m_maximumBound), - KX_PYATTRIBUTE_FLOAT_RW("rayLength",0,2000.f,KX_ConstraintActuator,m_maximumBound), - KX_PYATTRIBUTE_INT_RW("limit",KX_ConstraintActuator::KX_ACT_CONSTRAINT_NODEF+1,KX_ConstraintActuator::KX_ACT_CONSTRAINT_MAX-1,false,KX_ConstraintActuator,m_locrot), - { NULL } //Sentinel -}; - -int KX_ConstraintActuator::pyattr_check_direction(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_ConstraintActuator* act = static_cast(self); - MT_Vector3 dir(act->m_refDirection); - MT_Scalar len = dir.length(); - if (MT_fuzzyZero(len)) { - PyErr_SetString(PyExc_ValueError, "actuator.direction = vec: KX_ConstraintActuator, invalid direction"); - return 1; - } - act->m_refDirVector = dir/len; - return 0; -} - -#endif - -/* eof */ diff --git a/source/gameengine/Ketsji/KX_ConstraintActuator.h b/source/gameengine/Ketsji/KX_ConstraintActuator.h deleted file mode 100644 index af617655d5e..00000000000 --- a/source/gameengine/Ketsji/KX_ConstraintActuator.h +++ /dev/null @@ -1,152 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_ConstraintActuator.h - * \ingroup ketsji - */ - -#ifndef __KX_CONSTRAINTACTUATOR_H__ -#define __KX_CONSTRAINTACTUATOR_H__ - -#include "SCA_IActuator.h" -#include "MT_Scalar.h" -#include "MT_Vector3.h" -#include "KX_ClientObjectInfo.h" - -#include "BLI_utildefines.h" - -class KX_RayCast; -class KX_GameObject; - -class KX_ConstraintActuator : public SCA_IActuator -{ - Py_Header -protected: - // Damp time (int), - int m_posDampTime; - int m_rotDampTime; - // min (float) - float m_minimumBound; - // max (float) - float m_maximumBound; - // sinus of minimum angle - float m_minimumSine; - // sinus of maximum angle - float m_maximumSine; - // reference direction - float m_refDirection[3]; - MT_Vector3 m_refDirVector; // same as m_refDirection - // locrotxyz choice (pick one): only one choice allowed at a time! - int m_locrot; - // active time of actuator - int m_activeTime; - int m_currentTime; - // option - int m_option; - // property to check - STR_String m_property; - // hit object - KX_GameObject* m_hitObject; - - /** - * Clamp to , . Borders are included (in as far as - * float comparisons are good for equality...). - */ - void Clamp(MT_Scalar &var, float min, float max); - - - public: - // m_locrot - enum KX_CONSTRAINTTYPE { - KX_ACT_CONSTRAINT_NODEF = 0, - KX_ACT_CONSTRAINT_LOCX, - KX_ACT_CONSTRAINT_LOCY, - KX_ACT_CONSTRAINT_LOCZ, - KX_ACT_CONSTRAINT_ROTX, - KX_ACT_CONSTRAINT_ROTY, - KX_ACT_CONSTRAINT_ROTZ, - KX_ACT_CONSTRAINT_DIRPX, - KX_ACT_CONSTRAINT_DIRPY, - KX_ACT_CONSTRAINT_DIRPZ, - KX_ACT_CONSTRAINT_DIRNX, - KX_ACT_CONSTRAINT_DIRNY, - KX_ACT_CONSTRAINT_DIRNZ, - KX_ACT_CONSTRAINT_ORIX, - KX_ACT_CONSTRAINT_ORIY, - KX_ACT_CONSTRAINT_ORIZ, - KX_ACT_CONSTRAINT_FHPX, - KX_ACT_CONSTRAINT_FHPY, - KX_ACT_CONSTRAINT_FHPZ, - KX_ACT_CONSTRAINT_FHNX, - KX_ACT_CONSTRAINT_FHNY, - KX_ACT_CONSTRAINT_FHNZ, - KX_ACT_CONSTRAINT_MAX - }; - // match ACT_CONST_... values from BIF_interface.h - enum KX_CONSTRAINTOPT { - KX_ACT_CONSTRAINT_NORMAL = 64, - KX_ACT_CONSTRAINT_MATERIAL = 128, - KX_ACT_CONSTRAINT_PERMANENT = 256, - KX_ACT_CONSTRAINT_DISTANCE = 512, - KX_ACT_CONSTRAINT_LOCAL = 1024, - KX_ACT_CONSTRAINT_DOROTFH = 2048 - }; - bool IsValidMode(KX_CONSTRAINTTYPE m); - /// \see KX_RayCast - bool RayHit(KX_ClientObjectInfo *client, KX_RayCast *result, void *UNUSED(data)); - /// \see KX_RayCast - bool NeedRayCast(KX_ClientObjectInfo *client, void *UNUSED(data)); - - KX_ConstraintActuator(SCA_IObject* gameobj, - int posDamptime, - int rotDampTime, - float min, - float max, - float refDir[3], - int locrot, - int time, - int option, - char *property); - virtual ~KX_ConstraintActuator(); - virtual CValue* GetReplica() { - KX_ConstraintActuator* replica = new KX_ConstraintActuator(*this); - replica->ProcessReplica(); - return replica; - }; - - virtual bool Update(double curtime, bool frame); - - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - - static int pyattr_check_direction(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_check_min(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - -}; - -#endif /* __KX_CONSTRAINTACTUATOR_H__ */ diff --git a/source/gameengine/Ketsji/KX_ConstraintWrapper.cpp b/source/gameengine/Ketsji/KX_ConstraintWrapper.cpp deleted file mode 100644 index 2f32b5e3216..00000000000 --- a/source/gameengine/Ketsji/KX_ConstraintWrapper.cpp +++ /dev/null @@ -1,133 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_ConstraintWrapper.cpp - * \ingroup ketsji - */ - - -#include "EXP_PyObjectPlus.h" -#include "KX_ConstraintWrapper.h" -#include "PHY_IPhysicsEnvironment.h" - -KX_ConstraintWrapper::KX_ConstraintWrapper( - PHY_ConstraintType ctype, - int constraintId, - PHY_IPhysicsEnvironment* physenv) : - PyObjectPlus(), - m_constraintId(constraintId), - m_constraintType(ctype), - m_physenv(physenv) -{ -} -KX_ConstraintWrapper::~KX_ConstraintWrapper() -{ -} - -#ifdef WITH_PYTHON - -PyObject *KX_ConstraintWrapper::PyGetConstraintId() -{ - return PyLong_FromLong(m_constraintId); -} - - -PyObject *KX_ConstraintWrapper::PyGetParam(PyObject *args, PyObject *kwds) -{ - int dof; - float value; - - if (!PyArg_ParseTuple(args,"i:getParam",&dof)) - return NULL; - - value = m_physenv->GetConstraintParam(m_constraintId,dof); - return PyFloat_FromDouble(value); - -} - -PyObject *KX_ConstraintWrapper::PySetParam(PyObject *args, PyObject *kwds) -{ - int dof; - float minLimit,maxLimit; - - if (!PyArg_ParseTuple(args,"iff:setParam",&dof,&minLimit,&maxLimit)) - return NULL; - - m_physenv->SetConstraintParam(m_constraintId,dof,minLimit,maxLimit); - Py_RETURN_NONE; -} - - -//python specific stuff -PyTypeObject KX_ConstraintWrapper::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_ConstraintWrapper", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &PyObjectPlus::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_ConstraintWrapper::Methods[] = { - {"getConstraintId",(PyCFunction) KX_ConstraintWrapper::sPyGetConstraintId, METH_NOARGS}, - {"setParam",(PyCFunction) KX_ConstraintWrapper::sPySetParam, METH_VARARGS}, - {"getParam",(PyCFunction) KX_ConstraintWrapper::sPyGetParam, METH_VARARGS}, - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_ConstraintWrapper::Attributes[] = { - KX_PYATTRIBUTE_RO_FUNCTION("constraint_id", KX_ConstraintWrapper, pyattr_get_constraintId), - KX_PYATTRIBUTE_RO_FUNCTION("constraint_type", KX_ConstraintWrapper, pyattr_get_constraintType), - { NULL } //Sentinel -}; - -PyObject *KX_ConstraintWrapper::pyattr_get_constraintId(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_ConstraintWrapper* self = static_cast(self_v); - return self->PyGetConstraintId(); -} - -PyObject *KX_ConstraintWrapper::pyattr_get_constraintType(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_ConstraintWrapper* self = static_cast(self_v); - return PyLong_FromLong(self->m_constraintType); -} - -#endif // WITH_PYTHON diff --git a/source/gameengine/Ketsji/KX_ConstraintWrapper.h b/source/gameengine/Ketsji/KX_ConstraintWrapper.h deleted file mode 100644 index 5e20b7a9aca..00000000000 --- a/source/gameengine/Ketsji/KX_ConstraintWrapper.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_ConstraintWrapper.h - * \ingroup ketsji - */ - -#ifndef __KX_CONSTRAINTWRAPPER_H__ -#define __KX_CONSTRAINTWRAPPER_H__ - -#include "EXP_Value.h" -#include "PHY_DynamicTypes.h" - -class KX_ConstraintWrapper : public PyObjectPlus -{ - Py_Header -public: - KX_ConstraintWrapper(PHY_ConstraintType ctype,int constraintId,class PHY_IPhysicsEnvironment* physenv); - virtual ~KX_ConstraintWrapper (); - int getConstraintId() { return m_constraintId; } - -#ifdef WITH_PYTHON - KX_PYMETHOD_NOARGS(KX_ConstraintWrapper,GetConstraintId); - KX_PYMETHOD(KX_ConstraintWrapper,SetParam); - KX_PYMETHOD(KX_ConstraintWrapper,GetParam); - - static PyObject *pyattr_get_constraintId(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_constraintType(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); -#endif - -private: - int m_constraintId; - PHY_ConstraintType m_constraintType; - PHY_IPhysicsEnvironment* m_physenv; -}; - -#endif /* __KX_CONSTRAINTWRAPPER_H__ */ diff --git a/source/gameengine/Ketsji/KX_Dome.cpp b/source/gameengine/Ketsji/KX_Dome.cpp deleted file mode 100644 index 7abff85d39c..00000000000 --- a/source/gameengine/Ketsji/KX_Dome.cpp +++ /dev/null @@ -1,2051 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * Contributor(s): Dalai Felinto - * - * This code is originally inspired on some of the ideas and codes from Paul Bourke. - * Developed as part of a Research and Development project for - * SAT - La Société des arts technologiques. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_Dome.cpp - * \ingroup ketsji - */ - -#include "KX_Dome.h" - -#ifdef WITH_PYTHON -#include -#endif - -#include -#include - -#include "DNA_scene_types.h" -#include "RAS_CameraData.h" -#include "BLI_math.h" - -#include "GPU_matrix.h" - -// constructor -KX_Dome::KX_Dome ( - RAS_ICanvas* canvas, - /// rasterizer - RAS_IRasterizer* rasterizer, - /// engine - KX_KetsjiEngine* engine, - - short res, //resolution of the mesh - short mode, //mode - fisheye, truncated, warped, panoramic, ... - short angle, - float resbuf, //size adjustment of the buffer - short tilt, - struct Text* warptext - - ): - dlistSupported(false), - canvaswidth(-1), canvasheight(-1), - m_drawingmode(rasterizer->GetDrawingMode()), - m_resolution(res), - m_mode(mode), - m_angle(angle), - m_resbuffer(resbuf), - m_tilt(tilt), - m_canvas(canvas), - m_rasterizer(rasterizer), - m_engine(engine) -{ - warp.usemesh = false; - fboSupported = false; - - if (mode >= DOME_NUM_MODES) - m_mode = DOME_FISHEYE; - - if (warptext) // it there is a text data try to warp it - { - char *buf; - buf = txt_to_buf(warptext); - if (buf) - { - warp.usemesh = ParseWarpMesh(STR_String(buf)); - MEM_freeN(buf); - } - } - - //setting the viewport size - const int *viewport = m_canvas->GetViewPort(); - - SetViewPort(viewport); - - switch (m_mode) { - case DOME_FISHEYE: - if (m_angle <= 180) { - cubetop.resize(1); - cubebottom.resize(1); - cubeleft.resize(2); - cuberight.resize(2); - - CreateMeshDome180(); - m_numfaces = 4; - } - else if (m_angle > 180) { - cubetop.resize(2); - cubebottom.resize(2); - cubeleft.resize(2); - cubefront.resize(2); - cuberight.resize(2); - - CreateMeshDome250(); - m_numfaces = 5; - } break; - case DOME_ENVMAP: - m_angle = 360; - m_numfaces = 6; - break; - case DOME_PANORAM_SPH: - cubeleft.resize(2); - cubeleftback.resize(2); - cuberight.resize(2); - cuberightback.resize(2); - cubetop.resize(2); - cubebottom.resize(2); - - m_angle = 360; - CreateMeshPanorama(); - m_numfaces = 6; - break; - default: //DOME_TRUNCATED_FRONT and DOME_TRUNCATED_REAR - if (m_angle <= 180) { - cubetop.resize(1); - cubebottom.resize(1); - cubeleft.resize(2); - cuberight.resize(2); - - CreateMeshDome180(); - m_numfaces = 4; - } - else if (m_angle > 180) { - cubetop.resize(2); - cubebottom.resize(2); - cubeleft.resize(2); - cubefront.resize(2); - cuberight.resize(2); - - CreateMeshDome250(); - m_numfaces = 5; - } break; - } - - m_numimages =(warp.usemesh?m_numfaces+1:m_numfaces); - - CalculateCameraOrientation(); - - CreateGLImages(); - - if (warp.usemesh) - fboSupported = CreateFBO(); - - dlistSupported = CreateDL(); -} - -// destructor -KX_Dome::~KX_Dome (void) -{ - ClearGLImages(); - - if (fboSupported) - glDeleteFramebuffersEXT(1, &warp.fboId); - - if (dlistSupported) - glDeleteLists(dlistId, (GLsizei) m_numimages); -} - -void KX_Dome::SetViewPort(const int viewport[4]) -{ - if (canvaswidth != m_viewport.GetWidth() || canvasheight != m_viewport.GetHeight()) - { - m_viewport.SetLeft(viewport[0]); - m_viewport.SetBottom(viewport[1]); - m_viewport.SetRight(viewport[2]); - m_viewport.SetTop(viewport[3]); - - CalculateImageSize(); - } -} - -void KX_Dome::CreateGLImages(void) -{ - glGenTextures(m_numimages, (GLuint*)&domefacesId); - - for (int j=0;jGetWidth(); - canvasheight = m_canvas->GetHeight(); - - m_buffersize = (canvaswidth > canvasheight?canvasheight:canvaswidth); - m_buffersize = (int)(m_buffersize*m_resbuffer); //reduce buffer size for better performance - - int i = 0; - while ((1 << i) <= m_buffersize) - i++; - m_imagesize = (1 << i); - - if (warp.usemesh) { - // warp FBO needs to be up to twice as big as m_buffersize to get more resolution - warp.imagesize = m_imagesize; - if (m_buffersize == m_imagesize) - warp.imagesize *= 2; - - //if FBO is not working/supported, we use the canvas dimension as buffer - warp.bufferwidth = canvaswidth; - warp.bufferheight = canvasheight; - } -} - -bool KX_Dome::CreateDL() -{ - dlistId = glGenLists((GLsizei) m_numimages); - if (dlistId != 0) { - if (m_mode == DOME_FISHEYE || m_mode == DOME_TRUNCATED_FRONT || m_mode == DOME_TRUNCATED_REAR) { - glNewList(dlistId, GL_COMPILE); - GLDrawTriangles(cubetop, nfacestop); - glEndList(); - - glNewList(dlistId+1, GL_COMPILE); - GLDrawTriangles(cubebottom, nfacesbottom); - glEndList(); - - glNewList(dlistId+2, GL_COMPILE); - GLDrawTriangles(cubeleft, nfacesleft); - glEndList(); - - glNewList(dlistId+3, GL_COMPILE); - GLDrawTriangles(cuberight, nfacesright); - glEndList(); - - if (m_angle > 180) { - glNewList(dlistId+4, GL_COMPILE); - GLDrawTriangles(cubefront, nfacesfront); - glEndList(); - } - } - else if (m_mode == DOME_PANORAM_SPH) - { - glNewList(dlistId, GL_COMPILE); - GLDrawTriangles(cubetop, nfacestop); - glEndList(); - - glNewList(dlistId+1, GL_COMPILE); - GLDrawTriangles(cubebottom, nfacesbottom); - glEndList(); - - glNewList(dlistId+2, GL_COMPILE); - GLDrawTriangles(cubeleft, nfacesleft); - glEndList(); - - glNewList(dlistId+3, GL_COMPILE); - GLDrawTriangles(cuberight, nfacesright); - glEndList(); - - glNewList(dlistId+4, GL_COMPILE); - GLDrawTriangles(cubeleftback, nfacesleftback); - glEndList(); - - glNewList(dlistId+5, GL_COMPILE); - GLDrawTriangles(cuberightback, nfacesrightback); - glEndList(); - } - - if (warp.usemesh) { - glNewList((dlistId + m_numfaces), GL_COMPILE); - GLDrawWarpQuads(); - glEndList(); - } - - //clearing the vectors - cubetop.clear(); - cubebottom.clear(); - cuberight.clear(); - cubeleft.clear(); - cubefront.clear(); - cubeleftback.clear(); - cuberightback.clear(); - warp.nodes.clear(); - - } else // genList failed - return false; - - return true; -} - -bool KX_Dome::CreateFBO(void) -{ - if (!GLEW_EXT_framebuffer_object) - { - printf("Dome Error: FrameBuffer unsupported. Using low resolution warp image."); - return false; - } - - glGenFramebuffersEXT(1, &warp.fboId); - if (warp.fboId==0) - { - printf("Dome Error: Invalid frame buffer object. Using low resolution warp image."); - return false; - } - - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, warp.fboId); - - glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, - GL_TEXTURE_2D, domefacesId[m_numfaces], 0); - - GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); - - if (status == GL_FRAMEBUFFER_UNSUPPORTED_EXT) - { - printf("Dome Error: FrameBuffer settings unsupported. Using low resolution warp image."); - return false; - } - else if (status != GL_FRAMEBUFFER_COMPLETE_EXT) - { - glDeleteFramebuffersEXT(1, &warp.fboId); - return false; - } - - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); - - //nothing failed: we can use the whole FBO as buffersize - warp.bufferwidth = warp.bufferheight = warp.imagesize; - return true; -} - -void KX_Dome::GLDrawTriangles(vector & face, int nfaces) -{ - int i,j; - glBegin(GL_TRIANGLES); - for (i=0;i columns, lines; - - lines = text.Explode('\n'); - if (lines.size() < 6) { - printf("Dome Error: Warp Mesh File with insufficient data!\n"); - return false; - } - columns = lines[1].Explode(' '); - if (columns.size() == 1) - columns = lines[1].Explode('\t'); - - if (columns.size() !=2) { - printf("Dome Error: Warp Mesh File incorrect. The second line should contain: width height.\n"); - return false; - } - - warp.mode = atoi(lines[0]);// 1 = radial, 2 = fisheye - - warp.n_width = atoi(columns[0]); - warp.n_height = atoi(columns[1]); - - if ((int)lines.size() < 2 + (warp.n_width * warp.n_height)) { - printf("Dome Error: Warp Mesh File with insufficient data!\n"); - return false; - } - else { - warp.nodes = vector > (warp.n_height, vector(warp.n_width)); - - for (i=2; i-2 < (warp.n_width*warp.n_height); i++) { - columns = lines[i].Explode(' '); - if (columns.size() == 1) - columns = lines[i].Explode('\t'); - - if (columns.size() == 5) { - nodeX = (i-2)%warp.n_width; - nodeY = ((i-2) - nodeX) / warp.n_width; - - warp.nodes[nodeY][nodeX].x = atof(columns[0]); - warp.nodes[nodeY][nodeX].y = atof(columns[1]); - warp.nodes[nodeY][nodeX].u = atof(columns[2]); - warp.nodes[nodeY][nodeX].v = atof(columns[3]); - warp.nodes[nodeY][nodeX].i = atof(columns[4]); - } - else { - warp.nodes.clear(); - printf("Dome Error: Warp Mesh File with wrong number of fields. You should use 5: x y u v i.\n"); - return false; - } - } - } - return true; -} - -void KX_Dome::CreateMeshDome180(void) -{ - /* - * 1)- Define the faces of half of a cube - * - each face is made out of 2 triangles - * 2) Subdivide the faces - * - more resolution == more curved lines - * 3) Spherize the cube - * - normalize the verts - * 4) Flatten onto xz plane - * - transform it onto an equidistant spherical projection techniques to transform the sphere onto a dome image - */ - int i,j; - float uv_ratio = (float)(m_buffersize-1) / m_imagesize; - - m_radangle = DEG2RADF(m_angle); //calculates the radians angle, used for flattening - - //creating faces for the env mapcube 180deg Dome - // Top Face - just a triangle - cubetop[0].verts[0][0] = (float)(-M_SQRT2) / 2.0f; - cubetop[0].verts[0][1] = 0.0f; - cubetop[0].verts[0][2] = 0.5f; - cubetop[0].u[0] = 0.0; - cubetop[0].v[0] = uv_ratio; - - cubetop[0].verts[1][0] = 0.0f; - cubetop[0].verts[1][1] = (float)M_SQRT2 / 2.0f; - cubetop[0].verts[1][2] = 0.5f; - cubetop[0].u[1] = 0.0; - cubetop[0].v[1] = 0.0; - - cubetop[0].verts[2][0] = (float)M_SQRT2 / 2.0f; - cubetop[0].verts[2][1] = 0.0f; - cubetop[0].verts[2][2] = 0.5f; - cubetop[0].u[2] = uv_ratio; - cubetop[0].v[2] = 0.0; - - nfacestop = 1; - - /* Bottom face - just a triangle */ - cubebottom[0].verts[0][0] = (float)(-M_SQRT2) / 2.0f; - cubebottom[0].verts[0][1] = 0.0f; - cubebottom[0].verts[0][2] = -0.5f; - cubebottom[0].u[0] = uv_ratio; - cubebottom[0].v[0] = 0.0; - - cubebottom[0].verts[1][0] = (float)M_SQRT2 / 2.0f; - cubebottom[0].verts[1][1] = 0; - cubebottom[0].verts[1][2] = -0.5f; - cubebottom[0].u[1] = 0.0; - cubebottom[0].v[1] = uv_ratio; - - cubebottom[0].verts[2][0] = 0.0f; - cubebottom[0].verts[2][1] = (float)M_SQRT2 / 2.0f; - cubebottom[0].verts[2][2] = -0.5f; - cubebottom[0].u[2] = 0.0; - cubebottom[0].v[2] = 0.0; - - nfacesbottom = 1; - - /* Left face - two triangles */ - - cubeleft[0].verts[0][0] = (float)(-M_SQRT2) / 2.0f; - cubeleft[0].verts[0][1] = 0.0f; - cubeleft[0].verts[0][2] = -0.5f; - cubeleft[0].u[0] = 0.0; - cubeleft[0].v[0] = 0.0; - - cubeleft[0].verts[1][0] = 0.0f; - cubeleft[0].verts[1][1] = (float)M_SQRT2 / 2.0f; - cubeleft[0].verts[1][2] = -0.5f; - cubeleft[0].u[1] = uv_ratio; - cubeleft[0].v[1] = 0.0; - - cubeleft[0].verts[2][0] = (float)(-M_SQRT2) / 2.0f; - cubeleft[0].verts[2][1] = 0.0f; - cubeleft[0].verts[2][2] = 0.5f; - cubeleft[0].u[2] = 0.0; - cubeleft[0].v[2] = uv_ratio; - - //second triangle - cubeleft[1].verts[0][0] = (float)(-M_SQRT2) / 2.0f; - cubeleft[1].verts[0][1] = 0.0f; - cubeleft[1].verts[0][2] = 0.5f; - cubeleft[1].u[0] = 0.0; - cubeleft[1].v[0] = uv_ratio; - - cubeleft[1].verts[1][0] = 0.0f; - cubeleft[1].verts[1][1] = (float)M_SQRT2 / 2.0f; - cubeleft[1].verts[1][2] = -0.5f; - cubeleft[1].u[1] = uv_ratio; - cubeleft[1].v[1] = 0.0; - - cubeleft[1].verts[2][0] = 0.0f; - cubeleft[1].verts[2][1] = (float)M_SQRT2 / 2.0f; - cubeleft[1].verts[2][2] = 0.5f; - cubeleft[1].u[2] = uv_ratio; - cubeleft[1].v[2] = uv_ratio; - - nfacesleft = 2; - - /* Right face - two triangles */ - cuberight[0].verts[0][0] = 0.0f; - cuberight[0].verts[0][1] = (float)M_SQRT2 / 2.0f; - cuberight[0].verts[0][2] = -0.5f; - cuberight[0].u[0] = 0.0; - cuberight[0].v[0] = 0.0; - - cuberight[0].verts[1][0] = (float)M_SQRT2 / 2.0f; - cuberight[0].verts[1][1] = 0.0f; - cuberight[0].verts[1][2] = -0.5f; - cuberight[0].u[1] = uv_ratio; - cuberight[0].v[1] = 0.0; - - cuberight[0].verts[2][0] = (float)M_SQRT2 / 2.0f; - cuberight[0].verts[2][1] = 0.0f; - cuberight[0].verts[2][2] = 0.5f; - cuberight[0].u[2] = uv_ratio; - cuberight[0].v[2] = uv_ratio; - - //second triangle - cuberight[1].verts[0][0] = 0.0f; - cuberight[1].verts[0][1] = (float)M_SQRT2 / 2.0f; - cuberight[1].verts[0][2] = -0.5f; - cuberight[1].u[0] = 0.0; - cuberight[1].v[0] = 0.0; - - cuberight[1].verts[1][0] = (float)M_SQRT2 / 2.0f; - cuberight[1].verts[1][1] = 0.0f; - cuberight[1].verts[1][2] = 0.5f; - cuberight[1].u[1] = uv_ratio; - cuberight[1].v[1] = uv_ratio; - - cuberight[1].verts[2][0] = 0.0f; - cuberight[1].verts[2][1] = (float)M_SQRT2 / 2.0f; - cuberight[1].verts[2][2] = 0.5f; - cuberight[1].u[2] = 0.0; - cuberight[1].v[2] = uv_ratio; - - nfacesright = 2; - - //Refine a triangular mesh by bisecting each edge forms 3 new triangles for each existing triangle on each iteration - //Could be made more efficient for drawing if the triangles were ordered in a fan. Not that important since we are using DisplayLists - - for (i=0;im_radangle / 2.0; - - phi = atan2(verts[i][2], verts[i][0]); - - verts[i][0] = r * cos(phi); - verts[i][1] = 0.0f; - verts[i][2] = r * sin(phi); - - if (r > 1.0) { - //round the border - verts[i][0] = cos(phi); - verts[i][1] = -3.0f; - verts[i][2] = sin(phi); - } - } -} - -void KX_Dome::FlattenPanorama(MT_Vector3 verts[3]) -{ -// it creates a full spherical panoramic (360deg) - int i; - double phi, theta; - bool edge=false; - - for (i=0;i<3;i++) { - phi = atan2(verts[i][1], verts[i][0]); - phi *= -1.0; //flipping - - if (phi == -MT_PI) //It's on the edge - edge=true; - - verts[i][0] = phi / MT_PI; - verts[i][1] = 0.0f; - - theta = asin(verts[i][2]); - verts[i][2] = theta / MT_PI; - } - if (edge) { - bool right=false; - - for (i=0;i<3;i++) { - if (fmodf(verts[i][0],1.0f) > 0.0f) { - right=true; - break; - } - } - if (right) { - for (i=0;i<3;i++) { - if (verts[i][0] < 0.0f) - verts[i][0] *= -1.0f; - } - } - } -} - -void KX_Dome::SplitFace(vector & face, int *nfaces) -{ - int i; - int n1, n2; - - n1 = n2 = *nfaces; - - for (i=0;iGetCameraNear(),cam->GetCameraFar()); -#endif - - RAS_FrameFrustum m_frustum; //90 deg. Frustum - - m_frustum.camnear = cam->GetCameraNear(); - m_frustum.camfar = cam->GetCameraFar(); - -// float top = tan(90.0f*MT_PI/360.0f) * m_frustum.camnear; - float top = m_frustum.camnear; // for deg = 90deg, tan = 1 - - m_frustum.x1 = -top; - m_frustum.x2 = top; - m_frustum.y1 = -top; - m_frustum.y2 = top; - - m_projmat = m_rasterizer->GetFrustumMatrix( - m_frustum.x1, m_frustum.x2, m_frustum.y1, m_frustum.y2, m_frustum.camnear, m_frustum.camfar); -} - -void KX_Dome::CalculateCameraOrientation() -{ -/* - * Uses 4 cameras for angles up to 180deg - * Uses 5 cameras for angles up to 250deg - * Uses 6 cameras for angles up to 360deg - */ - int i; - float deg45 = MT_PI / 4.0f; - MT_Scalar c = cosf(deg45); - MT_Scalar s = sinf(deg45); - - if (m_angle <= 180 && (m_mode == DOME_FISHEYE - || m_mode == DOME_TRUNCATED_FRONT - || m_mode == DOME_TRUNCATED_REAR)) { - - m_locRot[0] = MT_Matrix3x3( // 90deg - Top - c, -s, 0.0f, - 0.0f,0.0f, -1.0f, - s, c, 0.0f); - - m_locRot[1] = MT_Matrix3x3( // 90deg - Bottom - -s, c, 0.0f, - 0.0f,0.0f, 1.0f, - s, c, 0.0f); - - m_locRot[2] = MT_Matrix3x3( // 45deg - Left - c, 0.0f, s, - 0, 1.0f, 0.0f, - -s, 0.0f, c); - - m_locRot[3] = MT_Matrix3x3( // 45deg - Right - c, 0.0f, -s, - 0.0f, 1.0f, 0.0f, - s, 0.0f, c); - - } else if (m_mode == DOME_ENVMAP || (m_angle > 180 && (m_mode == DOME_FISHEYE - || m_mode == DOME_TRUNCATED_FRONT - || m_mode == DOME_TRUNCATED_REAR))) { - - m_locRot[0] = MT_Matrix3x3( // 90deg - Top - 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f,-1.0f, - 0.0f, 1.0f, 0.0f); - - m_locRot[1] = MT_Matrix3x3( // 90deg - Bottom - 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, - 0.0f,-1.0f, 0.0f); - - m_locRot[2] = MT_Matrix3x3( // -90deg - Left - 0.0f, 0.0f, 1.0f, - 0.0f, 1.0f, 0.0f, - -1.0f, 0.0f, 0.0f); - - m_locRot[3] = MT_Matrix3x3( // 90deg - Right - 0.0f, 0.0f,-1.0f, - 0.0f, 1.0f, 0.0f, - 1.0f, 0.0f, 0.0f); - - m_locRot[4] = MT_Matrix3x3( // 0deg - Front - 1.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 1.0f); - - m_locRot[5] = MT_Matrix3x3( // 180deg - Back - USED for ENVMAP only - -1.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f,-1.0f); - - } else if (m_mode == DOME_PANORAM_SPH) { - - m_locRot[0] = MT_Matrix3x3( // Top - c, s, 0.0f, - 0.0f,0.0f, -1.0f, - -s, c, 0.0f); - - m_locRot[1] = MT_Matrix3x3( // Bottom - c, s, 0.0f, - 0.0f, 0.0f, 1.0f, - s, -c, 0.0f); - - m_locRot[2] = MT_Matrix3x3( // 45deg - Left - -s, 0.0f, c, - 0, 1.0f, 0.0f, - -c, 0.0f, -s); - - m_locRot[3] = MT_Matrix3x3( // 45deg - Right - c, 0.0f, s, - 0, 1.0f, 0.0f, - -s, 0.0f, c); - - m_locRot[4] = MT_Matrix3x3( // 135deg - LeftBack - -s, 0.0f, -c, - 0.0f, 1.0f, 0.0f, - c, 0.0f, -s); - - m_locRot[5] = MT_Matrix3x3( // 135deg - RightBack - c, 0.0f, -s, - 0.0f, 1.0f, 0.0f, - s, 0.0f, c); - } - - // rotating the camera in horizontal axis - if (m_tilt) - { - float tiltdeg = ((m_tilt % 360) * 2 * MT_PI) / 360; - c = cosf(tiltdeg); - s = sinf(tiltdeg); - - MT_Matrix3x3 tilt_mat = MT_Matrix3x3( - 1.0f, 0.0f, 0.0f, - 0.0f, c, -s, - 0.0f, s, c - ); - - for (i =0;i<6;i++) - m_locRot[i] = tilt_mat * m_locRot[i]; - } -} - -void KX_Dome::RotateCamera(KX_Camera* cam, int i) -{ -// I'm not using it, I'm doing inline calls for these commands -// but it's nice to have it here in case I need it - - MT_Matrix3x3 camori = cam->GetSGNode()->GetLocalOrientation(); - - cam->NodeSetLocalOrientation(camori*m_locRot[i]); - cam->NodeUpdateGS(0.f); - - MT_Transform camtrans(cam->GetWorldToCamera()); - MT_Matrix4x4 viewmat(camtrans); - m_rasterizer->SetViewMatrix(viewmat, cam->NodeGetWorldOrientation(), cam->NodeGetWorldPosition(), cam->NodeGetLocalScaling(), cam->GetCameraData()->m_perspective); - cam->SetModelviewMatrix(viewmat); - - // restore the original orientation - cam->NodeSetLocalOrientation(camori); - cam->NodeUpdateGS(0.f); -} - -void KX_Dome::Draw(void) -{ - - if (fboSupported) { - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, warp.fboId); - - glViewport(0,0,warp.imagesize, warp.imagesize); - glScissor(0,0,warp.imagesize, warp.imagesize); - } - - switch (m_mode) { - case DOME_FISHEYE: - DrawDomeFisheye(); - break; - case DOME_ENVMAP: - DrawEnvMap(); - break; - case DOME_PANORAM_SPH: - DrawPanorama(); - break; - case DOME_TRUNCATED_FRONT: - DrawDomeFisheye(); - break; - case DOME_TRUNCATED_REAR: - DrawDomeFisheye(); - break; - } - - if (warp.usemesh) - { - if (fboSupported) - { - m_canvas->SetViewPort(0, 0, m_canvas->GetWidth(), m_canvas->GetHeight()); - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); - } - else - { - glBindTexture(GL_TEXTURE_2D, domefacesId[m_numfaces]); - glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, m_viewport.GetLeft(), m_viewport.GetBottom(), warp.bufferwidth, warp.bufferheight); - } - DrawDomeWarped(); - } -} - -void KX_Dome::DrawEnvMap(void) -{ - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - - // Making the viewport always square - - int can_width = m_viewport.GetRight(); - int can_height = m_viewport.GetTop(); - - float ortho_width, ortho_height; - - if (warp.usemesh) - glOrtho((-1.0), 1.0, (-0.66), 0.66, 0.0, 0.0); //stretch the image to reduce resolution lost - - else { - if (can_width/3 <= can_height/2) { - ortho_width = 1.0f; - ortho_height = (float)can_height/can_width; - } - else { - ortho_height = 2.0f / 3; - ortho_width = (float)can_width/can_height * ortho_height; - } - - glOrtho((-ortho_width), ortho_width, (-ortho_height), ortho_height, -20.0f, 10.0f); - } - - glMatrixMode(GL_TEXTURE); - glLoadIdentity(); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - gpuLookAt(0.0f,0.0f,1.0f, 0.0f,0.0f,0.0f, 0.0f,1.0f,0.0f); - - glPolygonMode(GL_FRONT, GL_FILL); - glShadeModel(GL_SMOOTH); - glDisable(GL_LIGHTING); - glDisable(GL_DEPTH_TEST); - - glEnable(GL_TEXTURE_2D); - glColor3f(1.0f,1.0f,1.0f); - - float uv_ratio = (float)(m_buffersize-1) / m_imagesize; - double onebythree = 1.0f / 3; - - // domefacesId[0] => (top) - glBindTexture(GL_TEXTURE_2D, domefacesId[0]); - glBegin(GL_QUADS); - glTexCoord2f(uv_ratio,uv_ratio); - glVertex3f( onebythree, 0.0f, 3.0f); - glTexCoord2f(0.0f,uv_ratio); - glVertex3f(-onebythree, 0.0f, 3.0f); - glTexCoord2f(0.0f,0.0f); - glVertex3f(-onebythree,-2 * onebythree, 3.0f); - glTexCoord2f(uv_ratio,0.0f); - glVertex3f(onebythree,-2 * onebythree, 3.0f); - glEnd(); - - // domefacesId[1] => (bottom) - glBindTexture(GL_TEXTURE_2D, domefacesId[1]); - glBegin(GL_QUADS); - glTexCoord2f(uv_ratio,uv_ratio); - glVertex3f(-onebythree, 0.0f, 3.0f); - glTexCoord2f(0.0f,uv_ratio); - glVertex3f(-1.0f, 0.0f, 3.0f); - glTexCoord2f(0.0f,0.0f); - glVertex3f(-1.0f,-2 * onebythree, 3.0f); - glTexCoord2f(uv_ratio,0.0f); - glVertex3f(-onebythree,-2 * onebythree, 3.0f); - glEnd(); - - // domefacesId[2] => -90deg (left) - glBindTexture(GL_TEXTURE_2D, domefacesId[2]); - glBegin(GL_QUADS); - glTexCoord2f(uv_ratio,uv_ratio); - glVertex3f(-onebythree, 2 * onebythree, 3.0f); - glTexCoord2f(0.0f,uv_ratio); - glVertex3f(-1.0f, 2 * onebythree, 3.0f); - glTexCoord2f(0.0f,0.0f); - glVertex3f(-1.0f, 0.0f, 3.0f); - glTexCoord2f(uv_ratio,0.0f); - glVertex3f(-onebythree, 0.0f, 3.0f); - glEnd(); - - // domefacesId[3] => 90deg (right) - glBindTexture(GL_TEXTURE_2D, domefacesId[3]); - glBegin(GL_QUADS); - glTexCoord2f(uv_ratio,uv_ratio); - glVertex3f( 1.0f, 2 * onebythree, 3.0f); - glTexCoord2f(0.0f,uv_ratio); - glVertex3f( onebythree, 2 * onebythree, 3.0f); - glTexCoord2f(0.0f,0.0f); - glVertex3f( onebythree, 0.0f, 3.0f); - glTexCoord2f(uv_ratio,0.0f); - glVertex3f(1.0f, 0.0f, 3.0f); - glEnd(); - - // domefacesId[4] => 0deg (front) - glBindTexture(GL_TEXTURE_2D, domefacesId[4]); - glBegin(GL_QUADS); - glTexCoord2f(uv_ratio,uv_ratio); - glVertex3f( 1.0f, 0.0f, 3.0f); - glTexCoord2f(0.0f,uv_ratio); - glVertex3f( onebythree, 0.0f, 3.0f); - glTexCoord2f(0.0f,0.0f); - glVertex3f( onebythree,-2 * onebythree, 3.0f); - glTexCoord2f(uv_ratio,0.0f); - glVertex3f(1.0f, -2 * onebythree, 3.0f); - glEnd(); - - // domefacesId[5] => 180deg (back) - glBindTexture(GL_TEXTURE_2D, domefacesId[5]); - glBegin(GL_QUADS); - glTexCoord2f(uv_ratio,uv_ratio); - glVertex3f( onebythree, 2 * onebythree, 3.0f); - glTexCoord2f(0.0f,uv_ratio); - glVertex3f(-onebythree, 2 * onebythree, 3.0f); - glTexCoord2f(0.0f,0.0f); - glVertex3f(-onebythree, 0.0f, 3.0f); - glTexCoord2f(uv_ratio,0.0f); - glVertex3f(onebythree, 0.0f, 3.0f); - glEnd(); - - glDisable(GL_TEXTURE_2D); - glEnable(GL_DEPTH_TEST); -} - -void KX_Dome::DrawDomeFisheye(void) -{ - int i; - - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - - // Making the viewport always square - - int can_width = m_viewport.GetRight(); - int can_height = m_viewport.GetTop(); - - float ortho_width, ortho_height; - - if (m_mode == DOME_FISHEYE) { - if (warp.usemesh) - glOrtho((-1.0f), 1.0f, (-1.0f), 1.0f, -20.0f, 10.0f); //stretch the image to reduce resolution lost - - else { - if (can_width < can_height) { - ortho_width = 1.0f; - ortho_height = (float)can_height/can_width; - } - else { - ortho_width = (float)can_width/can_height; - ortho_height = 1.0f; - } - - glOrtho((-ortho_width), ortho_width, (-ortho_height), ortho_height, -20.0f, 10.0f); - } - } - else if (m_mode == DOME_TRUNCATED_FRONT) - { - ortho_width = 1.0f; - ortho_height = 2.0f * ((float)can_height / can_width) - 1.0f; - - glOrtho((-ortho_width), ortho_width, (-ortho_height), ortho_width, -20.0f, 10.0f); - } - else { //m_mode == DOME_TRUNCATED_REAR - ortho_width = 1.0f; - ortho_height = 2.0f * ((float)can_height / can_width) - 1.0f; - - glOrtho((-ortho_width), ortho_width, (-ortho_width), ortho_height, -20.0f, 10.0f); - } - - glMatrixMode(GL_TEXTURE); - glLoadIdentity(); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - gpuLookAt(0.0f,-1.0f,0.0f, 0.0f,0.0f,0.0f, 0.0f,0.0f,1.0f); - - if (m_drawingmode == RAS_IRasterizer::KX_WIREFRAME) - glPolygonMode(GL_FRONT, GL_LINE); - else - glPolygonMode(GL_FRONT, GL_FILL); - - glShadeModel(GL_SMOOTH); - glDisable(GL_LIGHTING); - glDisable(GL_DEPTH_TEST); - - glEnable(GL_TEXTURE_2D); - glColor3f(1.0f,1.0f,1.0f); - - if (dlistSupported) { - for (i=0;i 180) { - // front triangle - glBindTexture(GL_TEXTURE_2D, domefacesId[4]); - GLDrawTriangles(cubefront, nfacesfront); - } - } - glDisable(GL_TEXTURE_2D); - glEnable(GL_DEPTH_TEST); -} - -void KX_Dome::DrawPanorama(void) -{ - int i; - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - - // Making the viewport always square - - int can_width = m_viewport.GetRight(); - int can_height = m_viewport.GetTop(); - - float ortho_height = 1.0f; - float ortho_width = 1.0f; - - if (warp.usemesh) - glOrtho((-1.0f), 1.0f, (-0.5f), 0.5f, -20.0f, 10.0f); //stretch the image to reduce resolution lost - - else { - //using all the screen - if ((can_width / 2) <= (can_height)) { - ortho_width = 1.0f; - ortho_height = (float)can_height/can_width; - } - else { - ortho_width = (float)can_width / can_height * 0.5f; - ortho_height = 0.5f; - } - - glOrtho((-ortho_width), ortho_width, (-ortho_height), ortho_height, -20.0f, 10.0f); - } - - glMatrixMode(GL_TEXTURE); - glLoadIdentity(); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - gpuLookAt(0.0f,-1.0f,0.0f, 0.0f,0.0f,0.0f, 0.0f,0.0f,1.0f); - - if (m_drawingmode == RAS_IRasterizer::KX_WIREFRAME) - glPolygonMode(GL_FRONT, GL_LINE); - else - glPolygonMode(GL_FRONT, GL_FILL); - - glShadeModel(GL_SMOOTH); - glDisable(GL_LIGHTING); - glDisable(GL_DEPTH_TEST); - - glEnable(GL_TEXTURE_2D); - glColor3f(1.0f,1.0f,1.0f); - - if (dlistSupported) { - for (i=0;i (top) - glBindTexture(GL_TEXTURE_2D, domefacesId[0]); - GLDrawTriangles(cubetop, nfacestop); - - // domefacesId[5] => (bottom) - glBindTexture(GL_TEXTURE_2D, domefacesId[1]); - GLDrawTriangles(cubebottom, nfacesbottom); - - // domefacesId[1] => -45deg (left) - glBindTexture(GL_TEXTURE_2D, domefacesId[2]); - GLDrawTriangles(cubeleft, nfacesleft); - - // domefacesId[2] => 45deg (right) - glBindTexture(GL_TEXTURE_2D, domefacesId[3]); - GLDrawTriangles(cuberight, nfacesright); - - // domefacesId[0] => -135deg (leftback) - glBindTexture(GL_TEXTURE_2D, domefacesId[4]); - GLDrawTriangles(cubeleftback, nfacesleftback); - - // domefacesId[3] => 135deg (rightback) - glBindTexture(GL_TEXTURE_2D, domefacesId[5]); - GLDrawTriangles(cuberightback, nfacesrightback); - } - glDisable(GL_TEXTURE_2D); - glEnable(GL_DEPTH_TEST); -} - -void KX_Dome::DrawDomeWarped(void) -{ - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - - // Making the viewport always square - int can_width = m_viewport.GetRight(); - int can_height = m_viewport.GetTop(); - - double screen_ratio = can_width/ (double) can_height; - - glOrtho(-screen_ratio,screen_ratio,-1.0f,1.0f,-20.0f,10.0f); - - - glMatrixMode(GL_TEXTURE); - glLoadIdentity(); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - gpuLookAt(0.0f, 0.0f, 1.0f, 0.0f,0.0f,0.0f, 0.0f,1.0f,0.0f); - - if (m_drawingmode == RAS_IRasterizer::KX_WIREFRAME) - glPolygonMode(GL_FRONT, GL_LINE); - else - glPolygonMode(GL_FRONT, GL_FILL); - - glShadeModel(GL_SMOOTH); - glDisable(GL_LIGHTING); - glDisable(GL_DEPTH_TEST); - - glEnable(GL_TEXTURE_2D); - glColor3f(1.0f,1.0f,1.0f); - - if (dlistSupported) { - glBindTexture(GL_TEXTURE_2D, domefacesId[m_numfaces]); - glCallList(dlistId + m_numfaces); - } - else { - glBindTexture(GL_TEXTURE_2D, domefacesId[m_numfaces]); - GLDrawWarpQuads(); - } - glDisable(GL_TEXTURE_2D); - glEnable(GL_DEPTH_TEST); -} - -void KX_Dome::BindImages(int i) -{ - glBindTexture(GL_TEXTURE_2D, domefacesId[i]); - glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, m_viewport.GetLeft(), m_viewport.GetBottom(), m_buffersize, m_buffersize); -} - -void KX_Dome::RenderDomeFrame(KX_Scene* scene, KX_Camera* cam, int i) -{ - if (!cam) - return; - - m_canvas->SetViewPort(0,0,m_buffersize-1,m_buffersize-1); - -// m_rasterizer->SetAmbient(); - m_rasterizer->DisplayFog(); - - CalculateFrustum(cam); //calculates m_projmat - cam->SetProjectionMatrix(m_projmat); - m_rasterizer->SetProjectionMatrix(cam->GetProjectionMatrix()); -// Dome_RotateCamera(cam,i); - - MT_Matrix3x3 camori = cam->GetSGNode()->GetLocalOrientation(); - - cam->NodeSetLocalOrientation(camori*m_locRot[i]); - cam->NodeUpdateGS(0.f); - - MT_Transform camtrans(cam->GetWorldToCamera()); - MT_Matrix4x4 viewmat(camtrans); - m_rasterizer->SetViewMatrix(viewmat, cam->NodeGetWorldOrientation(), cam->NodeGetWorldPosition(), cam->NodeGetLocalScaling(), 1.0f); - cam->SetModelviewMatrix(viewmat); - - // restore the original orientation - cam->NodeSetLocalOrientation(camori); - cam->NodeUpdateGS(0.f); - - scene->CalculateVisibleMeshes(m_rasterizer,cam); - - m_engine->UpdateAnimations(scene); - - scene->RenderBuckets(camtrans, m_rasterizer); -} - diff --git a/source/gameengine/Ketsji/KX_Dome.h b/source/gameengine/Ketsji/KX_Dome.h deleted file mode 100644 index 5a0c4588ae2..00000000000 --- a/source/gameengine/Ketsji/KX_Dome.h +++ /dev/null @@ -1,197 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * Contributor(s): Dalai Felinto - * - * This source uses some of the ideas and code from Paul Bourke. - * Developed as part of a Research and Development project for - * SAT - La Société des arts technologiques. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_Dome.h - * \ingroup ketsji - */ - -#ifndef __KX_DOME_H__ -#define __KX_DOME_H__ - -#include "KX_Scene.h" -#include "KX_Camera.h" -#include "DNA_screen_types.h" -#include "RAS_ICanvas.h" -#include "RAS_IRasterizer.h" -#include "KX_KetsjiEngine.h" - -#include "GPU_glew.h" -#include - -#include "MEM_guardedalloc.h" -#include "BKE_text.h" - -//Dome modes: limit hardcoded in buttons_scene.c -#define DOME_FISHEYE 1 -#define DOME_TRUNCATED_FRONT 2 -#define DOME_TRUNCATED_REAR 3 -#define DOME_ENVMAP 4 -#define DOME_PANORAM_SPH 5 -#define DOME_NUM_MODES 6 - - -/// class for render 3d scene -class KX_Dome -{ -public: - /// constructor - KX_Dome (RAS_ICanvas* m_canvas, - /// rasterizer - RAS_IRasterizer* m_rasterizer, - /// engine - KX_KetsjiEngine* m_engine, - - short res, - short mode, - short angle, - float resbuf, - short tilt, - struct Text* warptext - ); - - /// destructor - virtual ~KX_Dome (void); - - //openGL checks: - bool dlistSupported; - bool fboSupported; - - //openGL names: - GLuint domefacesId[7]; /* ID of the images -- room for 7 images, using only 4 for 180deg x 360deg dome, - * 6 for panoramic and +1 for warp mesh */ - GLuint dlistId; /* ID of the Display Lists of the images (used as an offset) */ - - typedef struct { - double u[3], v[3]; - MT_Vector3 verts[3]; //three verts - } DomeFace; - - //mesh warp functions - typedef struct { - double x, y, u, v, i; - } WarpMeshNode; - - struct { - bool usemesh; - int mode; - int n_width, n_height; //nodes width and height - int imagesize; - int bufferwidth, bufferheight; - GLuint fboId; - vector > nodes; - } warp; - - bool ParseWarpMesh(STR_String text); - - vector cubetop, cubebottom, cuberight, cubeleft, cubefront, cubeback; //for fisheye - vector cubeleftback, cuberightback; //for panorama - - int nfacestop, nfacesbottom, nfacesleft, nfacesright, nfacesfront, nfacesback; - int nfacesleftback, nfacesrightback; - - int GetNumberRenders() { return m_numfaces; } - - void RenderDome(void); - void RenderDomeFrame(KX_Scene* scene, KX_Camera* cam, int i); - void BindImages(int i); - - void SetViewPort(const int viewport[4]); - void CalculateFrustum(KX_Camera* cam); - void RotateCamera(KX_Camera* cam, int i); - - //Mesh creation Functions - void CreateMeshDome180(void); - void CreateMeshDome250(void); - void CreateMeshPanorama(void); - - void SplitFace(vector & face, int *nfaces); - - void FlattenDome(MT_Vector3 verts[3]); - void FlattenPanorama(MT_Vector3 verts[3]); - - //Draw functions - void GLDrawTriangles(vector & face, int nfaces); - void GLDrawWarpQuads(void); - void Draw(void); - void DrawDomeFisheye(void); - void DrawEnvMap(void); - void DrawPanorama(void); - void DrawDomeWarped(void); - - //setting up openGL - void CreateGLImages(void); - void ClearGLImages(void);//called on resize - bool CreateDL(void); //create Display Lists - void ClearDL(void); //remove Display Lists - bool CreateFBO(void);//create FBO (for warp mesh) - void ClearFBO(void); //remove FBO - - void CalculateCameraOrientation(); - void CalculateImageSize(); //set m_imagesize - - int canvaswidth; - int canvasheight; - -protected: - int m_drawingmode; - - int m_imagesize; - int m_buffersize; // canvas small dimension - int m_numfaces; // 4 to 6 depending on the kind of dome image - int m_numimages; //numfaces +1 if we have warp mesh - - short m_resolution; //resolution to tessellate the mesh - short m_mode; // the mode (truncated, warped, panoramic,...) - short m_angle; //the angle of the fisheye - float m_radangle; //the angle of the fisheye in radians - float m_resbuffer; //the resolution of the buffer - short m_tilt; //the dome tilt (camera rotation on horizontal axis) - - RAS_Rect m_viewport; - - MT_Matrix4x4 m_projmat; - - MT_Matrix3x3 m_locRot[6]; // the rotation matrix - - /// rendered scene - KX_Scene * m_scene; - - /// canvas - RAS_ICanvas* m_canvas; - /// rasterizer - RAS_IRasterizer* m_rasterizer; - /// render tools - RAS_IRenderTools* m_rendertools; - /// engine - KX_KetsjiEngine* m_engine; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_Dome") -#endif -}; - -#endif /* __KX_DOME_H__ */ diff --git a/source/gameengine/Ketsji/KX_EmptyObject.cpp b/source/gameengine/Ketsji/KX_EmptyObject.cpp deleted file mode 100644 index 670329a4350..00000000000 --- a/source/gameengine/Ketsji/KX_EmptyObject.cpp +++ /dev/null @@ -1,37 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_EmptyObject.cpp - * \ingroup ketsji - */ - -#include "KX_EmptyObject.h" - -KX_EmptyObject::~KX_EmptyObject() -{ - -} diff --git a/source/gameengine/Ketsji/KX_EmptyObject.h b/source/gameengine/Ketsji/KX_EmptyObject.h deleted file mode 100644 index 63a0782a544..00000000000 --- a/source/gameengine/Ketsji/KX_EmptyObject.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_EmptyObject.h - * \ingroup ketsji - */ - -#ifndef __KX_EMPTYOBJECT_H__ -#define __KX_EMPTYOBJECT_H__ -#include "KX_GameObject.h" - -class KX_EmptyObject : public KX_GameObject -{ -public: - KX_EmptyObject(void* sgReplicationInfo,SG_Callbacks callbacks) : - KX_GameObject(sgReplicationInfo,callbacks) - {}; - virtual ~KX_EmptyObject(); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_EmptyObject") -#endif -}; - -#endif /* __KX_EMPTYOBJECT_H__ */ diff --git a/source/gameengine/Ketsji/KX_FontObject.cpp b/source/gameengine/Ketsji/KX_FontObject.cpp deleted file mode 100644 index ae79284288d..00000000000 --- a/source/gameengine/Ketsji/KX_FontObject.cpp +++ /dev/null @@ -1,300 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_FontObject.cpp - * \ingroup ketsji - */ - -#include "KX_FontObject.h" -#include "DNA_curve_types.h" -#include "DNA_vfont_types.h" -#include "KX_Scene.h" -#include "KX_PythonInit.h" -#include "BLI_math.h" -#include "EXP_StringValue.h" -#include "RAS_IRasterizer.h" - -/* paths needed for font load */ -#include "BLI_blenlib.h" -#include "BKE_global.h" -#include "BKE_font.h" -#include "BKE_main.h" -#include "DNA_packedFile_types.h" - -extern "C" { -#include "BLF_api.h" -} - -#define BGE_FONT_RES 100 - -/* proptotype */ -int GetFontId(VFont *font); - -static std::vector split_string(STR_String str) -{ - std::vector text = std::vector(); - - /* Split the string upon new lines */ - int begin=0, end=0; - while (end < str.Length()) - { - if (str.GetAt(end) == '\n') - { - text.push_back(str.Mid(begin, end-begin)); - begin = end+1; - } - end++; - } - //Now grab the last line - text.push_back(str.Mid(begin, end-begin)); - - return text; -} - -KX_FontObject::KX_FontObject(void* sgReplicationInfo, - SG_Callbacks callbacks, - RAS_IRasterizer* rasterizer, - Object *ob, - bool do_color_management): - KX_GameObject(sgReplicationInfo, callbacks), - m_object(ob), - m_dpi(72), - m_resolution(1.f), - m_rasterizer(rasterizer), - m_do_color_management(do_color_management) -{ - Curve *text = static_cast (ob->data); - m_text = split_string(text->str); - m_fsize = text->fsize; - m_line_spacing = text->linedist; - m_offset = MT_Vector3(text->xof, text->yof, 0); - - m_fontid = GetFontId(text->vfont); - - /* initialize the color with the object color and store it in the KX_Object class - * This is a workaround waiting for the fix: - * [#25487] BGE: Object Color only works when it has a keyed frame */ - copy_v4_v4(m_color, (const float*) ob->col); - this->SetObjectColor((const MT_Vector4&) m_color); -} - -KX_FontObject::~KX_FontObject() -{ - //remove font from the scene list - //it's handled in KX_Scene::NewRemoveObject -} - -CValue* KX_FontObject::GetReplica() -{ - KX_FontObject* replica = new KX_FontObject(*this); - replica->ProcessReplica(); - return replica; -} - -void KX_FontObject::ProcessReplica() -{ - KX_GameObject::ProcessReplica(); -} - -int GetFontId(VFont *vfont) -{ - PackedFile *packedfile=NULL; - int fontid = -1; - - if (vfont->packedfile) { - packedfile= vfont->packedfile; - fontid= BLF_load_mem(vfont->name, (unsigned char*)packedfile->data, packedfile->size); - - if (fontid == -1) { - printf("ERROR: packed font \"%s\" could not be loaded.\n", vfont->name); - fontid = BLF_load("default"); - } - return fontid; - } - - /* once we have packed working we can load the builtin font */ - const char *filepath = vfont->name; - if (BKE_vfont_is_builtin(vfont)) { - fontid = BLF_load("default"); - - /* XXX the following code is supposed to work (after you add get_builtin_packedfile to BKE_font.h ) - * unfortunately it's crashing on blf_glyph.c:173 because gc->glyph_width_max is 0 - */ - // packedfile=get_builtin_packedfile(); - // fontid= BLF_load_mem(font->name, (unsigned char*)packedfile->data, packedfile->size); - // return fontid; - - return BLF_load("default"); - } - - /* convert from absolute to relative */ - char expanded[256]; // font names can be bigger than FILE_MAX (240) - BLI_strncpy(expanded, filepath, 256); - BLI_path_abs(expanded, G.main->name); - - fontid = BLF_load(expanded); - - /* fallback */ - if (fontid == -1) - fontid = BLF_load("default"); - - return fontid; -} - -void KX_FontObject::DrawFontText() -{ - /* Allow for some logic brick control */ - if (this->GetProperty("Text")) - m_text = split_string(this->GetProperty("Text")->GetText()); - - /* only draws the text if visible */ - if (this->GetVisible() == 0) return; - - /* update the animated color */ - this->GetObjectColor().getValue(m_color); - - /* Font Objects don't use the glsl shader, this color management code is copied from gpu_shader_material.glsl */ - float color[4]; - if (m_do_color_management) { - linearrgb_to_srgb_v4(color, m_color); - } - else { - copy_v4_v4(color, m_color); - } - - /* HARDCODED MULTIPLICATION FACTOR - this will affect the render resolution directly */ - const float RES = BGE_FONT_RES * m_resolution; - - const float size = m_fsize * this->NodeGetWorldScaling()[0] * RES; - const float aspect = m_fsize / size; - - /* Get a working copy of the OpenGLMatrix to use */ - float *mat = GetOpenGLMatrix(); - - /* Account for offset */ - MT_Vector3 offset = this->NodeGetWorldOrientation() * m_offset * this->NodeGetWorldScaling(); - mat[12] += offset[0]; mat[13] += offset[1]; mat[14] += offset[2]; - - /* Orient the spacing vector */ - MT_Vector3 spacing = MT_Vector3(0.0f, m_fsize*m_line_spacing, 0.0f); - spacing = this->NodeGetWorldOrientation() * spacing * this->NodeGetWorldScaling()[1]; - - /* Draw each line, taking spacing into consideration */ - for (int i=0; iRenderText3D(m_fontid, m_text[i], int(size), m_dpi, color, mat, aspect); - } -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python Integration Hooks */ -/* ------------------------------------------------------------------------- */ - -PyTypeObject KX_FontObject::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_FontObject", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0, - &KX_GameObject::Sequence, - &KX_GameObject::Mapping, - 0,0,0, - NULL, - NULL, - 0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &KX_GameObject::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_FontObject::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_FontObject::Attributes[] = { - //KX_PYATTRIBUTE_STRING_RW("text", 0, 280, false, KX_FontObject, m_text[0]), //arbitrary limit. 280 = 140 unicode chars in unicode - KX_PYATTRIBUTE_RW_FUNCTION("text", KX_FontObject, pyattr_get_text, pyattr_set_text), - KX_PYATTRIBUTE_FLOAT_RW("size", 0.0001f, 10000.0f, KX_FontObject, m_fsize), - KX_PYATTRIBUTE_FLOAT_RW("resolution", 0.0001f, 10000.0f, KX_FontObject, m_resolution), - /* KX_PYATTRIBUTE_INT_RW("dpi", 0, 10000, false, KX_FontObject, m_dpi), */// no real need for expose this I think - { NULL } //Sentinel -}; - -PyObject *KX_FontObject::pyattr_get_text(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_FontObject* self = static_cast(self_v); - STR_String str = STR_String(); - for (int i=0; im_text.size(); ++i) - { - if (i!=0) - str += '\n'; - str += self->m_text[i]; - } - return PyUnicode_From_STR_String(str); -} - -int KX_FontObject::pyattr_set_text(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_FontObject* self = static_cast(self_v); - if (!PyUnicode_Check(value)) - return PY_SET_ATTR_FAIL; - const char *chars = _PyUnicode_AsString(value); - - /* Allow for some logic brick control */ - CValue* tprop = self->GetProperty("Text"); - if (tprop) { - CValue *newstringprop = new CStringValue(STR_String(chars), "Text"); - self->SetProperty("Text", newstringprop); - newstringprop->Release(); - } - else { - self->m_text = split_string(STR_String(chars)); - } - - return PY_SET_ATTR_SUCCESS; -} - -#endif // WITH_PYTHON diff --git a/source/gameengine/Ketsji/KX_FontObject.h b/source/gameengine/Ketsji/KX_FontObject.h deleted file mode 100644 index bf70eedfde6..00000000000 --- a/source/gameengine/Ketsji/KX_FontObject.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_FontObject.h - * \ingroup ketsji - */ - -#ifndef __KX_FONTOBJECT_H__ -#define __KX_FONTOBJECT_H__ -#include "KX_GameObject.h" - -class KX_FontObject : public KX_GameObject -{ -public: - Py_Header - KX_FontObject(void* sgReplicationInfo, - SG_Callbacks callbacks, - RAS_IRasterizer* rasterizer, - Object *ob, - bool do_color_management); - - virtual ~KX_FontObject(); - - void DrawFontText(); - - /** - * Inherited from CValue -- return a new copy of this - * instance allocated on the heap. Ownership of the new - * object belongs with the caller. - */ - virtual CValue* GetReplica(); - virtual void ProcessReplica(); - virtual int GetGameObjectType() { return OBJ_TEXT; } - -protected: - std::vector m_text; - Object* m_object; - int m_fontid; - int m_dpi; - float m_fsize; - float m_resolution; - float m_color[4]; - float m_line_spacing; - MT_Vector3 m_offset; - - class RAS_IRasterizer* m_rasterizer; //needed for drawing routine - - bool m_do_color_management; - -#ifdef WITH_PYTHON - static PyObject* pyattr_get_text(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_text(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); -#endif - -}; - -#endif /* __KX_FONTOBJECT_H__ */ diff --git a/source/gameengine/Ketsji/KX_GameActuator.cpp b/source/gameengine/Ketsji/KX_GameActuator.cpp deleted file mode 100644 index f1bd253f8b3..00000000000 --- a/source/gameengine/Ketsji/KX_GameActuator.cpp +++ /dev/null @@ -1,267 +0,0 @@ -/* - * global game stuff - * - * - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_GameActuator.cpp - * \ingroup ketsji - */ - - -#include - -#include "SCA_IActuator.h" -#include "KX_GameActuator.h" -//#include -#include "KX_Scene.h" -#include "KX_KetsjiEngine.h" -#include "KX_PythonInit.h" /* for config load/saving */ -#include "RAS_ICanvas.h" - -#include -#include - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -KX_GameActuator::KX_GameActuator(SCA_IObject *gameobj, - int mode, - const STR_String& filename, - const STR_String& loadinganimationname, - SCA_IScene* scene, - KX_KetsjiEngine* ketsjiengine) - : SCA_IActuator(gameobj, KX_ACT_GAME) -{ - m_mode = mode; - m_filename = filename; - m_loadinganimationname = loadinganimationname; - m_scene = scene; - m_ketsjiengine = ketsjiengine; -} /* End of constructor */ - - - -KX_GameActuator::~KX_GameActuator() -{ - // there's nothing to be done here, really.... -} /* end of destructor */ - - - -CValue* KX_GameActuator::GetReplica() -{ - KX_GameActuator* replica = new KX_GameActuator(*this); - replica->ProcessReplica(); - - return replica; -} - - - -bool KX_GameActuator::Update() -{ - // bool result = false; /*unused*/ - bool bNegativeEvent = IsNegativeEvent(); - RemoveAllEvents(); - - if (bNegativeEvent) - return false; // do nothing on negative events - - switch (m_mode) - { - case KX_GAME_LOAD: - case KX_GAME_START: - { - if (m_ketsjiengine) - { - STR_String exitstring = "start other game"; - m_ketsjiengine->RequestExit(KX_EXIT_REQUEST_START_OTHER_GAME); - m_ketsjiengine->SetNameNextGame(m_filename); - m_scene->AddDebugProperty((this)->GetParent(), exitstring); - } - - break; - } - case KX_GAME_RESTART: - { - if (m_ketsjiengine) - { - STR_String exitstring = "restarting game"; - m_ketsjiengine->RequestExit(KX_EXIT_REQUEST_RESTART_GAME); - m_ketsjiengine->SetNameNextGame(m_filename); - m_scene->AddDebugProperty((this)->GetParent(), exitstring); - } - break; - } - case KX_GAME_QUIT: - { - if (m_ketsjiengine) - { - STR_String exitstring = "quiting game"; - m_ketsjiengine->RequestExit(KX_EXIT_REQUEST_QUIT_GAME); - m_scene->AddDebugProperty((this)->GetParent(), exitstring); - } - break; - } - case KX_GAME_SAVECFG: - { -#ifdef WITH_PYTHON - if (m_ketsjiengine) - { - char mashal_path[512]; - char *marshal_buffer = NULL; - unsigned int marshal_length; - FILE *fp = NULL; - - pathGamePythonConfig(mashal_path); - marshal_length = saveGamePythonConfig(&marshal_buffer); - - if (marshal_length && marshal_buffer) { - fp = fopen(mashal_path, "wb"); - if (fp) { - if (fwrite(marshal_buffer, 1, marshal_length, fp) != marshal_length) { - printf("Warning: could not write marshal data\n"); - } - fclose(fp); - } else { - printf("Warning: could not open marshal file\n"); - } - } else { - printf("Warning: could not create marshal buffer\n"); - } - if (marshal_buffer) - delete [] marshal_buffer; - } - break; -#endif // WITH_PYTHON - } - case KX_GAME_LOADCFG: - { -#ifdef WITH_PYTHON - if (m_ketsjiengine) - { - char mashal_path[512]; - char *marshal_buffer; - int marshal_length; - FILE *fp = NULL; - int result; - - pathGamePythonConfig(mashal_path); - - fp = fopen(mashal_path, "rb"); - if (fp) { - // obtain file size: - fseek (fp , 0 , SEEK_END); - marshal_length = ftell(fp); - if (marshal_length == -1) { - printf("warning: could not read position of '%s'\n", mashal_path); - fclose(fp); - break; - } - rewind(fp); - - marshal_buffer = (char*) malloc (sizeof(char)*marshal_length); - - result = fread (marshal_buffer, 1, marshal_length, fp); - - if (result == marshal_length) { - loadGamePythonConfig(marshal_buffer, marshal_length); - } else { - printf("warning: could not read all of '%s'\n", mashal_path); - } - - free(marshal_buffer); - fclose(fp); - } else { - printf("warning: could not open '%s'\n", mashal_path); - } - } - break; -#endif // WITH_PYTHON - } - case KX_GAME_SCREENSHOT: - { - RAS_ICanvas *canvas = m_ketsjiengine->GetCanvas(); - if (canvas) { - canvas->MakeScreenShot(m_filename); - } - else { - printf("KX_GAME_SCREENSHOT error: Rasterizer not available"); - } - break; - } - default: - ; /* do nothing? this is an internal error !!! */ - } - - return false; -} - - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject KX_GameActuator::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_GameActuator", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &SCA_IActuator::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_GameActuator::Methods[] = -{ - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_GameActuator::Attributes[] = { - KX_PYATTRIBUTE_STRING_RW("fileName",0,100,false,KX_GameActuator,m_filename), - KX_PYATTRIBUTE_INT_RW("mode", KX_GAME_NODEF+1, KX_GAME_MAX-1, true, KX_GameActuator, m_mode), - { NULL } //Sentinel -}; - -#endif // WITH_PYTHON diff --git a/source/gameengine/Ketsji/KX_GameActuator.h b/source/gameengine/Ketsji/KX_GameActuator.h deleted file mode 100644 index 57472836bb2..00000000000 --- a/source/gameengine/Ketsji/KX_GameActuator.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_GameActuator.h - * \ingroup ketsji - * \brief actuator for global game stuff - */ - -#ifndef __KX_GAMEACTUATOR_H__ -#define __KX_GAMEACTUATOR_H__ - -#include "SCA_IActuator.h" - -#include "SCA_IScene.h" /* Replace_IScene only */ -#include "KX_Scene.h" /* Replace_IScene only */ - -class KX_GameActuator : public SCA_IActuator -{ - Py_Header -protected: - int m_mode; - bool m_restart; - STR_String m_filename; - STR_String m_loadinganimationname; - class SCA_IScene* m_scene; - class KX_KetsjiEngine* m_ketsjiengine; - - public: - enum KX_GameActuatorMode - { - KX_GAME_NODEF = 0, - KX_GAME_LOAD, - KX_GAME_START, - KX_GAME_RESTART, - KX_GAME_QUIT, - KX_GAME_SAVECFG, - KX_GAME_LOADCFG, - KX_GAME_SCREENSHOT, - KX_GAME_MAX - - }; - - KX_GameActuator(SCA_IObject* gameobj, - int mode, - const STR_String& filename, - const STR_String& loadinganimationname, - SCA_IScene* scene, - KX_KetsjiEngine* ketsjiEngine); - virtual ~KX_GameActuator(); - - virtual CValue* GetReplica(); - - virtual bool Update(); - - virtual void Replace_IScene(SCA_IScene *val) - { - m_scene= val; - }; - - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - -}; /* end of class KX_GameActuator */ - -#endif - diff --git a/source/gameengine/Ketsji/KX_GameObject.cpp b/source/gameengine/Ketsji/KX_GameObject.cpp deleted file mode 100644 index 3244400e1bd..00000000000 --- a/source/gameengine/Ketsji/KX_GameObject.cpp +++ /dev/null @@ -1,4203 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - * Game object wrapper - */ - -/** \file gameengine/Ketsji/KX_GameObject.cpp - * \ingroup ketsji - */ - -#ifdef _MSC_VER - /* This warning tells us about truncation of __long__ stl-generated names. - * It can occasionally cause DevStudio to have internal compiler warnings. */ -# pragma warning( disable:4786 ) -#endif - -#include "RAS_IPolygonMaterial.h" -#include "KX_BlenderMaterial.h" -#include "KX_GameObject.h" -#include "KX_Camera.h" // only for their ::Type -#include "KX_Light.h" // only for their ::Type -#include "KX_FontObject.h" // only for their ::Type -#include "RAS_MeshObject.h" -#include "KX_NavMeshObject.h" -#include "KX_MeshProxy.h" -#include "KX_PolyProxy.h" -#include // printf -#include "SG_Controller.h" -#include "PHY_IGraphicController.h" -#include "SG_Node.h" -#include "KX_ClientObjectInfo.h" -#include "RAS_BucketManager.h" -#include "KX_RayCast.h" -#include "KX_PythonInit.h" -#include "KX_PyMath.h" -#include "SCA_IActuator.h" -#include "SCA_ISensor.h" -#include "SCA_IController.h" -#include "NG_NetworkScene.h" //Needed for sendMessage() -#include "KX_ObstacleSimulation.h" -#include "KX_Scene.h" - -#include "BKE_object.h" - -#include "BL_ActionManager.h" -#include "BL_Action.h" - -#include "EXP_PyObjectPlus.h" /* python stuff */ -#include "EXP_ListWrapper.h" -#include "BLI_utildefines.h" - -#ifdef WITH_PYTHON -# include "EXP_PythonCallBack.h" -# include "python_utildefines.h" -#endif - -// This file defines relationships between parents and children -// in the game engine. - -#include "KX_SG_NodeRelationships.h" - -#include "BLI_math.h" - -static MT_Point3 dummy_point= MT_Point3(0.0f, 0.0f, 0.0f); -static MT_Vector3 dummy_scaling = MT_Vector3(1.0f, 1.0f, 1.0f); -static MT_Matrix3x3 dummy_orientation = MT_Matrix3x3(1.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 1.0f); - -KX_GameObject::KX_GameObject( - void* sgReplicationInfo, - SG_Callbacks callbacks) - : SCA_IObject(), - m_bDyna(false), - m_layer(0), - m_currentLodLevel(0), - m_previousLodLevel(0), - m_pBlenderObject(NULL), - m_pBlenderGroupObject(NULL), - m_bUseObjectColor(false), - m_bIsNegativeScaling(false), - m_objectColor(1.0f, 1.0f, 1.0f, 1.0f), - m_bVisible(true), - m_bCulled(true), - m_bOccluder(false), - m_pPhysicsController(NULL), - m_pGraphicController(NULL), - m_pObstacleSimulation(NULL), - m_pInstanceObjects(NULL), - m_pDupliGroupObject(NULL), - m_actionManager(NULL), - m_bRecordAnimation(false), - m_isDeformable(false) - -#ifdef WITH_PYTHON - , m_attr_dict(NULL), - m_collisionCallbacks(NULL) -#endif -{ - m_ignore_activity_culling = false; - m_pClient_info = new KX_ClientObjectInfo(this, KX_ClientObjectInfo::ACTOR); - m_pSGNode = new SG_Node(this,sgReplicationInfo,callbacks); - - // define the relationship between this node and it's parent. - - KX_NormalParentRelation * parent_relation = - KX_NormalParentRelation::New(); - m_pSGNode->SetParentRelation(parent_relation); -}; - - - -KX_GameObject::~KX_GameObject() -{ -#ifdef WITH_PYTHON - if (m_attr_dict) { - PyDict_Clear(m_attr_dict); /* in case of circular refs or other weird cases */ - /* Py_CLEAR: Py_DECREF's and NULL's */ - Py_CLEAR(m_attr_dict); - } - // Unregister collision callbacks - // Do this before we start freeing physics information like m_pClient_info - if (m_collisionCallbacks) { - UnregisterCollisionCallbacks(); - Py_CLEAR(m_collisionCallbacks); - } -#endif // WITH_PYTHON - - RemoveMeshes(); - - // is this delete somewhere ? - //if (m_sumoObj) - // delete m_sumoObj; - delete m_pClient_info; - //if (m_pSGNode) - // delete m_pSGNode; - if (m_pSGNode) - { - // must go through controllers and make sure they will not use us anymore - // This is important for KX_BulletPhysicsControllers that unregister themselves - // from the object when they are deleted. - SGControllerList::iterator contit; - SGControllerList& controllers = m_pSGNode->GetSGControllerList(); - for (contit = controllers.begin();contit!=controllers.end();++contit) - { - (*contit)->ClearObject(); - } - m_pSGNode->SetSGClientObject(NULL); - - /* m_pSGNode is freed in KX_Scene::RemoveNodeDestructObject */ - } - if (m_pGraphicController) - { - delete m_pGraphicController; - } - - if (m_pPhysicsController) - { - delete m_pPhysicsController; - } - - if (m_pObstacleSimulation) - { - m_pObstacleSimulation->DestroyObstacleForObj(this); - } - - if (m_actionManager) - { - delete m_actionManager; - } - - if (m_pDupliGroupObject) - { - m_pDupliGroupObject->Release(); - } - - if (m_pInstanceObjects) - { - m_pInstanceObjects->Release(); - } -} - -KX_GameObject* KX_GameObject::GetClientObject(KX_ClientObjectInfo *info) -{ - if (!info) - return NULL; - return info->m_gameobject; -} - -CValue* KX_GameObject:: Calc(VALUE_OPERATOR op, CValue *val) -{ - return NULL; -} - - - -CValue* KX_GameObject::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val) -{ - return NULL; -} - - - -const STR_String & KX_GameObject::GetText() -{ - return m_text; -} - - - -double KX_GameObject::GetNumber() -{ - return 0; -} - - - -STR_String& KX_GameObject::GetName() -{ - return m_name; -} - - -/* Set the name of the value */ -void KX_GameObject::SetName(const char *name) -{ - m_name = name; -} - -PHY_IPhysicsController* KX_GameObject::GetPhysicsController() -{ - return m_pPhysicsController; -} - -KX_GameObject* KX_GameObject::GetDupliGroupObject() -{ - return m_pDupliGroupObject; -} - -CListValue* KX_GameObject::GetInstanceObjects() -{ - return m_pInstanceObjects; -} - -void KX_GameObject::AddInstanceObjects(KX_GameObject* obj) -{ - if (!m_pInstanceObjects) - m_pInstanceObjects = new CListValue(); - - obj->AddRef(); - m_pInstanceObjects->Add(obj); -} - -void KX_GameObject::RemoveInstanceObject(KX_GameObject* obj) -{ - assert(m_pInstanceObjects); - m_pInstanceObjects->RemoveValue(obj); - obj->Release(); -} - -void KX_GameObject::RemoveDupliGroupObject() -{ - if (m_pDupliGroupObject) { - m_pDupliGroupObject->Release(); - m_pDupliGroupObject = NULL; - } -} - -void KX_GameObject::SetDupliGroupObject(KX_GameObject* obj) -{ - obj->AddRef(); - m_pDupliGroupObject = obj; -} - -void KX_GameObject::AddConstraint(bRigidBodyJointConstraint *cons) -{ - m_constraints.push_back(cons); -} - -std::vector KX_GameObject::GetConstraints() -{ - return m_constraints; -} - -void KX_GameObject::ClearConstraints() -{ - m_constraints.clear(); -} - -KX_GameObject* KX_GameObject::GetParent() -{ - KX_GameObject* result = NULL; - SG_Node* node = m_pSGNode; - - while (node && !result) - { - node = node->GetSGParent(); - if (node) - result = (KX_GameObject*)node->GetSGClientObject(); - } - - return result; - -} - -void KX_GameObject::SetParent(KX_Scene *scene, KX_GameObject* obj, bool addToCompound, bool ghost) -{ - // check on valid node in case a python controller holds a reference to a deleted object - if (obj && - GetSGNode() && // object is not zombi - obj->GetSGNode() && // object is not zombi - GetSGNode()->GetSGParent() != obj->GetSGNode() && // not already parented to same object - !GetSGNode()->IsAncessor(obj->GetSGNode()) && // no parenting loop - this != obj) // not the object itself - { - // Make sure the objects have some scale - MT_Vector3 scale1 = NodeGetWorldScaling(); - MT_Vector3 scale2 = obj->NodeGetWorldScaling(); - if (fabs(scale2[0]) < (MT_Scalar)FLT_EPSILON || - fabs(scale2[1]) < (MT_Scalar)FLT_EPSILON || - fabs(scale2[2]) < (MT_Scalar)FLT_EPSILON || - fabs(scale1[0]) < (MT_Scalar)FLT_EPSILON || - fabs(scale1[1]) < (MT_Scalar)FLT_EPSILON || - fabs(scale1[2]) < (MT_Scalar)FLT_EPSILON) { return; } - - // Remove us from our old parent and set our new parent - RemoveParent(scene); - obj->GetSGNode()->AddChild(GetSGNode()); - - if (m_pPhysicsController) - { - m_pPhysicsController->SuspendDynamics(ghost); - } - // Set us to our new scale, position, and orientation - scale2[0] = 1.0f/scale2[0]; - scale2[1] = 1.0f/scale2[1]; - scale2[2] = 1.0f/scale2[2]; - scale1 = scale1 * scale2; - MT_Matrix3x3 invori = obj->NodeGetWorldOrientation().inverse(); - MT_Vector3 newpos = invori*(NodeGetWorldPosition()-obj->NodeGetWorldPosition())*scale2; - - NodeSetLocalScale(scale1); - NodeSetLocalPosition(MT_Point3(newpos[0],newpos[1],newpos[2])); - NodeSetLocalOrientation(invori*NodeGetWorldOrientation()); - NodeUpdateGS(0.f); - // object will now be a child, it must be removed from the parent list - CListValue* rootlist = scene->GetRootParentList(); - if (rootlist->RemoveValue(this)) - // the object was in parent list, decrement ref count as it's now removed - Release(); - // if the new parent is a compound object, add this object shape to the compound shape. - // step 0: verify this object has physical controller - if (m_pPhysicsController && addToCompound) - { - // step 1: find the top parent (not necessarily obj) - KX_GameObject* rootobj = (KX_GameObject*)obj->GetSGNode()->GetRootSGParent()->GetSGClientObject(); - // step 2: verify it has a physical controller and compound shape - if (rootobj != NULL && - rootobj->m_pPhysicsController != NULL && - rootobj->m_pPhysicsController->IsCompound()) - { - rootobj->m_pPhysicsController->AddCompoundChild(m_pPhysicsController); - } - } - // graphically, the object hasn't change place, no need to update m_pGraphicController - } -} - -void KX_GameObject::RemoveParent(KX_Scene *scene) -{ - // check on valid node in case a python controller holds a reference to a deleted object - if (GetSGNode() && GetSGNode()->GetSGParent()) - { - // get the root object to remove us from compound object if needed - KX_GameObject* rootobj = (KX_GameObject*)GetSGNode()->GetRootSGParent()->GetSGClientObject(); - // Set us to the right spot - GetSGNode()->SetLocalScale(GetSGNode()->GetWorldScaling()); - GetSGNode()->SetLocalOrientation(GetSGNode()->GetWorldOrientation()); - GetSGNode()->SetLocalPosition(GetSGNode()->GetWorldPosition()); - - // Remove us from our parent - GetSGNode()->DisconnectFromParent(); - NodeUpdateGS(0.f); - // the object is now a root object, add it to the parentlist - CListValue* rootlist = scene->GetRootParentList(); - if (!rootlist->SearchValue(this)) - // object was not in root list, add it now and increment ref count - rootlist->Add(AddRef()); - if (m_pPhysicsController) - { - // in case this controller was added as a child shape to the parent - if (rootobj != NULL && - rootobj->m_pPhysicsController != NULL && - rootobj->m_pPhysicsController->IsCompound()) - { - rootobj->m_pPhysicsController->RemoveCompoundChild(m_pPhysicsController); - } - m_pPhysicsController->RestoreDynamics(); - if (m_pPhysicsController->IsDynamic() && (rootobj != NULL && rootobj->m_pPhysicsController)) - { - // dynamic object should remember the velocity they had while being parented - MT_Point3 childPoint = GetSGNode()->GetWorldPosition(); - MT_Point3 rootPoint = rootobj->GetSGNode()->GetWorldPosition(); - MT_Point3 relPoint; - relPoint = (childPoint-rootPoint); - MT_Vector3 linVel = rootobj->m_pPhysicsController->GetVelocity(relPoint); - MT_Vector3 angVel = rootobj->m_pPhysicsController->GetAngularVelocity(); - m_pPhysicsController->SetLinearVelocity(linVel, false); - m_pPhysicsController->SetAngularVelocity(angVel, false); - } - } - // graphically, the object hasn't change place, no need to update m_pGraphicController - } -} - -BL_ActionManager* KX_GameObject::GetActionManager() -{ - // We only want to create an action manager if we need it - if (!m_actionManager) - { - GetScene()->AddAnimatedObject(this); - m_actionManager = new BL_ActionManager(this); - } - return m_actionManager; -} - -bool KX_GameObject::PlayAction(const char* name, - float start, - float end, - short layer, - short priority, - float blendin, - short play_mode, - float layer_weight, - short ipo_flags, - float playback_speed, - short blend_mode) -{ - return GetActionManager()->PlayAction(name, start, end, layer, priority, blendin, play_mode, layer_weight, ipo_flags, playback_speed, blend_mode); -} - -void KX_GameObject::StopAction(short layer) -{ - GetActionManager()->StopAction(layer); -} - -void KX_GameObject::RemoveTaggedActions() -{ - GetActionManager()->RemoveTaggedActions(); -} - -bool KX_GameObject::IsActionDone(short layer) -{ - return GetActionManager()->IsActionDone(layer); -} - -void KX_GameObject::UpdateActionManager(float curtime) -{ - GetActionManager()->Update(curtime); -} - -float KX_GameObject::GetActionFrame(short layer) -{ - return GetActionManager()->GetActionFrame(layer); -} - -const char *KX_GameObject::GetActionName(short layer) -{ - return GetActionManager()->GetActionName(layer); -} - -void KX_GameObject::SetActionFrame(short layer, float frame) -{ - GetActionManager()->SetActionFrame(layer, frame); -} - -bAction *KX_GameObject::GetCurrentAction(short layer) -{ - return GetActionManager()->GetCurrentAction(layer); -} - -void KX_GameObject::SetPlayMode(short layer, short mode) -{ - GetActionManager()->SetPlayMode(layer, mode); -} - -void KX_GameObject::SetTimes(short layer, float start, float end) -{ - GetActionManager()->SetTimes(layer, start, end); -} - -void KX_GameObject::ProcessReplica() -{ - SCA_IObject::ProcessReplica(); - - m_pGraphicController = NULL; - m_pPhysicsController = NULL; - m_pSGNode = NULL; - - /* Dupli group and instance list are set later in replication. - * See KX_Scene::DupliGroupRecurse. */ - m_pDupliGroupObject = NULL; - m_pInstanceObjects = NULL; - m_pClient_info = new KX_ClientObjectInfo(*m_pClient_info); - m_pClient_info->m_gameobject = this; - m_actionManager = NULL; - m_state = 0; - - KX_Scene* scene = KX_GetActiveScene(); - KX_ObstacleSimulation* obssimulation = scene->GetObstacleSimulation(); - struct Object* blenderobject = GetBlenderObject(); - if (obssimulation && (blenderobject->gameflag & OB_HASOBSTACLE)) - { - obssimulation->AddObstacleForObj(this); - } - -#ifdef WITH_PYTHON - if (m_attr_dict) - m_attr_dict= PyDict_Copy(m_attr_dict); -#endif - -} - -static void setGraphicController_recursive(SG_Node* node) -{ - NodeList& children = node->GetSGChildren(); - - for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit) - { - SG_Node* childnode = (*childit); - KX_GameObject *clientgameobj = static_cast( (*childit)->GetSGClientObject()); - if (clientgameobj != NULL) // This is a GameObject - clientgameobj->ActivateGraphicController(false); - - // if the childobj is NULL then this may be an inverse parent link - // so a non recursive search should still look down this node. - setGraphicController_recursive(childnode); - } -} - - -void KX_GameObject::ActivateGraphicController(bool recurse) -{ - if (m_pGraphicController) - { - m_pGraphicController->Activate(m_bVisible); - } - if (recurse) - { - setGraphicController_recursive(GetSGNode()); - } -} - -void KX_GameObject::SetUserCollisionGroup(unsigned short group) -{ - m_userCollisionGroup = group; - if (m_pPhysicsController) - m_pPhysicsController->RefreshCollisions(); -} -void KX_GameObject::SetUserCollisionMask(unsigned short mask) -{ - m_userCollisionMask = mask; - if (m_pPhysicsController) - m_pPhysicsController->RefreshCollisions(); -} - -unsigned short KX_GameObject::GetUserCollisionGroup() -{ - return m_userCollisionGroup; -} -unsigned short KX_GameObject::GetUserCollisionMask() -{ - return m_userCollisionMask; -} - -bool KX_GameObject::CheckCollision(KX_GameObject* other) -{ - return this->m_userCollisionGroup & other->m_userCollisionMask; -} - -CValue* KX_GameObject::GetReplica() -{ - KX_GameObject* replica = new KX_GameObject(*this); - - // this will copy properties and so on... - replica->ProcessReplica(); - - return replica; -} - -bool KX_GameObject::IsDynamicsSuspended() const -{ - if (m_pPhysicsController) - return m_pPhysicsController->IsSuspended(); - return false; -} - -float KX_GameObject::getLinearDamping() const -{ - if (m_pPhysicsController) - return m_pPhysicsController->GetLinearDamping(); - return 0; -} - -float KX_GameObject::getAngularDamping() const -{ - if (m_pPhysicsController) - return m_pPhysicsController->GetAngularDamping(); - return 0; -} - -void KX_GameObject::setLinearDamping(float damping) -{ - if (m_pPhysicsController) - m_pPhysicsController->SetLinearDamping(damping); -} - - -void KX_GameObject::setAngularDamping(float damping) -{ - if (m_pPhysicsController) - m_pPhysicsController->SetAngularDamping(damping); -} - - -void KX_GameObject::setDamping(float linear, float angular) -{ - if (m_pPhysicsController) - m_pPhysicsController->SetDamping(linear, angular); -} - - -void KX_GameObject::ApplyForce(const MT_Vector3& force,bool local) -{ - if (m_pPhysicsController) - m_pPhysicsController->ApplyForce(force,local); -} - - - -void KX_GameObject::ApplyTorque(const MT_Vector3& torque,bool local) -{ - if (m_pPhysicsController) - m_pPhysicsController->ApplyTorque(torque,local); -} - - - -void KX_GameObject::ApplyMovement(const MT_Vector3& dloc,bool local) -{ - if (GetSGNode()) - { - if (m_pPhysicsController) // (IsDynamic()) - { - m_pPhysicsController->RelativeTranslate(dloc,local); - } - GetSGNode()->RelativeTranslate(dloc,GetSGNode()->GetSGParent(),local); - } -} - - - -void KX_GameObject::ApplyRotation(const MT_Vector3& drot,bool local) -{ - MT_Matrix3x3 rotmat(drot); - - if (GetSGNode()) { - GetSGNode()->RelativeRotate(rotmat,local); - - if (m_pPhysicsController) { // (IsDynamic()) - m_pPhysicsController->RelativeRotate(rotmat,local); - } - } -} - - - -/** - * GetOpenGL Matrix, returns an OpenGL 'compatible' matrix - */ -float *KX_GameObject::GetOpenGLMatrix() -{ - // todo: optimize and only update if necessary - float *fl = m_OpenGL_4x4Matrix.getPointer(); - if (GetSGNode()) { - MT_Transform trans; - - trans.setOrigin(GetSGNode()->GetWorldPosition()); - trans.setBasis(GetSGNode()->GetWorldOrientation()); - - MT_Vector3 scaling = GetSGNode()->GetWorldScaling(); - m_bIsNegativeScaling = ((scaling[0] < 0.0f) ^ (scaling[1] < 0.0f) ^ (scaling[2] < 0.0f)) ? true : false; - trans.scale(scaling[0], scaling[1], scaling[2]); - trans.getValue(fl); - GetSGNode()->ClearDirty(); - } - return fl; -} - -void KX_GameObject::UpdateBlenderObjectMatrix(Object* blendobj) -{ - if (!blendobj) - blendobj = m_pBlenderObject; - if (blendobj) { - const MT_Matrix3x3& rot = NodeGetWorldOrientation(); - const MT_Vector3& scale = NodeGetWorldScaling(); - const MT_Vector3& pos = NodeGetWorldPosition(); - rot.getValue(blendobj->obmat[0]); - pos.getValue(blendobj->obmat[3]); - mul_v3_fl(blendobj->obmat[0], scale[0]); - mul_v3_fl(blendobj->obmat[1], scale[1]); - mul_v3_fl(blendobj->obmat[2], scale[2]); - } -} - -void KX_GameObject::AddMeshUser() -{ - for (size_t i=0;iAddMeshUser(this, &m_meshSlots, GetDeformer()); - } - // set the part of the mesh slot that never change - float *fl = GetOpenGLMatrixPtr()->getPointer(); - - SG_QList::iterator mit(m_meshSlots); -// RAS_MeshSlot* ms; - for (mit.begin(); !mit.end(); ++mit) - { - (*mit)->m_OpenGLMatrix = fl; - } - UpdateBuckets(false); -} - -static void UpdateBuckets_recursive(SG_Node* node) -{ - NodeList& children = node->GetSGChildren(); - - for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit) - { - SG_Node* childnode = (*childit); - KX_GameObject *clientgameobj = static_cast( (*childit)->GetSGClientObject()); - if (clientgameobj != NULL) // This is a GameObject - clientgameobj->UpdateBuckets(0); - - // if the childobj is NULL then this may be an inverse parent link - // so a non recursive search should still look down this node. - UpdateBuckets_recursive(childnode); - } -} - -void KX_GameObject::UpdateBuckets( bool recursive ) -{ - if (GetSGNode()) { - RAS_MeshSlot *ms; - - if (GetSGNode()->IsDirty()) - GetOpenGLMatrix(); - - SG_QList::iterator mit(m_meshSlots); - for (mit.begin(); !mit.end(); ++mit) - { - ms = *mit; - ms->m_bObjectColor = m_bUseObjectColor; - ms->m_RGBAcolor = m_objectColor; - ms->m_bVisible = m_bVisible; - ms->m_bCulled = m_bCulled || !m_bVisible; - if (!ms->m_bCulled) - ms->m_bucket->ActivateMesh(ms); - - /* split if necessary */ -#ifdef USE_SPLIT - ms->Split(); -#endif - } - - if (recursive) { - UpdateBuckets_recursive(GetSGNode()); - } - } -} - -void KX_GameObject::RemoveMeshes() -{ - for (size_t i=0;iRemoveFromBuckets(this); - - //note: meshes can be shared, and are deleted by KX_BlenderSceneConverter - - m_meshes.clear(); -} - -void KX_GameObject::AddLodMesh(RAS_MeshObject* mesh) -{ - m_lodmeshes.push_back(mesh); -} - - -static float calcHysteresis(KX_Scene *kxscene, LodLevel *lod) -{ - float hystvariance = 0.0f; - - if (!kxscene->IsActivedLodHysteresis()) - return hystvariance; - - short hysteresis = 0; - // if exists, LoD level hysteresis will override scene hysteresis - if (lod->next->flags & OB_LOD_USE_HYST) - hysteresis = lod->next->obhysteresis; - else - hysteresis = kxscene->GetLodHysteresisValue(); - - return hystvariance = MT_abs(lod->next->distance - lod->distance) * hysteresis / 100; -} - -void KX_GameObject::UpdateLod(MT_Vector3 &cam_pos) -{ - // Handle dupligroups - if (m_pInstanceObjects) { - KX_GameObject *instob; - int count = m_pInstanceObjects->GetCount(); - for (int i = 0; i < count; i++) { - instob = (KX_GameObject*)m_pInstanceObjects->GetValue(i); - instob->UpdateLod(cam_pos); - } - } - - if (m_lodmeshes.empty()) - return; - - MT_Vector3 delta = NodeGetWorldPosition() - cam_pos; - float distance2 = delta.length2(); - - int level = 0; - float hystvariance = 0.0f; - Object *bob = GetBlenderObject(); - LodLevel *lod = (LodLevel *)bob->lodlevels.first; - KX_Scene *kxscene = GetScene(); - - for (; lod; lod = lod->next, level++) { - if (!lod->source || lod->source->type != OB_MESH) - level--; - - if (!lod->next) - break; - - if (level == m_previousLodLevel || level == (m_previousLodLevel + 1)) { - hystvariance = calcHysteresis(kxscene, lod); - float newdistance = lod->next->distance + hystvariance; - if (newdistance * newdistance > distance2) - break; - } - else if (level == (m_previousLodLevel - 1)) { - hystvariance = calcHysteresis(kxscene, lod); - float newdistance = lod->next->distance - hystvariance; - if (newdistance * newdistance > distance2) - break; - } - } - - RAS_MeshObject *mesh = m_lodmeshes[level]; - m_currentLodLevel = level; - if (mesh != m_meshes[0]) { - m_previousLodLevel = level; - GetScene()->ReplaceMesh(this, mesh, true, false); - } -} - -void KX_GameObject::UpdateTransform() -{ - // HACK: saves function call for dynamic object, they are handled differently - if (m_pPhysicsController && !m_pPhysicsController->IsDynamic()) - m_pPhysicsController->SetTransform(); - if (m_pGraphicController) - // update the culling tree - m_pGraphicController->SetGraphicTransform(); - -} - -void KX_GameObject::UpdateTransformFunc(SG_IObject* node, void* gameobj, void* scene) -{ - ((KX_GameObject*)gameobj)->UpdateTransform(); -} - -void KX_GameObject::SynchronizeTransform() -{ - // only used for sensor object, do full synchronization as bullet doesn't do it - if (m_pPhysicsController) - m_pPhysicsController->SetTransform(); - if (m_pGraphicController) - m_pGraphicController->SetGraphicTransform(); -} - -void KX_GameObject::SynchronizeTransformFunc(SG_IObject* node, void* gameobj, void* scene) -{ - ((KX_GameObject*)gameobj)->SynchronizeTransform(); -} - - -void KX_GameObject::SetDebugColor(unsigned int bgra) -{ - for (size_t i=0;iDebugColor(bgra); -} - - - -void KX_GameObject::ResetDebugColor() -{ - SetDebugColor(0xff000000); -} - -void KX_GameObject::InitIPO(bool ipo_as_force, - bool ipo_add, - bool ipo_local) -{ - SGControllerList::iterator it = GetSGNode()->GetSGControllerList().begin(); - - while (it != GetSGNode()->GetSGControllerList().end()) { - (*it)->SetOption(SG_Controller::SG_CONTR_IPO_RESET, true); - (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_AS_FORCE, ipo_as_force); - (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_ADD, ipo_add); - (*it)->SetOption(SG_Controller::SG_CONTR_IPO_LOCAL, ipo_local); - it++; - } -} - -void KX_GameObject::UpdateIPO(float curframetime, - bool recurse) -{ - /* This function shouldn't call BL_Action::Update, not even indirectly, - * as it will cause deadlock due to the lock in BL_Action::Update. */ - - // just the 'normal' update procedure. - GetSGNode()->SetSimulatedTime(curframetime,recurse); - GetSGNode()->UpdateWorldData(curframetime); - UpdateTransform(); -} - -// IPO update -void -KX_GameObject::UpdateMaterialData( - dword matname_hash, - MT_Vector4 rgba, - MT_Vector3 specrgb, - MT_Scalar hard, - MT_Scalar spec, - MT_Scalar ref, - MT_Scalar emit, - MT_Scalar alpha - - ) -{ - int mesh = 0; - if (((unsigned int)mesh < m_meshes.size()) && mesh >= 0) { - list::iterator mit = m_meshes[mesh]->GetFirstMaterial(); - - for (; mit != m_meshes[mesh]->GetLastMaterial(); ++mit) - { - RAS_IPolyMaterial* poly = mit->m_bucket->GetPolyMaterial(); - - if (poly->GetFlag() & RAS_BLENDERMAT ) - { - KX_BlenderMaterial *m = static_cast(poly); - - if (matname_hash == 0) - { - m->UpdateIPO(rgba, specrgb,hard,spec,ref,emit, alpha); - // if mesh has only one material attached to it then use original hack with no need to edit vertices (better performance) - SetObjectColor(rgba); - } - else - { - if (matname_hash == poly->GetMaterialNameHash()) - { - m->UpdateIPO(rgba, specrgb,hard,spec,ref,emit, alpha); - m_meshes[mesh]->SetVertexColor(poly,rgba); - - // no break here, because one blender material can be split into several game engine materials - // (e.g. one uvsphere material is split into one material at poles with ras_mode TRIANGLE and one material for the body - // if here was a break then would miss some vertices if material was split - } - } - } - } - } -} -bool -KX_GameObject::GetVisible( - void - ) -{ - return m_bVisible; -} - -static void setVisible_recursive(SG_Node* node, bool v) -{ - NodeList& children = node->GetSGChildren(); - - for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit) - { - SG_Node* childnode = (*childit); - KX_GameObject *clientgameobj = static_cast( (*childit)->GetSGClientObject()); - if (clientgameobj != NULL) // This is a GameObject - clientgameobj->SetVisible(v, 0); - - // if the childobj is NULL then this may be an inverse parent link - // so a non recursive search should still look down this node. - setVisible_recursive(childnode, v); - } -} - - -void -KX_GameObject::SetVisible( - bool v, - bool recursive - ) -{ - if (GetSGNode()) { - m_bVisible = v; - if (m_pGraphicController) - m_pGraphicController->Activate(m_bVisible); - if (recursive) - setVisible_recursive(GetSGNode(), v); - } -} - -static void setOccluder_recursive(SG_Node* node, bool v) -{ - NodeList& children = node->GetSGChildren(); - - for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit) - { - SG_Node* childnode = (*childit); - KX_GameObject *clientgameobj = static_cast( (*childit)->GetSGClientObject()); - if (clientgameobj != NULL) // This is a GameObject - clientgameobj->SetOccluder(v, false); - - // if the childobj is NULL then this may be an inverse parent link - // so a non recursive search should still look down this node. - setOccluder_recursive(childnode, v); - } -} - -void -KX_GameObject::SetOccluder( - bool v, - bool recursive - ) -{ - if (GetSGNode()) { - m_bOccluder = v; - if (recursive) - setOccluder_recursive(GetSGNode(), v); - } -} - -static void setDebug_recursive(SG_Node *node, bool debug) -{ - NodeList& children = node->GetSGChildren(); - KX_Scene *scene = KX_GetActiveScene(); - - for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit) { - SG_Node *childnode = (*childit); - KX_GameObject *clientgameobj = static_cast( (*childit)->GetSGClientObject()); - if (clientgameobj != NULL) { - if (debug) { - if (!scene->ObjectInDebugList(clientgameobj)) - scene->AddObjectDebugProperties(clientgameobj); - } - else - scene->RemoveObjectDebugProperties(clientgameobj); - } - - /* if the childobj is NULL then this may be an inverse parent link - * so a non recursive search should still look down this node. */ - setDebug_recursive(childnode, debug); - } -} - -void KX_GameObject::SetUseDebugProperties( bool debug, bool recursive ) -{ - KX_Scene *scene = KX_GetActiveScene(); - - if (debug) { - if (!scene->ObjectInDebugList(this)) - scene->AddObjectDebugProperties(this); - } - else - scene->RemoveObjectDebugProperties(this); - - if (recursive) - setDebug_recursive(GetSGNode(), debug); -} - -void -KX_GameObject::SetLayer( - int l - ) -{ - m_layer = l; -} - -int -KX_GameObject::GetLayer( - void - ) -{ - return m_layer; -} - -void KX_GameObject::addLinearVelocity(const MT_Vector3& lin_vel,bool local) -{ - if (m_pPhysicsController) - { - MT_Vector3 lv = local ? NodeGetWorldOrientation() * lin_vel : lin_vel; - m_pPhysicsController->SetLinearVelocity(lv + m_pPhysicsController->GetLinearVelocity(), 0); - } -} - - - -void KX_GameObject::setLinearVelocity(const MT_Vector3& lin_vel,bool local) -{ - if (m_pPhysicsController) - m_pPhysicsController->SetLinearVelocity(lin_vel,local); -} - - - -void KX_GameObject::setAngularVelocity(const MT_Vector3& ang_vel,bool local) -{ - if (m_pPhysicsController) - m_pPhysicsController->SetAngularVelocity(ang_vel,local); -} - - -void KX_GameObject::ResolveCombinedVelocities( - const MT_Vector3 & lin_vel, - const MT_Vector3 & ang_vel, - bool lin_vel_local, - bool ang_vel_local -) { - if (m_pPhysicsController) - { - - MT_Vector3 lv = lin_vel_local ? NodeGetWorldOrientation() * lin_vel : lin_vel; - MT_Vector3 av = ang_vel_local ? NodeGetWorldOrientation() * ang_vel : ang_vel; - m_pPhysicsController->ResolveCombinedVelocities( - lv.x(),lv.y(),lv.z(),av.x(),av.y(),av.z()); - } -} - - -void KX_GameObject::SetObjectColor(const MT_Vector4& rgbavec) -{ - m_bUseObjectColor = true; - m_objectColor = rgbavec; -} - -const MT_Vector4& KX_GameObject::GetObjectColor() -{ - return m_objectColor; -} - -void KX_GameObject::AlignAxisToVect(const MT_Vector3& dir, int axis, float fac) -{ - const MT_Scalar eps = 3.0f * MT_EPSILON; - MT_Matrix3x3 orimat; - MT_Vector3 vect,ori,z,x,y; - MT_Scalar len; - - // check on valid node in case a python controller holds a reference to a deleted object - if (!GetSGNode()) - return; - - vect = dir; - len = vect.length(); - if (MT_fuzzyZero(len)) - { - cout << "alignAxisToVect() Error: Null vector!\n"; - return; - } - - if (fac <= 0.0f) { - return; - } - - // normalize - vect /= len; - orimat = GetSGNode()->GetWorldOrientation(); - switch (axis) - { - case 0: // align x axis of new coord system to vect - ori.setValue(orimat[0][2], orimat[1][2], orimat[2][2]); // pivot axis - if (1.0f - MT_abs(vect.dot(ori)) < eps) { // vect parallel to pivot? - ori.setValue(orimat[0][1], orimat[1][1], orimat[2][1]); // change the pivot! - } - - if (fac == 1.0f) { - x = vect; - } else { - x = (vect * fac) + ((orimat * MT_Vector3(1.0f, 0.0f, 0.0f)) * (1.0f - fac)); - len = x.length(); - if (MT_fuzzyZero(len)) x = vect; - else x /= len; - } - y = ori.cross(x); - z = x.cross(y); - break; - case 1: // y axis - ori.setValue(orimat[0][0], orimat[1][0], orimat[2][0]); - if (1.0f - MT_abs(vect.dot(ori)) < eps) { - ori.setValue(orimat[0][2], orimat[1][2], orimat[2][2]); - } - - if (fac == 1.0f) { - y = vect; - } else { - y = (vect * fac) + ((orimat * MT_Vector3(0.0f, 1.0f, 0.0f)) * (1.0f - fac)); - len = y.length(); - if (MT_fuzzyZero(len)) y = vect; - else y /= len; - } - z = ori.cross(y); - x = y.cross(z); - break; - case 2: // z axis - ori.setValue(orimat[0][1], orimat[1][1], orimat[2][1]); - if (1.0f - MT_abs(vect.dot(ori)) < eps) { - ori.setValue(orimat[0][0], orimat[1][0], orimat[2][0]); - } - - if (fac == 1.0f) { - z = vect; - } else { - z = (vect * fac) + ((orimat * MT_Vector3(0.0f, 0.0f, 1.0f)) * (1.0f - fac)); - len = z.length(); - if (MT_fuzzyZero(len)) z = vect; - else z /= len; - } - x = ori.cross(z); - y = z.cross(x); - break; - default: // invalid axis specified - cout << "alignAxisToVect(): Invalid axis '" << axis <<"'\n"; - return; - } - x.normalize(); // normalize the new base vectors - y.normalize(); - z.normalize(); - orimat.setValue(x[0], y[0], z[0], - x[1], y[1], z[1], - x[2], y[2], z[2]); - - if (GetSGNode()->GetSGParent() != NULL) - { - // the object is a child, adapt its local orientation so that - // the global orientation is aligned as we want (cancelling out the parent orientation) - MT_Matrix3x3 invori = GetSGNode()->GetSGParent()->GetWorldOrientation().inverse(); - NodeSetLocalOrientation(invori*orimat); - } - else { - NodeSetLocalOrientation(orimat); - } -} - -MT_Scalar KX_GameObject::GetMass() -{ - if (m_pPhysicsController) - { - return m_pPhysicsController->GetMass(); - } - return 0.0f; -} - -MT_Vector3 KX_GameObject::GetLocalInertia() -{ - MT_Vector3 local_inertia(0.0f,0.0f,0.0f); - if (m_pPhysicsController) - { - local_inertia = m_pPhysicsController->GetLocalInertia(); - } - return local_inertia; -} - -MT_Vector3 KX_GameObject::GetLinearVelocity(bool local) -{ - MT_Vector3 velocity(0.0f,0.0f,0.0f), locvel; - MT_Matrix3x3 ori; - if (m_pPhysicsController) - { - velocity = m_pPhysicsController->GetLinearVelocity(); - - if (local) - { - ori = GetSGNode()->GetWorldOrientation(); - - locvel = velocity * ori; - return locvel; - } - } - return velocity; -} - -MT_Vector3 KX_GameObject::GetAngularVelocity(bool local) -{ - MT_Vector3 velocity(0.0f,0.0f,0.0f), locvel; - MT_Matrix3x3 ori; - if (m_pPhysicsController) - { - velocity = m_pPhysicsController->GetAngularVelocity(); - - if (local) - { - ori = GetSGNode()->GetWorldOrientation(); - - locvel = velocity * ori; - return locvel; - } - } - return velocity; -} - -MT_Vector3 KX_GameObject::GetVelocity(const MT_Point3& point) -{ - if (m_pPhysicsController) - { - return m_pPhysicsController->GetVelocity(point); - } - return MT_Vector3(0.0f,0.0f,0.0f); -} - -// scenegraph node stuff - -void KX_GameObject::NodeSetLocalPosition(const MT_Point3& trans) -{ - // check on valid node in case a python controller holds a reference to a deleted object - if (!GetSGNode()) - return; - - if (m_pPhysicsController && !GetSGNode()->GetSGParent()) - { - // don't update physic controller if the object is a child: - // 1) the transformation will not be right - // 2) in this case, the physic controller is necessarily a static object - // that is updated from the normal kinematic synchronization - m_pPhysicsController->SetPosition(trans); - } - - GetSGNode()->SetLocalPosition(trans); - -} - - - -void KX_GameObject::NodeSetLocalOrientation(const MT_Matrix3x3& rot) -{ - // check on valid node in case a python controller holds a reference to a deleted object - if (!GetSGNode()) - return; - - if (m_pPhysicsController && !GetSGNode()->GetSGParent()) - { - // see note above - m_pPhysicsController->SetOrientation(rot); - } - GetSGNode()->SetLocalOrientation(rot); -} - -void KX_GameObject::NodeSetGlobalOrientation(const MT_Matrix3x3& rot) -{ - // check on valid node in case a python controller holds a reference to a deleted object - if (!GetSGNode()) - return; - - if (GetSGNode()->GetSGParent()) - GetSGNode()->SetLocalOrientation(GetSGNode()->GetSGParent()->GetWorldOrientation().inverse()*rot); - else - NodeSetLocalOrientation(rot); -} - -void KX_GameObject::NodeSetLocalScale(const MT_Vector3& scale) -{ - // check on valid node in case a python controller holds a reference to a deleted object - if (!GetSGNode()) - return; - - if (m_pPhysicsController && !GetSGNode()->GetSGParent()) - { - // see note above - m_pPhysicsController->SetScaling(scale); - } - GetSGNode()->SetLocalScale(scale); -} - - - -void KX_GameObject::NodeSetRelativeScale(const MT_Vector3& scale) -{ - if (GetSGNode()) - { - GetSGNode()->RelativeScale(scale); - if (m_pPhysicsController && (!GetSGNode()->GetSGParent())) - { - // see note above - // we can use the local scale: it's the same thing for a root object - // and the world scale is not yet updated - MT_Vector3 newscale = GetSGNode()->GetLocalScale(); - m_pPhysicsController->SetScaling(newscale); - } - } -} - -void KX_GameObject::NodeSetWorldScale(const MT_Vector3& scale) -{ - if (!GetSGNode()) - return; - SG_Node* parent = GetSGNode()->GetSGParent(); - if (parent != NULL) - { - // Make sure the objects have some scale - MT_Vector3 p_scale = parent->GetWorldScaling(); - if (fabs(p_scale[0]) < (MT_Scalar)FLT_EPSILON || - fabs(p_scale[1]) < (MT_Scalar)FLT_EPSILON || - fabs(p_scale[2]) < (MT_Scalar)FLT_EPSILON) - { - return; - } - - p_scale[0] = 1/p_scale[0]; - p_scale[1] = 1/p_scale[1]; - p_scale[2] = 1/p_scale[2]; - - NodeSetLocalScale(scale * p_scale); - } - else - { - NodeSetLocalScale(scale); - } -} - -void KX_GameObject::NodeSetWorldPosition(const MT_Point3& trans) -{ - if (!GetSGNode()) - return; - SG_Node* parent = GetSGNode()->GetSGParent(); - if (parent != NULL) - { - // Make sure the objects have some scale - MT_Vector3 scale = parent->GetWorldScaling(); - if (fabs(scale[0]) < (MT_Scalar)FLT_EPSILON || - fabs(scale[1]) < (MT_Scalar)FLT_EPSILON || - fabs(scale[2]) < (MT_Scalar)FLT_EPSILON) - { - return; - } - scale[0] = 1.0f/scale[0]; - scale[1] = 1.0f/scale[1]; - scale[2] = 1.0f/scale[2]; - MT_Matrix3x3 invori = parent->GetWorldOrientation().inverse(); - MT_Vector3 newpos = invori*(trans-parent->GetWorldPosition())*scale; - NodeSetLocalPosition(MT_Point3(newpos[0],newpos[1],newpos[2])); - } - else - { - NodeSetLocalPosition(trans); - } -} - - -void KX_GameObject::NodeUpdateGS(double time) -{ - if (GetSGNode()) - GetSGNode()->UpdateWorldData(time); -} - - - -const MT_Matrix3x3& KX_GameObject::NodeGetWorldOrientation() const -{ - // check on valid node in case a python controller holds a reference to a deleted object - if (!GetSGNode()) - return dummy_orientation; - return GetSGNode()->GetWorldOrientation(); -} - -const MT_Matrix3x3& KX_GameObject::NodeGetLocalOrientation() const -{ - // check on valid node in case a python controller holds a reference to a deleted object - if (!GetSGNode()) - return dummy_orientation; - return GetSGNode()->GetLocalOrientation(); -} - -const MT_Vector3& KX_GameObject::NodeGetWorldScaling() const -{ - // check on valid node in case a python controller holds a reference to a deleted object - if (!GetSGNode()) - return dummy_scaling; - - return GetSGNode()->GetWorldScaling(); -} - -const MT_Vector3& KX_GameObject::NodeGetLocalScaling() const -{ - // check on valid node in case a python controller holds a reference to a deleted object - if (!GetSGNode()) - return dummy_scaling; - - return GetSGNode()->GetLocalScale(); -} - -const MT_Point3& KX_GameObject::NodeGetWorldPosition() const -{ - // check on valid node in case a python controller holds a reference to a deleted object - if (GetSGNode()) - return GetSGNode()->GetWorldPosition(); - else - return dummy_point; -} - -const MT_Point3& KX_GameObject::NodeGetLocalPosition() const -{ - // check on valid node in case a python controller holds a reference to a deleted object - if (GetSGNode()) - return GetSGNode()->GetLocalPosition(); - else - return dummy_point; -} - - -void KX_GameObject::UnregisterCollisionCallbacks() -{ - if (!GetPhysicsController()) { - printf("Warning, trying to unregister collision callbacks for object without collisions: %s!\n", GetName().ReadPtr()); - return; - } - - // Unregister from callbacks - KX_Scene* scene = GetScene(); - PHY_IPhysicsEnvironment* pe = scene->GetPhysicsEnvironment(); - PHY_IPhysicsController* spc = GetPhysicsController(); - // If we are the last to unregister on this physics controller - if (pe->RemoveCollisionCallback(spc)) { - // If we are a sensor object - if (m_pClient_info->isSensor()) - // Remove sensor body from physics world - pe->RemoveSensor(spc); - } -} - -void KX_GameObject::RegisterCollisionCallbacks() -{ - if (!GetPhysicsController()) { - printf("Warning, trying to register collision callbacks for object without collisions: %s!\n", GetName().ReadPtr()); - return; - } - - // Register from callbacks - KX_Scene* scene = GetScene(); - PHY_IPhysicsEnvironment* pe = scene->GetPhysicsEnvironment(); - PHY_IPhysicsController* spc = GetPhysicsController(); - // If we are the first to register on this physics controller - if (pe->RequestCollisionCallback(spc)) { - // If we are a sensor object - if (m_pClient_info->isSensor()) - // Add sensor body to physics world - pe->AddSensor(spc); - } -} -void KX_GameObject::RunCollisionCallbacks(KX_GameObject *collider, const MT_Vector3 &point, const MT_Vector3 &normal) -{ -#ifdef WITH_PYTHON - if (!m_collisionCallbacks || PyList_GET_SIZE(m_collisionCallbacks) == 0) - return; - - PyObject *args[] = {collider->GetProxy(), PyObjectFrom(point), PyObjectFrom(normal)}; - RunPythonCallBackList(m_collisionCallbacks, args, 1, ARRAY_SIZE(args)); - - for (unsigned int i = 0; i < ARRAY_SIZE(args); ++i) { - Py_DECREF(args[i]); - } -#endif -} - -/* Suspend/ resume: for the dynamic behavior, there is a simple - * method. For the residual motion, there is not. I wonder what the - * correct solution is for Sumo. Remove from the motion-update tree? - * - * So far, only switch the physics and logic. - * */ - -void KX_GameObject::Resume(void) -{ - if (m_suspended) { - SCA_IObject::Resume(); - // Child objects must be static, so we block changing to dynamic - if (GetPhysicsController() && !GetParent()) - GetPhysicsController()->RestoreDynamics(); - - m_suspended = false; - } -} - -void KX_GameObject::Suspend() -{ - if ((!m_ignore_activity_culling) && (!m_suspended)) { - SCA_IObject::Suspend(); - if (GetPhysicsController()) - GetPhysicsController()->SuspendDynamics(); - m_suspended = true; - } -} - -static void walk_children(SG_Node* node, CListValue* list, bool recursive) -{ - if (!node) - return; - NodeList& children = node->GetSGChildren(); - - for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit) - { - SG_Node* childnode = (*childit); - CValue* childobj = (CValue*)childnode->GetSGClientObject(); - if (childobj != NULL) // This is a GameObject - { - // add to the list - list->Add(childobj->AddRef()); - } - - // if the childobj is NULL then this may be an inverse parent link - // so a non recursive search should still look down this node. - if (recursive || childobj==NULL) { - walk_children(childnode, list, recursive); - } - } -} - -CListValue* KX_GameObject::GetChildren() -{ - CListValue* list = new CListValue(); - walk_children(GetSGNode(), list, 0); /* GetSGNode() is always valid or it would have raised an exception before this */ - return list; -} - -CListValue* KX_GameObject::GetChildrenRecursive() -{ - CListValue* list = new CListValue(); - walk_children(GetSGNode(), list, 1); - return list; -} - -KX_Scene* KX_GameObject::GetScene() -{ - SG_Node* node = this->GetSGNode(); - if (node == NULL) { - // this happens for object in non active layers, rely on static scene then - return KX_GetActiveScene(); - } - return static_cast(node->GetSGClientInfo()); -} - -/* --------------------------------------------------------------------- - * Some stuff taken from the header - * --------------------------------------------------------------------- */ -void KX_GameObject::Relink(CTR_Map *map_parameter) -{ - // we will relink the sensors and actuators that use object references - // if the object is part of the replicated hierarchy, use the new - // object reference instead - SCA_SensorList& sensorlist = GetSensors(); - SCA_SensorList::iterator sit; - for (sit=sensorlist.begin(); sit != sensorlist.end(); sit++) - { - (*sit)->Relink(map_parameter); - } - SCA_ActuatorList& actuatorlist = GetActuators(); - SCA_ActuatorList::iterator ait; - for (ait=actuatorlist.begin(); ait != actuatorlist.end(); ait++) - { - (*ait)->Relink(map_parameter); - } -} - -#ifdef USE_MATHUTILS - -/* These require an SGNode */ -#define MATHUTILS_VEC_CB_POS_LOCAL 1 -#define MATHUTILS_VEC_CB_POS_GLOBAL 2 -#define MATHUTILS_VEC_CB_SCALE_LOCAL 3 -#define MATHUTILS_VEC_CB_SCALE_GLOBAL 4 -#define MATHUTILS_VEC_CB_INERTIA_LOCAL 5 -#define MATHUTILS_VEC_CB_OBJECT_COLOR 6 -#define MATHUTILS_VEC_CB_LINVEL_LOCAL 7 -#define MATHUTILS_VEC_CB_LINVEL_GLOBAL 8 -#define MATHUTILS_VEC_CB_ANGVEL_LOCAL 9 -#define MATHUTILS_VEC_CB_ANGVEL_GLOBAL 10 - -static unsigned char mathutils_kxgameob_vector_cb_index= -1; /* index for our callbacks */ - -static int mathutils_kxgameob_generic_check(BaseMathObject *bmo) -{ - KX_GameObject* self = static_castBGE_PROXY_REF(bmo->cb_user); - if (self == NULL) - return -1; - - return 0; -} - -static int mathutils_kxgameob_vector_get(BaseMathObject *bmo, int subtype) -{ - KX_GameObject* self = static_castBGE_PROXY_REF(bmo->cb_user); - if (self == NULL) - return -1; - -#define PHYS_ERR(attr) PyErr_SetString(PyExc_AttributeError, "KX_GameObject." attr ", is missing a physics controller") - - switch (subtype) { - case MATHUTILS_VEC_CB_POS_LOCAL: - self->NodeGetLocalPosition().getValue(bmo->data); - break; - case MATHUTILS_VEC_CB_POS_GLOBAL: - self->NodeGetWorldPosition().getValue(bmo->data); - break; - case MATHUTILS_VEC_CB_SCALE_LOCAL: - self->NodeGetLocalScaling().getValue(bmo->data); - break; - case MATHUTILS_VEC_CB_SCALE_GLOBAL: - self->NodeGetWorldScaling().getValue(bmo->data); - break; - case MATHUTILS_VEC_CB_INERTIA_LOCAL: - if (!self->GetPhysicsController()) return PHYS_ERR("localInertia"), -1; - self->GetPhysicsController()->GetLocalInertia().getValue(bmo->data); - break; - case MATHUTILS_VEC_CB_OBJECT_COLOR: - self->GetObjectColor().getValue(bmo->data); - break; - case MATHUTILS_VEC_CB_LINVEL_LOCAL: - if (!self->GetPhysicsController()) return PHYS_ERR("localLinearVelocity"), -1; - self->GetLinearVelocity(true).getValue(bmo->data); - break; - case MATHUTILS_VEC_CB_LINVEL_GLOBAL: - if (!self->GetPhysicsController()) return PHYS_ERR("worldLinearVelocity"), -1; - self->GetLinearVelocity(false).getValue(bmo->data); - break; - case MATHUTILS_VEC_CB_ANGVEL_LOCAL: - if (!self->GetPhysicsController()) return PHYS_ERR("localLinearVelocity"), -1; - self->GetAngularVelocity(true).getValue(bmo->data); - break; - case MATHUTILS_VEC_CB_ANGVEL_GLOBAL: - if (!self->GetPhysicsController()) return PHYS_ERR("worldLinearVelocity"), -1; - self->GetAngularVelocity(false).getValue(bmo->data); - break; - - } - -#undef PHYS_ERR - - return 0; -} - -static int mathutils_kxgameob_vector_set(BaseMathObject *bmo, int subtype) -{ - KX_GameObject* self = static_castBGE_PROXY_REF(bmo->cb_user); - if (self == NULL) - return -1; - - switch (subtype) { - case MATHUTILS_VEC_CB_POS_LOCAL: - self->NodeSetLocalPosition(MT_Point3(bmo->data)); - self->NodeUpdateGS(0.f); - break; - case MATHUTILS_VEC_CB_POS_GLOBAL: - self->NodeSetWorldPosition(MT_Point3(bmo->data)); - self->NodeUpdateGS(0.f); - break; - case MATHUTILS_VEC_CB_SCALE_LOCAL: - self->NodeSetLocalScale(MT_Point3(bmo->data)); - self->NodeUpdateGS(0.f); - break; - case MATHUTILS_VEC_CB_SCALE_GLOBAL: - PyErr_SetString(PyExc_AttributeError, "KX_GameObject.worldScale is read-only"); - return -1; - case MATHUTILS_VEC_CB_INERTIA_LOCAL: - /* read only */ - break; - case MATHUTILS_VEC_CB_OBJECT_COLOR: - self->SetObjectColor(MT_Vector4(bmo->data)); - break; - case MATHUTILS_VEC_CB_LINVEL_LOCAL: - self->setLinearVelocity(MT_Point3(bmo->data),true); - break; - case MATHUTILS_VEC_CB_LINVEL_GLOBAL: - self->setLinearVelocity(MT_Point3(bmo->data),false); - break; - case MATHUTILS_VEC_CB_ANGVEL_LOCAL: - self->setAngularVelocity(MT_Point3(bmo->data),true); - break; - case MATHUTILS_VEC_CB_ANGVEL_GLOBAL: - self->setAngularVelocity(MT_Point3(bmo->data),false); - break; - } - - return 0; -} - -static int mathutils_kxgameob_vector_get_index(BaseMathObject *bmo, int subtype, int index) -{ - /* lazy, avoid repeteing the case statement */ - if (mathutils_kxgameob_vector_get(bmo, subtype) == -1) - return -1; - return 0; -} - -static int mathutils_kxgameob_vector_set_index(BaseMathObject *bmo, int subtype, int index) -{ - float f= bmo->data[index]; - - /* lazy, avoid repeteing the case statement */ - if (mathutils_kxgameob_vector_get(bmo, subtype) == -1) - return -1; - - bmo->data[index] = f; - return mathutils_kxgameob_vector_set(bmo, subtype); -} - -static Mathutils_Callback mathutils_kxgameob_vector_cb = { - mathutils_kxgameob_generic_check, - mathutils_kxgameob_vector_get, - mathutils_kxgameob_vector_set, - mathutils_kxgameob_vector_get_index, - mathutils_kxgameob_vector_set_index -}; - -/* Matrix */ -#define MATHUTILS_MAT_CB_ORI_LOCAL 1 -#define MATHUTILS_MAT_CB_ORI_GLOBAL 2 - -static unsigned char mathutils_kxgameob_matrix_cb_index= -1; /* index for our callbacks */ - -static int mathutils_kxgameob_matrix_get(BaseMathObject *bmo, int subtype) -{ - KX_GameObject* self = static_castBGE_PROXY_REF(bmo->cb_user); - if (self == NULL) - return -1; - - switch (subtype) { - case MATHUTILS_MAT_CB_ORI_LOCAL: - self->NodeGetLocalOrientation().getValue3x3(bmo->data); - break; - case MATHUTILS_MAT_CB_ORI_GLOBAL: - self->NodeGetWorldOrientation().getValue3x3(bmo->data); - break; - } - - return 0; -} - - -static int mathutils_kxgameob_matrix_set(BaseMathObject *bmo, int subtype) -{ - KX_GameObject* self = static_castBGE_PROXY_REF(bmo->cb_user); - if (self == NULL) - return -1; - - MT_Matrix3x3 mat3x3; - switch (subtype) { - case MATHUTILS_MAT_CB_ORI_LOCAL: - mat3x3.setValue3x3(bmo->data); - self->NodeSetLocalOrientation(mat3x3); - self->NodeUpdateGS(0.f); - break; - case MATHUTILS_MAT_CB_ORI_GLOBAL: - mat3x3.setValue3x3(bmo->data); - self->NodeSetLocalOrientation(mat3x3); - self->NodeUpdateGS(0.f); - break; - } - - return 0; -} - -static Mathutils_Callback mathutils_kxgameob_matrix_cb = { - mathutils_kxgameob_generic_check, - mathutils_kxgameob_matrix_get, - mathutils_kxgameob_matrix_set, - NULL, - NULL -}; - - -void KX_GameObject_Mathutils_Callback_Init(void) -{ - // register mathutils callbacks, ok to run more than once. - mathutils_kxgameob_vector_cb_index= Mathutils_RegisterCallback(&mathutils_kxgameob_vector_cb); - mathutils_kxgameob_matrix_cb_index= Mathutils_RegisterCallback(&mathutils_kxgameob_matrix_cb); -} - -#endif // USE_MATHUTILS - -#ifdef WITH_PYTHON -/* ------- python stuff ---------------------------------------------------*/ -PyMethodDef KX_GameObject::Methods[] = { - {"applyForce", (PyCFunction) KX_GameObject::sPyApplyForce, METH_VARARGS}, - {"applyTorque", (PyCFunction) KX_GameObject::sPyApplyTorque, METH_VARARGS}, - {"applyRotation", (PyCFunction) KX_GameObject::sPyApplyRotation, METH_VARARGS}, - {"applyMovement", (PyCFunction) KX_GameObject::sPyApplyMovement, METH_VARARGS}, - {"getLinearVelocity", (PyCFunction) KX_GameObject::sPyGetLinearVelocity, METH_VARARGS}, - {"setLinearVelocity", (PyCFunction) KX_GameObject::sPySetLinearVelocity, METH_VARARGS}, - {"getAngularVelocity", (PyCFunction) KX_GameObject::sPyGetAngularVelocity, METH_VARARGS}, - {"setAngularVelocity", (PyCFunction) KX_GameObject::sPySetAngularVelocity, METH_VARARGS}, - {"getVelocity", (PyCFunction) KX_GameObject::sPyGetVelocity, METH_VARARGS}, - {"setDamping", (PyCFunction) KX_GameObject::sPySetDamping, METH_VARARGS}, - {"getReactionForce", (PyCFunction) KX_GameObject::sPyGetReactionForce, METH_NOARGS}, - {"alignAxisToVect",(PyCFunction) KX_GameObject::sPyAlignAxisToVect, METH_VARARGS}, - {"getAxisVect",(PyCFunction) KX_GameObject::sPyGetAxisVect, METH_O}, - {"suspendDynamics", (PyCFunction)KX_GameObject::sPySuspendDynamics, METH_VARARGS}, - {"restoreDynamics", (PyCFunction)KX_GameObject::sPyRestoreDynamics,METH_NOARGS}, - {"enableRigidBody", (PyCFunction)KX_GameObject::sPyEnableRigidBody,METH_NOARGS}, - {"disableRigidBody", (PyCFunction)KX_GameObject::sPyDisableRigidBody,METH_NOARGS}, - {"applyImpulse", (PyCFunction) KX_GameObject::sPyApplyImpulse, METH_VARARGS}, - {"setCollisionMargin", (PyCFunction) KX_GameObject::sPySetCollisionMargin, METH_O}, - {"setParent", (PyCFunction)KX_GameObject::sPySetParent,METH_VARARGS}, - {"setVisible",(PyCFunction) KX_GameObject::sPySetVisible, METH_VARARGS}, - {"setOcclusion",(PyCFunction) KX_GameObject::sPySetOcclusion, METH_VARARGS}, - {"removeParent", (PyCFunction)KX_GameObject::sPyRemoveParent,METH_NOARGS}, - - - {"getPhysicsId", (PyCFunction)KX_GameObject::sPyGetPhysicsId,METH_NOARGS}, - {"getPropertyNames", (PyCFunction)KX_GameObject::sPyGetPropertyNames,METH_NOARGS}, - {"replaceMesh",(PyCFunction) KX_GameObject::sPyReplaceMesh, METH_VARARGS}, - {"endObject",(PyCFunction) KX_GameObject::sPyEndObject, METH_NOARGS}, - {"reinstancePhysicsMesh", (PyCFunction)KX_GameObject::sPyReinstancePhysicsMesh,METH_VARARGS}, - - KX_PYMETHODTABLE(KX_GameObject, rayCastTo), - KX_PYMETHODTABLE(KX_GameObject, rayCast), - KX_PYMETHODTABLE_O(KX_GameObject, getDistanceTo), - KX_PYMETHODTABLE_O(KX_GameObject, getVectTo), - KX_PYMETHODTABLE(KX_GameObject, sendMessage), - KX_PYMETHODTABLE(KX_GameObject, addDebugProperty), - - KX_PYMETHODTABLE_KEYWORDS(KX_GameObject, playAction), - KX_PYMETHODTABLE(KX_GameObject, stopAction), - KX_PYMETHODTABLE(KX_GameObject, getActionFrame), - KX_PYMETHODTABLE(KX_GameObject, getActionName), - KX_PYMETHODTABLE(KX_GameObject, setActionFrame), - KX_PYMETHODTABLE(KX_GameObject, isPlayingAction), - - // dict style access for props - {"get",(PyCFunction) KX_GameObject::sPyget, METH_VARARGS}, - - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_GameObject::Attributes[] = { - KX_PYATTRIBUTE_INT_RO("currentLodLevel", KX_GameObject, m_currentLodLevel), - KX_PYATTRIBUTE_RO_FUNCTION("name", KX_GameObject, pyattr_get_name), - KX_PYATTRIBUTE_RO_FUNCTION("parent", KX_GameObject, pyattr_get_parent), - KX_PYATTRIBUTE_RO_FUNCTION("groupMembers", KX_GameObject, pyattr_get_group_members), - KX_PYATTRIBUTE_RO_FUNCTION("groupObject", KX_GameObject, pyattr_get_group_object), - KX_PYATTRIBUTE_RO_FUNCTION("scene", KX_GameObject, pyattr_get_scene), - KX_PYATTRIBUTE_RO_FUNCTION("life", KX_GameObject, pyattr_get_life), - KX_PYATTRIBUTE_RW_FUNCTION("mass", KX_GameObject, pyattr_get_mass, pyattr_set_mass), - KX_PYATTRIBUTE_RO_FUNCTION("isSuspendDynamics", KX_GameObject, pyattr_get_is_suspend_dynamics), - KX_PYATTRIBUTE_RW_FUNCTION("linVelocityMin", KX_GameObject, pyattr_get_lin_vel_min, pyattr_set_lin_vel_min), - KX_PYATTRIBUTE_RW_FUNCTION("linVelocityMax", KX_GameObject, pyattr_get_lin_vel_max, pyattr_set_lin_vel_max), - KX_PYATTRIBUTE_RW_FUNCTION("angularVelocityMin", KX_GameObject, pyattr_get_ang_vel_min, pyattr_set_ang_vel_min), - KX_PYATTRIBUTE_RW_FUNCTION("angularVelocityMax", KX_GameObject, pyattr_get_ang_vel_max, pyattr_set_ang_vel_max), - KX_PYATTRIBUTE_RW_FUNCTION("visible", KX_GameObject, pyattr_get_visible, pyattr_set_visible), - KX_PYATTRIBUTE_RW_FUNCTION("record_animation", KX_GameObject, pyattr_get_record_animation, pyattr_set_record_animation), - KX_PYATTRIBUTE_BOOL_RW ("occlusion", KX_GameObject, m_bOccluder), - KX_PYATTRIBUTE_RW_FUNCTION("position", KX_GameObject, pyattr_get_worldPosition, pyattr_set_localPosition), - KX_PYATTRIBUTE_RO_FUNCTION("localInertia", KX_GameObject, pyattr_get_localInertia), - KX_PYATTRIBUTE_RW_FUNCTION("orientation",KX_GameObject,pyattr_get_worldOrientation,pyattr_set_localOrientation), - KX_PYATTRIBUTE_RW_FUNCTION("scaling", KX_GameObject, pyattr_get_worldScaling, pyattr_set_localScaling), - KX_PYATTRIBUTE_RW_FUNCTION("timeOffset",KX_GameObject, pyattr_get_timeOffset,pyattr_set_timeOffset), - KX_PYATTRIBUTE_RW_FUNCTION("collisionCallbacks", KX_GameObject, pyattr_get_collisionCallbacks, pyattr_set_collisionCallbacks), - KX_PYATTRIBUTE_RW_FUNCTION("collisionGroup", KX_GameObject, pyattr_get_collisionGroup, pyattr_set_collisionGroup), - KX_PYATTRIBUTE_RW_FUNCTION("collisionMask", KX_GameObject, pyattr_get_collisionMask, pyattr_set_collisionMask), - KX_PYATTRIBUTE_RW_FUNCTION("state", KX_GameObject, pyattr_get_state, pyattr_set_state), - KX_PYATTRIBUTE_RO_FUNCTION("meshes", KX_GameObject, pyattr_get_meshes), - KX_PYATTRIBUTE_RW_FUNCTION("localOrientation",KX_GameObject,pyattr_get_localOrientation,pyattr_set_localOrientation), - KX_PYATTRIBUTE_RW_FUNCTION("worldOrientation",KX_GameObject,pyattr_get_worldOrientation,pyattr_set_worldOrientation), - KX_PYATTRIBUTE_RW_FUNCTION("localPosition", KX_GameObject, pyattr_get_localPosition, pyattr_set_localPosition), - KX_PYATTRIBUTE_RW_FUNCTION("worldPosition", KX_GameObject, pyattr_get_worldPosition, pyattr_set_worldPosition), - KX_PYATTRIBUTE_RW_FUNCTION("localScale", KX_GameObject, pyattr_get_localScaling, pyattr_set_localScaling), - KX_PYATTRIBUTE_RW_FUNCTION("worldScale", KX_GameObject, pyattr_get_worldScaling, pyattr_set_worldScaling), - KX_PYATTRIBUTE_RW_FUNCTION("localTransform", KX_GameObject, pyattr_get_localTransform, pyattr_set_localTransform), - KX_PYATTRIBUTE_RW_FUNCTION("worldTransform", KX_GameObject, pyattr_get_worldTransform, pyattr_set_worldTransform), - KX_PYATTRIBUTE_RW_FUNCTION("linearVelocity", KX_GameObject, pyattr_get_localLinearVelocity, pyattr_set_worldLinearVelocity), - KX_PYATTRIBUTE_RW_FUNCTION("localLinearVelocity", KX_GameObject, pyattr_get_localLinearVelocity, pyattr_set_localLinearVelocity), - KX_PYATTRIBUTE_RW_FUNCTION("worldLinearVelocity", KX_GameObject, pyattr_get_worldLinearVelocity, pyattr_set_worldLinearVelocity), - KX_PYATTRIBUTE_RW_FUNCTION("angularVelocity", KX_GameObject, pyattr_get_localAngularVelocity, pyattr_set_worldAngularVelocity), - KX_PYATTRIBUTE_RW_FUNCTION("localAngularVelocity", KX_GameObject, pyattr_get_localAngularVelocity, pyattr_set_localAngularVelocity), - KX_PYATTRIBUTE_RW_FUNCTION("worldAngularVelocity", KX_GameObject, pyattr_get_worldAngularVelocity, pyattr_set_worldAngularVelocity), - KX_PYATTRIBUTE_RW_FUNCTION("linearDamping", KX_GameObject, pyattr_get_linearDamping, pyattr_set_linearDamping), - KX_PYATTRIBUTE_RW_FUNCTION("angularDamping", KX_GameObject, pyattr_get_angularDamping, pyattr_set_angularDamping), - KX_PYATTRIBUTE_RO_FUNCTION("children", KX_GameObject, pyattr_get_children), - KX_PYATTRIBUTE_RO_FUNCTION("childrenRecursive", KX_GameObject, pyattr_get_children_recursive), - KX_PYATTRIBUTE_RO_FUNCTION("attrDict", KX_GameObject, pyattr_get_attrDict), - KX_PYATTRIBUTE_RW_FUNCTION("color", KX_GameObject, pyattr_get_obcolor, pyattr_set_obcolor), - KX_PYATTRIBUTE_RW_FUNCTION("debug", KX_GameObject, pyattr_get_debug, pyattr_set_debug), - KX_PYATTRIBUTE_RW_FUNCTION("debugRecursive", KX_GameObject, pyattr_get_debugRecursive, pyattr_set_debugRecursive), - - /* experimental, don't rely on these yet */ - KX_PYATTRIBUTE_RO_FUNCTION("sensors", KX_GameObject, pyattr_get_sensors), - KX_PYATTRIBUTE_RO_FUNCTION("controllers", KX_GameObject, pyattr_get_controllers), - KX_PYATTRIBUTE_RO_FUNCTION("actuators", KX_GameObject, pyattr_get_actuators), - {NULL} //Sentinel -}; - -PyObject *KX_GameObject::PyReplaceMesh(PyObject *args) -{ - KX_Scene *scene = KX_GetActiveScene(); - SCA_LogicManager *logicmgr = GetScene()->GetLogicManager(); - - PyObject *value; - int use_gfx= 1, use_phys= 0; - RAS_MeshObject *new_mesh; - - if (!PyArg_ParseTuple(args,"O|ii:replaceMesh", &value, &use_gfx, &use_phys)) - return NULL; - - if (!ConvertPythonToMesh(logicmgr, value, &new_mesh, false, "gameOb.replaceMesh(value): KX_GameObject")) - return NULL; - - scene->ReplaceMesh(this, new_mesh, (bool)use_gfx, (bool)use_phys); - Py_RETURN_NONE; -} - -PyObject *KX_GameObject::PyEndObject() -{ - KX_Scene* scene = GetScene(); - - scene->DelayedRemoveObject(this); - - Py_RETURN_NONE; - -} - -PyObject *KX_GameObject::PyReinstancePhysicsMesh(PyObject *args) -{ - KX_GameObject *gameobj= NULL; - RAS_MeshObject *mesh= NULL; - SCA_LogicManager *logicmgr = GetScene()->GetLogicManager(); - - PyObject *gameobj_py= NULL; - PyObject *mesh_py= NULL; - - if ( !PyArg_ParseTuple(args,"|OO:reinstancePhysicsMesh",&gameobj_py, &mesh_py) || - (gameobj_py && !ConvertPythonToGameObject(logicmgr, gameobj_py, &gameobj, true, "gameOb.reinstancePhysicsMesh(obj, mesh): KX_GameObject")) || - (mesh_py && !ConvertPythonToMesh(logicmgr, mesh_py, &mesh, true, "gameOb.reinstancePhysicsMesh(obj, mesh): KX_GameObject")) - ) { - return NULL; - } - - /* gameobj and mesh can be NULL */ - if (GetPhysicsController() && GetPhysicsController()->ReinstancePhysicsShape(gameobj, mesh)) - Py_RETURN_TRUE; - - Py_RETURN_FALSE; -} - -static PyObject *Map_GetItem(PyObject *self_v, PyObject *item) -{ - KX_GameObject* self = static_castBGE_PROXY_REF(self_v); - const char *attr_str= _PyUnicode_AsString(item); - CValue* resultattr; - PyObject *pyconvert; - - if (self == NULL) { - PyErr_SetString(PyExc_SystemError, "val = gameOb[key]: KX_GameObject, " BGE_PROXY_ERROR_MSG); - return NULL; - } - - /* first see if the attributes a string and try get the cvalue attribute */ - if (attr_str && (resultattr=self->GetProperty(attr_str))) { - pyconvert = resultattr->ConvertValueToPython(); - return pyconvert ? pyconvert:resultattr->GetProxy(); - } - /* no CValue attribute, try get the python only m_attr_dict attribute */ - else if (self->m_attr_dict && (pyconvert=PyDict_GetItem(self->m_attr_dict, item))) { - - if (attr_str) - PyErr_Clear(); - Py_INCREF(pyconvert); - return pyconvert; - } - else { - if (attr_str) PyErr_Format(PyExc_KeyError, "value = gameOb[key]: KX_GameObject, key \"%s\" does not exist", attr_str); - else PyErr_SetString(PyExc_KeyError, "value = gameOb[key]: KX_GameObject, key does not exist"); - return NULL; - } - -} - - -static int Map_SetItem(PyObject *self_v, PyObject *key, PyObject *val) -{ - KX_GameObject* self = static_castBGE_PROXY_REF(self_v); - const char *attr_str= _PyUnicode_AsString(key); - if (attr_str==NULL) - PyErr_Clear(); - - if (self == NULL) { - PyErr_SetString(PyExc_SystemError, "gameOb[key] = value: KX_GameObject, " BGE_PROXY_ERROR_MSG); - return -1; - } - - if (val==NULL) { /* del ob["key"] */ - int del= 0; - - /* try remove both just in case */ - if (attr_str) - del |= (self->RemoveProperty(attr_str)==true) ? 1:0; - - if (self->m_attr_dict) - del |= (PyDict_DelItem(self->m_attr_dict, key)==0) ? 1:0; - - if (del==0) { - if (attr_str) PyErr_Format(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key \"%s\" could not be set", attr_str); - else PyErr_SetString(PyExc_KeyError, "del gameOb[key]: KX_GameObject, key could not be deleted"); - return -1; - } - else if (self->m_attr_dict) { - PyErr_Clear(); /* PyDict_DelItem sets an error when it fails */ - } - } - else { /* ob["key"] = value */ - bool set = false; - - /* as CValue */ - if (attr_str && PyObject_TypeCheck(val, &PyObjectPlus::Type)==0) /* don't allow GameObjects for eg to be assigned to CValue props */ - { - CValue *vallie = self->ConvertPythonToValue(val, false, "gameOb[key] = value: "); - - if (vallie) { - CValue* oldprop = self->GetProperty(attr_str); - - if (oldprop) - oldprop->SetValue(vallie); - else - self->SetProperty(attr_str, vallie); - - vallie->Release(); - set = true; - - /* try remove dict value to avoid double ups */ - if (self->m_attr_dict) { - if (PyDict_DelItem(self->m_attr_dict, key) != 0) - PyErr_Clear(); - } - } - else if (PyErr_Occurred()) { - return -1; - } - } - - if (set == false) { - if (self->m_attr_dict==NULL) /* lazy init */ - self->m_attr_dict= PyDict_New(); - - - if (PyDict_SetItem(self->m_attr_dict, key, val)==0) - { - if (attr_str) - self->RemoveProperty(attr_str); /* overwrite the CValue if it exists */ - set = true; - } - else { - if (attr_str) PyErr_Format(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key \"%s\" not be added to internal dictionary", attr_str); - else PyErr_SetString(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key not be added to internal dictionary"); - } - } - - if (set == false) { - return -1; /* pythons error value */ - } - - } - - return 0; /* success */ -} - -static int Seq_Contains(PyObject *self_v, PyObject *value) -{ - KX_GameObject* self = static_castBGE_PROXY_REF(self_v); - - if (self == NULL) { - PyErr_SetString(PyExc_SystemError, "val in gameOb: KX_GameObject, " BGE_PROXY_ERROR_MSG); - return -1; - } - - if (PyUnicode_Check(value) && self->GetProperty(_PyUnicode_AsString(value))) - return 1; - - if (self->m_attr_dict && PyDict_GetItem(self->m_attr_dict, value)) - return 1; - - return 0; -} - - -PyMappingMethods KX_GameObject::Mapping = { - (lenfunc)NULL , /*inquiry mp_length */ - (binaryfunc)Map_GetItem, /*binaryfunc mp_subscript */ - (objobjargproc)Map_SetItem, /*objobjargproc mp_ass_subscript */ -}; - -PySequenceMethods KX_GameObject::Sequence = { - NULL, /* Cant set the len otherwise it can evaluate as false */ - NULL, /* sq_concat */ - NULL, /* sq_repeat */ - NULL, /* sq_item */ - NULL, /* sq_slice */ - NULL, /* sq_ass_item */ - NULL, /* sq_ass_slice */ - (objobjproc)Seq_Contains, /* sq_contains */ - (binaryfunc) NULL, /* sq_inplace_concat */ - (ssizeargfunc) NULL, /* sq_inplace_repeat */ -}; - -PyTypeObject KX_GameObject::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_GameObject", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0, - &Sequence, - &Mapping, - 0,0,0, - NULL, - NULL, - 0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &SCA_IObject::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyObject *KX_GameObject::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_GameObject* self = static_cast(self_v); - return PyUnicode_From_STR_String(self->GetName()); -} - -PyObject *KX_GameObject::pyattr_get_parent(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_GameObject* self = static_cast(self_v); - KX_GameObject* parent = self->GetParent(); - if (parent) { - return parent->GetProxy(); - } - Py_RETURN_NONE; -} - -PyObject *KX_GameObject::pyattr_get_group_members(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_GameObject* self = static_cast(self_v); - CListValue* instances = self->GetInstanceObjects(); - if (instances) { - return instances->GetProxy(); - } - Py_RETURN_NONE; -} - -PyObject* KX_GameObject::pyattr_get_collisionCallbacks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_GameObject* self = static_cast(self_v); - - // Only objects with a physics controller should have collision callbacks - if (!self->GetPhysicsController()) { - PyErr_SetString(PyExc_AttributeError, "KX_GameObject.collisionCallbacks: attribute only available for objects with collisions enabled"); - return NULL; - } - - // Return the existing callbacks - if (self->m_collisionCallbacks == NULL) - { - self->m_collisionCallbacks = PyList_New(0); - // Subscribe to collision update from KX_TouchManager - self->RegisterCollisionCallbacks(); - } - Py_INCREF(self->m_collisionCallbacks); - return self->m_collisionCallbacks; -} - -int KX_GameObject::pyattr_set_collisionCallbacks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject* self = static_cast(self_v); - - // Only objects with a physics controller should have collision callbacks - if (!self->GetPhysicsController()) { - PyErr_SetString(PyExc_AttributeError, "KX_GameObject.collisionCallbacks: attribute only available for objects with collisions enabled"); - return PY_SET_ATTR_FAIL; - } - - if (!PyList_CheckExact(value)) - { - PyErr_SetString(PyExc_ValueError, "Expected a list"); - return PY_SET_ATTR_FAIL; - } - - if (self->m_collisionCallbacks == NULL) { - self->RegisterCollisionCallbacks(); - } else { - Py_DECREF(self->m_collisionCallbacks); - } - - Py_INCREF(value); - - - self->m_collisionCallbacks = value; - - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_GameObject::pyattr_get_collisionGroup(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_GameObject* self = static_cast(self_v); - return PyLong_FromLong(self->GetUserCollisionGroup()); -} - -int KX_GameObject::pyattr_set_collisionGroup(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject* self = static_cast(self_v); - int val = PyLong_AsLong(value); - - if (val == -1 && PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, "gameOb.collisionGroup = int: KX_GameObject, expected an int bit field"); - return PY_SET_ATTR_FAIL; - } - - if (val == 0 || val & ~((1 << OB_MAX_COL_MASKS) - 1)) { - PyErr_Format(PyExc_AttributeError, "gameOb.collisionGroup = int: KX_GameObject, expected a int bit field, 0 < group < %i", (1 << OB_MAX_COL_MASKS)); - return PY_SET_ATTR_FAIL; - } - - self->SetUserCollisionGroup(val); - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_GameObject::pyattr_get_collisionMask(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_GameObject* self = static_cast(self_v); - return PyLong_FromLong(self->GetUserCollisionMask()); -} - -int KX_GameObject::pyattr_set_collisionMask(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject* self = static_cast(self_v); - int val = PyLong_AsLong(value); - - if (val == -1 && PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, "gameOb.collisionMask = int: KX_GameObject, expected an int bit field"); - return PY_SET_ATTR_FAIL; - } - - if (val == 0 || val & ~((1 << OB_MAX_COL_MASKS) - 1)) { - PyErr_Format(PyExc_AttributeError, "gameOb.collisionMask = int: KX_GameObject, expected a int bit field, 0 < mask < %i", (1 << OB_MAX_COL_MASKS)); - return PY_SET_ATTR_FAIL; - } - - self->SetUserCollisionMask(val); - return PY_SET_ATTR_SUCCESS; -} - -PyObject* KX_GameObject::pyattr_get_scene(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_GameObject *self = static_cast(self_v); - KX_Scene *scene = self->GetScene(); - if (scene) { - return scene->GetProxy(); - } - Py_RETURN_NONE; -} - -PyObject *KX_GameObject::pyattr_get_group_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_GameObject* self = static_cast(self_v); - KX_GameObject* pivot = self->GetDupliGroupObject(); - if (pivot) { - return pivot->GetProxy(); - } - Py_RETURN_NONE; -} - -PyObject *KX_GameObject::pyattr_get_life(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_GameObject* self = static_cast(self_v); - - CValue *life = self->GetProperty("::timebomb"); - if (life) - // this convert the timebomb seconds to frames, hard coded 50.0f (assuming 50fps) - // value hardcoded in KX_Scene::AddReplicaObject() - return PyFloat_FromDouble(life->GetNumber() * 50.0); - else - Py_RETURN_NONE; -} - -PyObject *KX_GameObject::pyattr_get_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_GameObject* self = static_cast(self_v); - PHY_IPhysicsController *spc = self->GetPhysicsController(); - return PyFloat_FromDouble(spc ? spc->GetMass() : 0.0f); -} - -int KX_GameObject::pyattr_set_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject* self = static_cast(self_v); - PHY_IPhysicsController *spc = self->GetPhysicsController(); - MT_Scalar val = PyFloat_AsDouble(value); - if (val < 0.0f) { /* also accounts for non float */ - PyErr_SetString(PyExc_AttributeError, "gameOb.mass = float: KX_GameObject, expected a float zero or above"); - return PY_SET_ATTR_FAIL; - } - - if (spc) - spc->SetMass(val); - - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_GameObject::pyattr_get_is_suspend_dynamics(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_GameObject* self = static_cast(self_v); - - // Only objects with a physics controller can be suspended - if (!self->GetPhysicsController()) { - PyErr_SetString(PyExc_AttributeError, "This object has not Physics Controller"); - return NULL; - } - - return PyBool_FromLong(self->IsDynamicsSuspended()); -} - -PyObject *KX_GameObject::pyattr_get_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_GameObject* self = static_cast(self_v); - PHY_IPhysicsController *spc = self->GetPhysicsController(); - return PyFloat_FromDouble(spc ? spc->GetLinVelocityMin() : 0.0f); -} - -int KX_GameObject::pyattr_set_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject* self = static_cast(self_v); - PHY_IPhysicsController *spc = self->GetPhysicsController(); - MT_Scalar val = PyFloat_AsDouble(value); - if (val < 0.0f) { /* also accounts for non float */ - PyErr_SetString(PyExc_AttributeError, "gameOb.linVelocityMin = float: KX_GameObject, expected a float zero or above"); - return PY_SET_ATTR_FAIL; - } - - if (spc) - spc->SetLinVelocityMin(val); - - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_GameObject::pyattr_get_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_GameObject* self = static_cast(self_v); - PHY_IPhysicsController *spc = self->GetPhysicsController(); - return PyFloat_FromDouble(spc ? spc->GetLinVelocityMax() : 0.0f); -} - -int KX_GameObject::pyattr_set_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject* self = static_cast(self_v); - PHY_IPhysicsController *spc = self->GetPhysicsController(); - MT_Scalar val = PyFloat_AsDouble(value); - if (val < 0.0f) { /* also accounts for non float */ - PyErr_SetString(PyExc_AttributeError, "gameOb.linVelocityMax = float: KX_GameObject, expected a float zero or above"); - return PY_SET_ATTR_FAIL; - } - - if (spc) - spc->SetLinVelocityMax(val); - - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_GameObject::pyattr_get_ang_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_GameObject *self = static_cast(self_v); - PHY_IPhysicsController *spc = self->GetPhysicsController(); - return PyFloat_FromDouble(spc ? spc->GetAngularVelocityMin() : 0.0f); -} - -int KX_GameObject::pyattr_set_ang_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject *self = static_cast(self_v); - PHY_IPhysicsController *spc = self->GetPhysicsController(); - MT_Scalar val = PyFloat_AsDouble(value); - if (val < 0.0f) { /* also accounts for non float */ - PyErr_SetString(PyExc_AttributeError, - "gameOb.angularVelocityMin = float: KX_GameObject, expected a nonnegative float"); - return PY_SET_ATTR_FAIL; - } - - if (spc) - spc->SetAngularVelocityMin(val); - - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_GameObject::pyattr_get_ang_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_GameObject *self = static_cast(self_v); - PHY_IPhysicsController *spc = self->GetPhysicsController(); - return PyFloat_FromDouble(spc ? spc->GetAngularVelocityMax() : 0.0f); -} - -int KX_GameObject::pyattr_set_ang_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject *self = static_cast(self_v); - PHY_IPhysicsController *spc = self->GetPhysicsController(); - MT_Scalar val = PyFloat_AsDouble(value); - if (val < 0.0f) { /* also accounts for non float */ - PyErr_SetString(PyExc_AttributeError, - "gameOb.angularVelocityMax = float: KX_GameObject, expected a nonnegative float"); - return PY_SET_ATTR_FAIL; - } - - if (spc) - spc->SetAngularVelocityMax(val); - - return PY_SET_ATTR_SUCCESS; -} - - -PyObject *KX_GameObject::pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_GameObject* self = static_cast(self_v); - return PyBool_FromLong(self->GetVisible()); -} - -int KX_GameObject::pyattr_set_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject* self = static_cast(self_v); - int param = PyObject_IsTrue( value ); - if (param == -1) { - PyErr_SetString(PyExc_AttributeError, "gameOb.visible = bool: KX_GameObject, expected True or False"); - return PY_SET_ATTR_FAIL; - } - - self->SetVisible(param, false); - self->UpdateBuckets(false); - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_GameObject::pyattr_get_record_animation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_GameObject* self = static_cast(self_v); - return PyBool_FromLong(self->IsRecordAnimation()); -} - -int KX_GameObject::pyattr_set_record_animation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject* self = static_cast(self_v); - int param = PyObject_IsTrue(value); - if (param == -1) { - PyErr_SetString(PyExc_AttributeError, "gameOb.record_animation = bool: KX_GameObject, expected boolean"); - return PY_SET_ATTR_FAIL; - } - - self->SetRecordAnimation(param); - - return PY_SET_ATTR_SUCCESS; -} - - - -PyObject *KX_GameObject::pyattr_get_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ -#ifdef USE_MATHUTILS - return Vector_CreatePyObject_cb( - BGE_PROXY_FROM_REF_BORROW(self_v), 3, - mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_POS_GLOBAL); -#else - KX_GameObject* self = static_cast(self_v); - return PyObjectFrom(self->NodeGetWorldPosition()); -#endif -} - -int KX_GameObject::pyattr_set_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject* self = static_cast(self_v); - MT_Point3 pos; - if (!PyVecTo(value, pos)) - return PY_SET_ATTR_FAIL; - - self->NodeSetWorldPosition(pos); - self->NodeUpdateGS(0.f); - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_GameObject::pyattr_get_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ -#ifdef USE_MATHUTILS - return Vector_CreatePyObject_cb( - BGE_PROXY_FROM_REF_BORROW(self_v), 3, - mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_POS_LOCAL); -#else - KX_GameObject* self = static_cast(self_v); - return PyObjectFrom(self->NodeGetLocalPosition()); -#endif -} - -int KX_GameObject::pyattr_set_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject* self = static_cast(self_v); - MT_Point3 pos; - if (!PyVecTo(value, pos)) - return PY_SET_ATTR_FAIL; - - self->NodeSetLocalPosition(pos); - self->NodeUpdateGS(0.f); - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_GameObject::pyattr_get_localInertia(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ -#ifdef USE_MATHUTILS - return Vector_CreatePyObject_cb( - BGE_PROXY_FROM_REF_BORROW(self_v), 3, - mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_INERTIA_LOCAL); -#else - KX_GameObject* self = static_cast(self_v); - if (self->GetPhysicsController1()) - return PyObjectFrom(self->GetPhysicsController1()->GetLocalInertia()); - return Py_BuildValue("fff", 0.0f, 0.0f, 0.0f); -#endif -} - -PyObject *KX_GameObject::pyattr_get_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ -#ifdef USE_MATHUTILS - return Matrix_CreatePyObject_cb( - BGE_PROXY_FROM_REF_BORROW(self_v), 3, 3, - mathutils_kxgameob_matrix_cb_index, MATHUTILS_MAT_CB_ORI_GLOBAL); -#else - KX_GameObject* self = static_cast(self_v); - return PyObjectFrom(self->NodeGetWorldOrientation()); -#endif -} - -int KX_GameObject::pyattr_set_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject* self = static_cast(self_v); - - /* if value is not a sequence PyOrientationTo makes an error */ - MT_Matrix3x3 rot; - if (!PyOrientationTo(value, rot, "gameOb.worldOrientation = sequence: KX_GameObject, ")) - return PY_SET_ATTR_FAIL; - - self->NodeSetGlobalOrientation(rot); - - self->NodeUpdateGS(0.f); - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_GameObject::pyattr_get_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ -#ifdef USE_MATHUTILS - return Matrix_CreatePyObject_cb( - BGE_PROXY_FROM_REF_BORROW(self_v), 3, 3, - mathutils_kxgameob_matrix_cb_index, MATHUTILS_MAT_CB_ORI_LOCAL); -#else - KX_GameObject* self = static_cast(self_v); - return PyObjectFrom(self->NodeGetLocalOrientation()); -#endif -} - -int KX_GameObject::pyattr_set_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject* self = static_cast(self_v); - - /* if value is not a sequence PyOrientationTo makes an error */ - MT_Matrix3x3 rot; - if (!PyOrientationTo(value, rot, "gameOb.localOrientation = sequence: KX_GameObject, ")) - return PY_SET_ATTR_FAIL; - - self->NodeSetLocalOrientation(rot); - self->NodeUpdateGS(0.f); - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_GameObject::pyattr_get_worldScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ -#ifdef USE_MATHUTILS - return Vector_CreatePyObject_cb( - BGE_PROXY_FROM_REF_BORROW(self_v), 3, - mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_SCALE_GLOBAL); -#else - KX_GameObject* self = static_cast(self_v); - return PyObjectFrom(self->NodeGetWorldScaling()); -#endif -} - -int KX_GameObject::pyattr_set_worldScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject* self = static_cast(self_v); - MT_Vector3 scale; - if (!PyVecTo(value, scale)) - return PY_SET_ATTR_FAIL; - - self->NodeSetWorldScale(scale); - self->NodeUpdateGS(0.f); - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_GameObject::pyattr_get_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ -#ifdef USE_MATHUTILS - return Vector_CreatePyObject_cb( - BGE_PROXY_FROM_REF_BORROW(self_v), 3, - mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_SCALE_LOCAL); -#else - KX_GameObject* self = static_cast(self_v); - return PyObjectFrom(self->NodeGetLocalScaling()); -#endif -} - -int KX_GameObject::pyattr_set_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject* self = static_cast(self_v); - MT_Vector3 scale; - if (!PyVecTo(value, scale)) - return PY_SET_ATTR_FAIL; - - self->NodeSetLocalScale(scale); - self->NodeUpdateGS(0.f); - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_GameObject::pyattr_get_localTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_GameObject* self = static_cast(self_v); - - float mat[16]; - - MT_Transform trans; - - trans.setOrigin(self->GetSGNode()->GetLocalPosition()); - trans.setBasis(self->GetSGNode()->GetLocalOrientation()); - - MT_Vector3 scaling = self->GetSGNode()->GetLocalScale(); - trans.scale(scaling[0], scaling[1], scaling[2]); - - trans.getValue(mat); - - return PyObjectFrom(MT_Matrix4x4(mat)); -} - -int KX_GameObject::pyattr_set_localTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject* self = static_cast(self_v); - MT_Matrix4x4 temp; - if (!PyMatTo(value, temp)) - return PY_SET_ATTR_FAIL; - - float transform[4][4]; - float loc[3], size[3]; - float rot[3][3]; - MT_Matrix3x3 orientation; - - temp.getValue(*transform); - mat4_to_loc_rot_size(loc, rot, size, transform); - - self->NodeSetLocalPosition(MT_Point3(loc)); - - //MT_Matrix3x3's constructor expects a 4x4 matrix - orientation = MT_Matrix3x3(); - orientation.setValue3x3(*rot); - self->NodeSetLocalOrientation(orientation); - - self->NodeSetLocalScale(MT_Vector3(size)); - - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_GameObject::pyattr_get_worldTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_GameObject* self = static_cast(self_v); - - return PyObjectFrom(MT_Matrix4x4(self->GetOpenGLMatrix())); -} - -int KX_GameObject::pyattr_set_worldTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject* self = static_cast(self_v); - MT_Matrix4x4 temp; - if (!PyMatTo(value, temp)) - return PY_SET_ATTR_FAIL; - - float transform[4][4]; - float loc[3], size[3]; - float rot[3][3]; - MT_Matrix3x3 orientation; - - temp.getValue(*transform); - mat4_to_loc_rot_size(loc, rot, size, transform); - - self->NodeSetWorldPosition(MT_Point3(loc)); - - //MT_Matrix3x3's constructor expects a 4x4 matrix - orientation = MT_Matrix3x3(); - orientation.setValue3x3(*rot); - self->NodeSetGlobalOrientation(orientation); - - self->NodeSetWorldScale(MT_Vector3(size)); - - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_GameObject::pyattr_get_worldLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ -#ifdef USE_MATHUTILS - return Vector_CreatePyObject_cb( - BGE_PROXY_FROM_REF_BORROW(self_v), 3, - mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_LINVEL_GLOBAL); -#else - KX_GameObject* self = static_cast(self_v); - return PyObjectFrom(GetLinearVelocity(false)); -#endif -} - -int KX_GameObject::pyattr_set_worldLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject* self = static_cast(self_v); - MT_Vector3 velocity; - if (!PyVecTo(value, velocity)) - return PY_SET_ATTR_FAIL; - - self->setLinearVelocity(velocity, false); - - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_GameObject::pyattr_get_localLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ -#ifdef USE_MATHUTILS - return Vector_CreatePyObject_cb( - BGE_PROXY_FROM_REF_BORROW(self_v), 3, - mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_LINVEL_LOCAL); -#else - KX_GameObject* self = static_cast(self_v); - return PyObjectFrom(GetLinearVelocity(true)); -#endif -} - -int KX_GameObject::pyattr_set_localLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject* self = static_cast(self_v); - MT_Vector3 velocity; - if (!PyVecTo(value, velocity)) - return PY_SET_ATTR_FAIL; - - self->setLinearVelocity(velocity, true); - - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_GameObject::pyattr_get_worldAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ -#ifdef USE_MATHUTILS - return Vector_CreatePyObject_cb( - BGE_PROXY_FROM_REF_BORROW(self_v), 3, - mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_ANGVEL_GLOBAL); -#else - KX_GameObject* self = static_cast(self_v); - return PyObjectFrom(GetAngularVelocity(false)); -#endif -} - -int KX_GameObject::pyattr_set_worldAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject* self = static_cast(self_v); - MT_Vector3 velocity; - if (!PyVecTo(value, velocity)) - return PY_SET_ATTR_FAIL; - - self->setAngularVelocity(velocity, false); - - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_GameObject::pyattr_get_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ -#ifdef USE_MATHUTILS - return Vector_CreatePyObject_cb( - BGE_PROXY_FROM_REF_BORROW(self_v), 3, - mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_ANGVEL_LOCAL); -#else - KX_GameObject* self = static_cast(self_v); - return PyObjectFrom(GetAngularVelocity(true)); -#endif -} - -int KX_GameObject::pyattr_set_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject* self = static_cast(self_v); - MT_Vector3 velocity; - if (!PyVecTo(value, velocity)) - return PY_SET_ATTR_FAIL; - - self->setAngularVelocity(velocity, true); - - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_GameObject::pyattr_get_linearDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_GameObject* self = static_cast(self_v); - return PyFloat_FromDouble(self->getLinearDamping()); -} - -int KX_GameObject::pyattr_set_linearDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject* self = static_cast(self_v); - float val = PyFloat_AsDouble(value); - self->setLinearDamping(val); - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_GameObject::pyattr_get_angularDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_GameObject* self = static_cast(self_v); - return PyFloat_FromDouble(self->getAngularDamping()); -} - -int KX_GameObject::pyattr_set_angularDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject* self = static_cast(self_v); - float val = PyFloat_AsDouble(value); - self->setAngularDamping(val); - return PY_SET_ATTR_SUCCESS; -} - - -PyObject *KX_GameObject::pyattr_get_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_GameObject* self = static_cast(self_v); - SG_Node* sg_parent; - if (self->GetSGNode() && (sg_parent = self->GetSGNode()->GetSGParent()) != NULL && sg_parent->IsSlowParent()) { - return PyFloat_FromDouble(static_cast(sg_parent->GetParentRelation())->GetTimeOffset()); - } else { - return PyFloat_FromDouble(0.0f); - } -} - -int KX_GameObject::pyattr_set_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject* self = static_cast(self_v); - if (self->GetSGNode()) { - MT_Scalar val = PyFloat_AsDouble(value); - SG_Node *sg_parent= self->GetSGNode()->GetSGParent(); - if (val < 0.0f) { /* also accounts for non float */ - PyErr_SetString(PyExc_AttributeError, "gameOb.timeOffset = float: KX_GameObject, expected a float zero or above"); - return PY_SET_ATTR_FAIL; - } - if (sg_parent && sg_parent->IsSlowParent()) - static_cast(sg_parent->GetParentRelation())->SetTimeOffset(val); - } - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_GameObject::pyattr_get_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_GameObject* self = static_cast(self_v); - int state = 0; - state |= self->GetState(); - return PyLong_FromLong(state); -} - -int KX_GameObject::pyattr_set_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject* self = static_cast(self_v); - int state_i = PyLong_AsLong(value); - unsigned int state = 0; - - if (state_i == -1 && PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, "gameOb.state = int: KX_GameObject, expected an int bit field"); - return PY_SET_ATTR_FAIL; - } - - state |= state_i; - if ((state & ((1<<30)-1)) == 0) { - PyErr_SetString(PyExc_AttributeError, "gameOb.state = int: KX_GameObject, state bitfield was not between 0 and 30 (1<<0 and 1<<29)"); - return PY_SET_ATTR_FAIL; - } - self->SetState(state); - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_GameObject::pyattr_get_meshes(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_GameObject* self = static_cast(self_v); - PyObject *meshes= PyList_New(self->m_meshes.size()); - int i; - - for (i=0; i < (int)self->m_meshes.size(); i++) - { - KX_MeshProxy* meshproxy = new KX_MeshProxy(self->m_meshes[i]); - PyList_SET_ITEM(meshes, i, meshproxy->NewProxy(true)); - } - - return meshes; -} - -PyObject *KX_GameObject::pyattr_get_obcolor(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ -#ifdef USE_MATHUTILS - return Vector_CreatePyObject_cb( - BGE_PROXY_FROM_REF_BORROW(self_v), 4, - mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_OBJECT_COLOR); -#else - KX_GameObject* self = static_cast(self_v); - return PyObjectFrom(self->GetObjectColor()); -#endif -} - -int KX_GameObject::pyattr_set_obcolor(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject* self = static_cast(self_v); - MT_Vector4 obcolor; - if (!PyVecTo(value, obcolor)) - return PY_SET_ATTR_FAIL; - - self->SetObjectColor(obcolor); - return PY_SET_ATTR_SUCCESS; -} - -static int kx_game_object_get_sensors_size_cb(void *self_v) -{ - return ((KX_GameObject *)self_v)->GetSensors().size(); -} - -static PyObject *kx_game_object_get_sensors_item_cb(void *self_v, int index) -{ - return ((KX_GameObject *)self_v)->GetSensors()[index]->GetProxy(); -} - -static const char *kx_game_object_get_sensors_item_name_cb(void *self_v, int index) -{ - return ((KX_GameObject *)self_v)->GetSensors()[index]->GetName().ReadPtr(); -} - -/* These are experimental! */ -PyObject *KX_GameObject::pyattr_get_sensors(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - return (new CListWrapper(self_v, - ((KX_GameObject *)self_v)->GetProxy(), - NULL, - kx_game_object_get_sensors_size_cb, - kx_game_object_get_sensors_item_cb, - kx_game_object_get_sensors_item_name_cb, - NULL))->NewProxy(true); -} - -static int kx_game_object_get_controllers_size_cb(void *self_v) -{ - return ((KX_GameObject *)self_v)->GetControllers().size(); -} - -static PyObject *kx_game_object_get_controllers_item_cb(void *self_v, int index) -{ - return ((KX_GameObject *)self_v)->GetControllers()[index]->GetProxy(); -} - -static const char *kx_game_object_get_controllers_item_name_cb(void *self_v, int index) -{ - return ((KX_GameObject *)self_v)->GetControllers()[index]->GetName().ReadPtr(); -} - -PyObject *KX_GameObject::pyattr_get_controllers(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - return (new CListWrapper(self_v, - ((KX_GameObject *)self_v)->GetProxy(), - NULL, - kx_game_object_get_controllers_size_cb, - kx_game_object_get_controllers_item_cb, - kx_game_object_get_controllers_item_name_cb, - NULL))->NewProxy(true); -} - -static int kx_game_object_get_actuators_size_cb(void *self_v) -{ - return ((KX_GameObject *)self_v)->GetActuators().size(); -} - -static PyObject *kx_game_object_get_actuators_item_cb(void *self_v, int index) -{ - return ((KX_GameObject *)self_v)->GetActuators()[index]->GetProxy(); -} - -static const char *kx_game_object_get_actuators_item_name_cb(void *self_v, int index) -{ - return ((KX_GameObject *)self_v)->GetActuators()[index]->GetName().ReadPtr(); -} - -PyObject *KX_GameObject::pyattr_get_actuators(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - return (new CListWrapper(self_v, - ((KX_GameObject *)self_v)->GetProxy(), - NULL, - kx_game_object_get_actuators_size_cb, - kx_game_object_get_actuators_item_cb, - kx_game_object_get_actuators_item_name_cb, - NULL))->NewProxy(true); -} -/* End experimental */ - -PyObject *KX_GameObject::pyattr_get_children(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_GameObject* self = static_cast(self_v); - return self->GetChildren()->NewProxy(true); -} - -PyObject *KX_GameObject::pyattr_get_children_recursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_GameObject* self = static_cast(self_v); - return self->GetChildrenRecursive()->NewProxy(true); -} - -PyObject *KX_GameObject::pyattr_get_attrDict(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_GameObject* self = static_cast(self_v); - - if (self->m_attr_dict==NULL) - self->m_attr_dict= PyDict_New(); - - Py_INCREF(self->m_attr_dict); - return self->m_attr_dict; -} - -PyObject *KX_GameObject::pyattr_get_debug(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_Scene *scene = KX_GetActiveScene(); - KX_GameObject *self = static_cast(self_v); - - return PyBool_FromLong(scene->ObjectInDebugList(self)); -} - -int KX_GameObject::pyattr_set_debug(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject *self = static_cast(self_v); - int param = PyObject_IsTrue(value); - - if (param == -1) { - PyErr_SetString(PyExc_AttributeError, "gameOb.debug = bool: KX_GameObject, expected True or False"); - return PY_SET_ATTR_FAIL; - } - - self->SetUseDebugProperties(param, false); - - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_GameObject::pyattr_get_debugRecursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_Scene *scene = KX_GetActiveScene(); - KX_GameObject *self = static_cast(self_v); - - return PyBool_FromLong(scene->ObjectInDebugList(self)); -} - -int KX_GameObject::pyattr_set_debugRecursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_GameObject *self = static_cast(self_v); - int param = PyObject_IsTrue(value); - - if (param == -1) { - PyErr_SetString(PyExc_AttributeError, "gameOb.debugRecursive = bool: KX_GameObject, expected True or False"); - return PY_SET_ATTR_FAIL; - } - - self->SetUseDebugProperties(param, true); - - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_GameObject::PyApplyForce(PyObject *args) -{ - int local = 0; - PyObject *pyvect; - - if (PyArg_ParseTuple(args, "O|i:applyForce", &pyvect, &local)) { - MT_Vector3 force; - if (PyVecTo(pyvect, force)) { - ApplyForce(force, (local!=0)); - Py_RETURN_NONE; - } - } - return NULL; -} - -PyObject *KX_GameObject::PyApplyTorque(PyObject *args) -{ - int local = 0; - PyObject *pyvect; - - if (PyArg_ParseTuple(args, "O|i:applyTorque", &pyvect, &local)) { - MT_Vector3 torque; - if (PyVecTo(pyvect, torque)) { - ApplyTorque(torque, (local!=0)); - Py_RETURN_NONE; - } - } - return NULL; -} - -PyObject *KX_GameObject::PyApplyRotation(PyObject *args) -{ - int local = 0; - PyObject *pyvect; - - if (PyArg_ParseTuple(args, "O|i:applyRotation", &pyvect, &local)) { - MT_Vector3 rotation; - if (PyVecTo(pyvect, rotation)) { - ApplyRotation(rotation, (local!=0)); - Py_RETURN_NONE; - } - } - return NULL; -} - -PyObject *KX_GameObject::PyApplyMovement(PyObject *args) -{ - int local = 0; - PyObject *pyvect; - - if (PyArg_ParseTuple(args, "O|i:applyMovement", &pyvect, &local)) { - MT_Vector3 movement; - if (PyVecTo(pyvect, movement)) { - ApplyMovement(movement, (local!=0)); - Py_RETURN_NONE; - } - } - return NULL; -} - -PyObject *KX_GameObject::PyGetLinearVelocity(PyObject *args) -{ - // only can get the velocity if we have a physics object connected to us... - int local = 0; - if (PyArg_ParseTuple(args,"|i:getLinearVelocity",&local)) - { - return PyObjectFrom(GetLinearVelocity((local!=0))); - } - else - { - return NULL; - } -} - -PyObject *KX_GameObject::PySetLinearVelocity(PyObject *args) -{ - int local = 0; - PyObject *pyvect; - - if (PyArg_ParseTuple(args,"O|i:setLinearVelocity",&pyvect,&local)) { - MT_Vector3 velocity; - if (PyVecTo(pyvect, velocity)) { - setLinearVelocity(velocity, (local!=0)); - Py_RETURN_NONE; - } - } - return NULL; -} - -PyObject *KX_GameObject::PyGetAngularVelocity(PyObject *args) -{ - // only can get the velocity if we have a physics object connected to us... - int local = 0; - if (PyArg_ParseTuple(args,"|i:getAngularVelocity",&local)) - { - return PyObjectFrom(GetAngularVelocity((local!=0))); - } - else - { - return NULL; - } -} - -PyObject *KX_GameObject::PySetAngularVelocity(PyObject *args) -{ - int local = 0; - PyObject *pyvect; - - if (PyArg_ParseTuple(args,"O|i:setAngularVelocity",&pyvect,&local)) { - MT_Vector3 velocity; - if (PyVecTo(pyvect, velocity)) { - setAngularVelocity(velocity, (local!=0)); - Py_RETURN_NONE; - } - } - return NULL; -} - -PyObject *KX_GameObject::PySetDamping(PyObject *args) -{ - float linear; - float angular; - - if (!PyArg_ParseTuple(args,"ff|i:setDamping", &linear, &angular)) - return NULL; - - setDamping(linear, angular); - Py_RETURN_NONE; -} - -PyObject *KX_GameObject::PySetVisible(PyObject *args) -{ - int visible, recursive = 0; - if (!PyArg_ParseTuple(args,"i|i:setVisible",&visible, &recursive)) - return NULL; - - SetVisible(visible ? true:false, recursive ? true:false); - UpdateBuckets(recursive ? true:false); - Py_RETURN_NONE; - -} - -PyObject *KX_GameObject::PySetOcclusion(PyObject *args) -{ - int occlusion, recursive = 0; - if (!PyArg_ParseTuple(args,"i|i:setOcclusion",&occlusion, &recursive)) - return NULL; - - SetOccluder(occlusion ? true:false, recursive ? true:false); - Py_RETURN_NONE; -} - -PyObject *KX_GameObject::PyGetVelocity(PyObject *args) -{ - // only can get the velocity if we have a physics object connected to us... - MT_Point3 point(0.0f,0.0f,0.0f); - PyObject *pypos = NULL; - - if (!PyArg_ParseTuple(args, "|O:getVelocity", &pypos) || (pypos && !PyVecTo(pypos, point))) - return NULL; - - return PyObjectFrom(GetVelocity(point)); -} - -PyObject *KX_GameObject::PyGetReactionForce() -{ - // only can get the velocity if we have a physics object connected to us... - - // XXX - Currently not working with bullet intergration, see KX_BulletPhysicsController.cpp's getReactionForce -#if 0 - if (GetPhysicsController1()) - return PyObjectFrom(GetPhysicsController1()->getReactionForce()); - return PyObjectFrom(dummy_point); -#endif - - return Py_BuildValue("fff", 0.0f, 0.0f, 0.0f); - -} - - - -PyObject *KX_GameObject::PyEnableRigidBody() -{ - if (GetPhysicsController()) - GetPhysicsController()->SetRigidBody(true); - - Py_RETURN_NONE; -} - - - -PyObject *KX_GameObject::PyDisableRigidBody() -{ - if (GetPhysicsController()) - GetPhysicsController()->SetRigidBody(false); - - Py_RETURN_NONE; -} - - -PyObject *KX_GameObject::PySetParent(PyObject *args) -{ - KX_Scene *scene = KX_GetActiveScene(); - SCA_LogicManager *logicmgr = GetScene()->GetLogicManager(); - PyObject *pyobj; - KX_GameObject *obj; - int addToCompound=1, ghost=1; - - if (!PyArg_ParseTuple(args,"O|ii:setParent", &pyobj, &addToCompound, &ghost)) { - return NULL; // Python sets a simple error - } - if (!ConvertPythonToGameObject(logicmgr, pyobj, &obj, true, "gameOb.setParent(obj): KX_GameObject")) - return NULL; - if (obj) - this->SetParent(scene, obj, addToCompound, ghost); - Py_RETURN_NONE; -} - -PyObject *KX_GameObject::PyRemoveParent() -{ - KX_Scene *scene = KX_GetActiveScene(); - - this->RemoveParent(scene); - Py_RETURN_NONE; -} - - -PyObject *KX_GameObject::PySetCollisionMargin(PyObject *value) -{ - float collisionMargin = PyFloat_AsDouble(value); - - if (collisionMargin==-1 && PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, "expected a float"); - return NULL; - } - - if (m_pPhysicsController) - { - m_pPhysicsController->SetMargin(collisionMargin); - Py_RETURN_NONE; - } - PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller"); - return NULL; -} - - - -PyObject *KX_GameObject::PyApplyImpulse(PyObject *args) -{ - PyObject *pyattach; - PyObject *pyimpulse; - int local = 0; - - if (!m_pPhysicsController) { - PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller"); - return NULL; - } - - if (PyArg_ParseTuple(args, "OO|i:applyImpulse", &pyattach, &pyimpulse, &local)) - { - MT_Point3 attach; - MT_Vector3 impulse; - if (PyVecTo(pyattach, attach) && PyVecTo(pyimpulse, impulse)) - { - m_pPhysicsController->ApplyImpulse(attach, impulse, (local!=0)); - Py_RETURN_NONE; - } - - } - - return NULL; -} - - - -PyObject *KX_GameObject::PySuspendDynamics(PyObject *args) -{ - bool ghost = false; - - if (!PyArg_ParseTuple(args, "|b", &ghost)) - return NULL; - - if (GetPhysicsController()) - GetPhysicsController()->SuspendDynamics(ghost); - - Py_RETURN_NONE; -} - - - -PyObject *KX_GameObject::PyRestoreDynamics() -{ - // Child objects must be static, so we block changing to dynamic - if (GetPhysicsController() && !GetParent()) - GetPhysicsController()->RestoreDynamics(); - Py_RETURN_NONE; -} - - -PyObject *KX_GameObject::PyAlignAxisToVect(PyObject *args) -{ - PyObject *pyvect; - int axis = 2; //z axis is the default - float fac = 1.0f; - - if (PyArg_ParseTuple(args,"O|if:alignAxisToVect",&pyvect,&axis, &fac)) - { - MT_Vector3 vect; - if (PyVecTo(pyvect, vect)) { - if (fac > 0.0f) { - if (fac> 1.0f) fac = 1.0f; - - AlignAxisToVect(vect, axis, fac); - NodeUpdateGS(0.f); - } - Py_RETURN_NONE; - } - } - return NULL; -} - -PyObject *KX_GameObject::PyGetAxisVect(PyObject *value) -{ - MT_Vector3 vect; - if (PyVecTo(value, vect)) - { - return PyObjectFrom(NodeGetWorldOrientation() * vect); - } - return NULL; -} - - -PyObject *KX_GameObject::PyGetPhysicsId() -{ - PHY_IPhysicsController* ctrl = GetPhysicsController(); - unsigned long long physid = 0; - if (ctrl) - { - physid = (unsigned long long)ctrl; - } - return PyLong_FromUnsignedLongLong(physid); -} - -PyObject *KX_GameObject::PyGetPropertyNames() -{ - PyObject *list= ConvertKeysToPython(); - - if (m_attr_dict) { - PyObject *key, *value; - Py_ssize_t pos = 0; - - while (PyDict_Next(m_attr_dict, &pos, &key, &value)) { - PyList_Append(list, key); - } - } - return list; -} - -KX_PYMETHODDEF_DOC_O(KX_GameObject, getDistanceTo, -"getDistanceTo(other): get distance to another point/KX_GameObject") -{ - MT_Point3 b; - if (PyVecTo(value, b)) - { - return PyFloat_FromDouble(NodeGetWorldPosition().distance(b)); - } - PyErr_Clear(); - - SCA_LogicManager *logicmgr = GetScene()->GetLogicManager(); - KX_GameObject *other; - if (ConvertPythonToGameObject(logicmgr, value, &other, false, "gameOb.getDistanceTo(value): KX_GameObject")) - { - return PyFloat_FromDouble(NodeGetWorldPosition().distance(other->NodeGetWorldPosition())); - } - - return NULL; -} - -KX_PYMETHODDEF_DOC_O(KX_GameObject, getVectTo, -"getVectTo(other): get vector and the distance to another point/KX_GameObject\n" -"Returns a 3-tuple with (distance,worldVector,localVector)\n") -{ - MT_Point3 toPoint, fromPoint; - MT_Vector3 toDir, locToDir; - MT_Scalar distance; - - SCA_LogicManager *logicmgr = GetScene()->GetLogicManager(); - PyObject *returnValue; - - if (!PyVecTo(value, toPoint)) - { - PyErr_Clear(); - - KX_GameObject *other; - if (ConvertPythonToGameObject(logicmgr, value, &other, false, "")) /* error will be overwritten */ - { - toPoint = other->NodeGetWorldPosition(); - } else - { - PyErr_SetString(PyExc_TypeError, "gameOb.getVectTo(other): KX_GameObject, expected a 3D Vector or KX_GameObject type"); - return NULL; - } - } - - fromPoint = NodeGetWorldPosition(); - toDir = toPoint-fromPoint; - distance = toDir.length(); - - if (MT_fuzzyZero(distance)) - { - //cout << "getVectTo() Error: Null vector!\n"; - locToDir = toDir = MT_Vector3(0.0f,0.0f,0.0f); - distance = 0.0f; - } else { - toDir.normalize(); - locToDir = toDir * NodeGetWorldOrientation(); - } - - returnValue = PyTuple_New(3); - if (returnValue) { // very unlikely to fail, python sets a memory error here. - PyTuple_SET_ITEM(returnValue, 0, PyFloat_FromDouble(distance)); - PyTuple_SET_ITEM(returnValue, 1, PyObjectFrom(toDir)); - PyTuple_SET_ITEM(returnValue, 2, PyObjectFrom(locToDir)); - } - return returnValue; -} - -struct KX_GameObject::RayCastData -{ - RayCastData(STR_String prop, bool xray, short mask) - :m_prop(prop), - m_xray(xray), - m_mask(mask), - m_hitObject(NULL) - { - } - - STR_String m_prop; - bool m_xray; - unsigned short m_mask; - KX_GameObject *m_hitObject; -}; - -bool KX_GameObject::RayHit(KX_ClientObjectInfo *client, KX_RayCast *result, RayCastData *rayData) -{ - KX_GameObject* hitKXObj = client->m_gameobject; - - // if X-ray option is selected, the unwnted objects were not tested, so get here only with true hit - // if not, all objects were tested and the front one may not be the correct one. - if ((rayData->m_xray || rayData->m_prop.Length() == 0 || hitKXObj->GetProperty(rayData->m_prop) != NULL) && - hitKXObj->GetUserCollisionGroup() & rayData->m_mask) - { - rayData->m_hitObject = hitKXObj; - return true; - } - // return true to stop RayCast::RayTest from looping, the above test was decisive - // We would want to loop only if we want to get more than one hit point - return true; -} - -/* this function is used to pre-filter the object before casting the ray on them. - * This is useful for "X-Ray" option when we want to see "through" unwanted object. - */ -bool KX_GameObject::NeedRayCast(KX_ClientObjectInfo *client, RayCastData *rayData) -{ - KX_GameObject* hitKXObj = client->m_gameobject; - - if (client->m_type > KX_ClientObjectInfo::ACTOR) - { - // Unknown type of object, skip it. - // Should not occur as the sensor objects are filtered in RayTest() - printf("Invalid client type %d found in ray casting\n", client->m_type); - return false; - } - - // if X-Ray option is selected, skip object that don't match the criteria as we see through them - // if not, test all objects because we don't know yet which one will be on front - if ((!rayData->m_xray || rayData->m_prop.Length() == 0 || hitKXObj->GetProperty(rayData->m_prop) != NULL) && - hitKXObj->GetUserCollisionGroup() & rayData->m_mask) - { - return true; - } - // skip the object - return false; -} - -KX_PYMETHODDEF_DOC(KX_GameObject, rayCastTo, -"rayCastTo(other,dist,prop): look towards another point/KX_GameObject and return first object hit within dist that matches prop\n" -" prop = property name that object must have; can be omitted => detect any object\n" -" dist = max distance to look (can be negative => look behind); 0 or omitted => detect up to other\n" -" other = 3-tuple or object reference") -{ - MT_Point3 toPoint; - PyObject *pyarg; - float dist = 0.0f; - char *propName = NULL; - SCA_LogicManager *logicmgr = GetScene()->GetLogicManager(); - - if (!PyArg_ParseTuple(args,"O|fs:rayCastTo", &pyarg, &dist, &propName)) { - return NULL; // python sets simple error - } - - if (!PyVecTo(pyarg, toPoint)) - { - KX_GameObject *other; - PyErr_Clear(); - - if (ConvertPythonToGameObject(logicmgr, pyarg, &other, false, "")) /* error will be overwritten */ - { - toPoint = other->NodeGetWorldPosition(); - } else - { - PyErr_SetString(PyExc_TypeError, "gameOb.rayCastTo(other,dist,prop): KX_GameObject, the first argument to rayCastTo must be a vector or a KX_GameObject"); - return NULL; - } - } - MT_Point3 fromPoint = NodeGetWorldPosition(); - - if (dist != 0.0f) - toPoint = fromPoint + dist * (toPoint-fromPoint).safe_normalized(); - - PHY_IPhysicsEnvironment* pe = GetScene()->GetPhysicsEnvironment(); - PHY_IPhysicsController *spc = GetPhysicsController(); - KX_GameObject *parent = GetParent(); - if (!spc && parent) - spc = parent->GetPhysicsController(); - - RayCastData rayData(propName, false, (1u << OB_MAX_COL_MASKS) - 1); - KX_RayCast::Callback callback(this, spc, &rayData); - if (KX_RayCast::RayTest(pe, fromPoint, toPoint, callback) && rayData.m_hitObject) { - return rayData.m_hitObject->GetProxy(); - } - - Py_RETURN_NONE; -} - -/* faster then Py_BuildValue since some scripts call raycast a lot */ -static PyObject *none_tuple_3() -{ - PyObject *ret= PyTuple_New(3); - PyTuple_SET_ITEM(ret, 0, Py_None); - PyTuple_SET_ITEM(ret, 1, Py_None); - PyTuple_SET_ITEM(ret, 2, Py_None); - - Py_INCREF(Py_None); - Py_INCREF(Py_None); - Py_INCREF(Py_None); - return ret; -} -static PyObject *none_tuple_4() -{ - PyObject *ret= PyTuple_New(4); - PyTuple_SET_ITEM(ret, 0, Py_None); - PyTuple_SET_ITEM(ret, 1, Py_None); - PyTuple_SET_ITEM(ret, 2, Py_None); - PyTuple_SET_ITEM(ret, 3, Py_None); - - Py_INCREF(Py_None); - Py_INCREF(Py_None); - Py_INCREF(Py_None); - Py_INCREF(Py_None); - return ret; -} - -static PyObject *none_tuple_5() -{ - PyObject *ret= PyTuple_New(5); - PyTuple_SET_ITEM(ret, 0, Py_None); - PyTuple_SET_ITEM(ret, 1, Py_None); - PyTuple_SET_ITEM(ret, 2, Py_None); - PyTuple_SET_ITEM(ret, 3, Py_None); - PyTuple_SET_ITEM(ret, 4, Py_None); - - Py_INCREF(Py_None); - Py_INCREF(Py_None); - Py_INCREF(Py_None); - Py_INCREF(Py_None); - Py_INCREF(Py_None); - return ret; -} - -KX_PYMETHODDEF_DOC(KX_GameObject, rayCast, - "rayCast(to,from,dist,prop,face,xray,poly,mask): cast a ray and return 3-tuple (object,hit,normal) or 4-tuple (object,hit,normal,polygon) or 4-tuple (object,hit,normal,polygon,hituv) of contact point with object within dist that matches prop.\n" - " If no hit, return (None,None,None) or (None,None,None,None) or (None,None,None,None,None).\n" -" to = 3-tuple or object reference for destination of ray (if object, use center of object)\n" -" from = 3-tuple or object reference for origin of ray (if object, use center of object)\n" -" Can be None or omitted => start from self object center\n" -" dist = max distance to look (can be negative => look behind); 0 or omitted => detect up to to\n" -" prop = property name that object must have; can be omitted => detect any object\n" -" face = normal option: 1=>return face normal; 0 or omitted => normal is oriented towards origin\n" -" xray = X-ray option: 1=>skip objects that don't match prop; 0 or omitted => stop on first object\n" -" poly = polygon option: 1=>return value is a 4-tuple and the 4th element is a KX_PolyProxy object\n" -" which can be None if hit object has no mesh or if there is no hit\n" -" 2=>return value is a 5-tuple, the 4th element is the KX_PolyProxy object\n" -" and the 5th element is the vector of UV coordinates at the hit point of the None if there is no UV mapping\n" -" If 0 or omitted, return value is a 3-tuple\n" -" mask = collision mask: the collision mask that ray can hit, 0 < mask < 65536\n" -"Note: The object on which you call this method matters: the ray will ignore it.\n" -" prop and xray option interact as follow:\n" -" prop off, xray off: return closest hit or no hit if there is no object on the full extend of the ray\n" -" prop off, xray on : idem\n" -" prop on, xray off: return closest hit if it matches prop, no hit otherwise\n" -" prop on, xray on : return closest hit matching prop or no hit if there is no object matching prop on the full extend of the ray\n") -{ - MT_Point3 toPoint; - MT_Point3 fromPoint; - PyObject *pyto; - PyObject *pyfrom = NULL; - float dist = 0.0f; - char *propName = NULL; - KX_GameObject *other; - int face=0, xray=0, poly=0; - int mask = (1 << OB_MAX_COL_MASKS) - 1; - SCA_LogicManager *logicmgr = GetScene()->GetLogicManager(); - - if (!PyArg_ParseTuple(args,"O|Ofsiiii:rayCast", &pyto, &pyfrom, &dist, &propName, &face, &xray, &poly, &mask)) { - return NULL; // Python sets a simple error - } - - if (!PyVecTo(pyto, toPoint)) - { - PyErr_Clear(); - - if (ConvertPythonToGameObject(logicmgr, pyto, &other, false, "")) /* error will be overwritten */ - { - toPoint = other->NodeGetWorldPosition(); - } else - { - PyErr_SetString(PyExc_TypeError, "the first argument to rayCast must be a vector or a KX_GameObject"); - return NULL; - } - } - if (!pyfrom || pyfrom == Py_None) - { - fromPoint = NodeGetWorldPosition(); - } - else if (!PyVecTo(pyfrom, fromPoint)) - { - PyErr_Clear(); - - if (ConvertPythonToGameObject(logicmgr, pyfrom, &other, false, "")) /* error will be overwritten */ - { - fromPoint = other->NodeGetWorldPosition(); - } else - { - PyErr_SetString(PyExc_TypeError, "gameOb.rayCast(to,from,dist,prop,face,xray,poly,mask): KX_GameObject, the second optional argument to rayCast must be a vector or a KX_GameObject"); - return NULL; - } - } - - if (mask == 0 || mask & ~((1 << OB_MAX_COL_MASKS) - 1)) { - PyErr_Format(PyExc_TypeError, "gameOb.rayCast(to,from,dist,prop,face,xray,poly,mask): KX_GameObject, mask argument to rayCast must be a int bitfield, 0 < mask < %i", (1 << OB_MAX_COL_MASKS)); - return NULL; - } - - if (dist != 0.0f) { - MT_Vector3 toDir = toPoint-fromPoint; - if (MT_fuzzyZero(toDir.length2())) { - //return Py_BuildValue("OOO", Py_None, Py_None, Py_None); - return none_tuple_3(); - } - toDir.normalize(); - toPoint = fromPoint + (dist) * toDir; - } else if (MT_fuzzyZero((toPoint-fromPoint).length2())) { - //return Py_BuildValue("OOO", Py_None, Py_None, Py_None); - return none_tuple_3(); - } - - PHY_IPhysicsEnvironment* pe = GetScene()->GetPhysicsEnvironment(); - PHY_IPhysicsController *spc = GetPhysicsController(); - KX_GameObject *parent = GetParent(); - if (!spc && parent) - spc = parent->GetPhysicsController(); - - // to get the hit results - RayCastData rayData(propName, xray, mask); - KX_RayCast::Callback callback(this, spc, &rayData, face, (poly == 2)); - - if (KX_RayCast::RayTest(pe, fromPoint, toPoint, callback) && rayData.m_hitObject) { - PyObject *returnValue = (poly == 2) ? PyTuple_New(5) : (poly) ? PyTuple_New(4) : PyTuple_New(3); - if (returnValue) { // unlikely this would ever fail, if it does python sets an error - PyTuple_SET_ITEM(returnValue, 0, rayData.m_hitObject->GetProxy()); - PyTuple_SET_ITEM(returnValue, 1, PyObjectFrom(callback.m_hitPoint)); - PyTuple_SET_ITEM(returnValue, 2, PyObjectFrom(callback.m_hitNormal)); - if (poly) - { - if (callback.m_hitMesh) - { - // if this field is set, then we can trust that m_hitPolygon is a valid polygon - RAS_Polygon* polygon = callback.m_hitMesh->GetPolygon(callback.m_hitPolygon); - KX_PolyProxy* polyproxy = new KX_PolyProxy(callback.m_hitMesh, polygon); - PyTuple_SET_ITEM(returnValue, 3, polyproxy->NewProxy(true)); - if (poly == 2) - { - if (callback.m_hitUVOK) - PyTuple_SET_ITEM(returnValue, 4, PyObjectFrom(callback.m_hitUV)); - else { - Py_INCREF(Py_None); - PyTuple_SET_ITEM(returnValue, 4, Py_None); - } - } - } - else - { - Py_INCREF(Py_None); - PyTuple_SET_ITEM(returnValue, 3, Py_None); - if (poly==2) - { - Py_INCREF(Py_None); - PyTuple_SET_ITEM(returnValue, 4, Py_None); - } - } - } - } - return returnValue; - } - // no hit - if (poly == 2) - return none_tuple_5(); - else if (poly) - return none_tuple_4(); - else - return none_tuple_3(); -} - -KX_PYMETHODDEF_DOC_VARARGS(KX_GameObject, sendMessage, - "sendMessage(subject, [body, to])\n" -"sends a message in same manner as a message actuator" -"subject = Subject of the message (string)" -"body = Message body (string)" -"to = Name of object to send the message to") -{ - KX_Scene *scene = KX_GetActiveScene(); - char* subject; - char* body = (char *)""; - char* to = (char *)""; - const STR_String& from = GetName(); - - if (!PyArg_ParseTuple(args, "s|ss:sendMessage", &subject, &body, &to)) - return NULL; - - scene->GetNetworkScene()->SendMessage(to, from, subject, body); - Py_RETURN_NONE; -} - -static void layer_check(short &layer, const char *method_name) -{ - if (layer < 0 || layer >= MAX_ACTION_LAYERS) - { - printf("KX_GameObject.%s(): given layer (%d) is out of range (0 - %d), setting to 0.\n", method_name, layer, MAX_ACTION_LAYERS-1); - layer = 0; - } -} - -KX_PYMETHODDEF_DOC(KX_GameObject, playAction, - "playAction(name, start_frame, end_frame, layer=0, priority=0 blendin=0, play_mode=ACT_MODE_PLAY, layer_weight=0.0, ipo_flags=0, speed=1.0)\n" - "Plays an action\n") -{ - const char* name; - float start, end, blendin=0.f, speed=1.f, layer_weight=0.f; - short layer=0, priority=0; - short ipo_flags=0; - short play_mode=0; - short blend_mode=0; - - static const char *kwlist[] = {"name", "start_frame", "end_frame", "layer", "priority", "blendin", "play_mode", "layer_weight", "ipo_flags", "speed", "blend_mode", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "sff|hhfhfhfh:playAction", const_cast(kwlist), - &name, &start, &end, &layer, &priority, &blendin, &play_mode, &layer_weight, &ipo_flags, &speed, &blend_mode)) - return NULL; - - layer_check(layer, "playAction"); - - if (play_mode < 0 || play_mode > BL_Action::ACT_MODE_MAX) - { - printf("KX_GameObject.playAction(): given play_mode (%d) is out of range (0 - %d), setting to ACT_MODE_PLAY", play_mode, BL_Action::ACT_MODE_MAX-1); - play_mode = BL_Action::ACT_MODE_PLAY; - } - - if (blend_mode < 0 || blend_mode > BL_Action::ACT_BLEND_MAX) - { - printf("KX_GameObject.playAction(): given blend_mode (%d) is out of range (0 - %d), setting to ACT_BLEND_BLEND", blend_mode, BL_Action::ACT_BLEND_MAX-1); - blend_mode = BL_Action::ACT_BLEND_BLEND; - } - - if (layer_weight < 0.f || layer_weight > 1.f) - { - printf("KX_GameObject.playAction(): given layer_weight (%f) is out of range (0.0 - 1.0), setting to 0.0", layer_weight); - layer_weight = 0.f; - } - - PlayAction(name, start, end, layer, priority, blendin, play_mode, layer_weight, ipo_flags, speed, blend_mode); - - Py_RETURN_NONE; -} - -KX_PYMETHODDEF_DOC(KX_GameObject, stopAction, - "stopAction(layer=0)\n" - "Stop playing the action on the given layer\n") -{ - short layer = 0; - - if (!PyArg_ParseTuple(args, "|h:stopAction", &layer)) - return NULL; - - layer_check(layer, "stopAction"); - - StopAction(layer); - - Py_RETURN_NONE; -} - -KX_PYMETHODDEF_DOC(KX_GameObject, getActionFrame, - "getActionFrame(layer=0)\n" - "Gets the current frame of the action playing in the supplied layer\n") -{ - short layer = 0; - - if (!PyArg_ParseTuple(args, "|h:getActionFrame", &layer)) - return NULL; - - layer_check(layer, "getActionFrame"); - - return PyFloat_FromDouble(GetActionFrame(layer)); -} - -KX_PYMETHODDEF_DOC(KX_GameObject, getActionName, - "getActionName(layer=0)\n" - "Gets the name of the current action playing in the supplied layer\n") -{ - short layer = 0; - - if (!PyArg_ParseTuple(args, "|h:getActionName", &layer)) - return NULL; - - layer_check(layer, "getActionName"); - - return PyUnicode_FromString(GetActionName(layer)); -} - -KX_PYMETHODDEF_DOC(KX_GameObject, setActionFrame, - "setActionFrame(frame, layer=0)\n" - "Set the current frame of the action playing in the supplied layer\n") -{ - short layer = 0; - float frame; - - if (!PyArg_ParseTuple(args, "f|h:setActionFrame", &frame, &layer)) - return NULL; - - layer_check(layer, "setActionFrame"); - - SetActionFrame(layer, frame); - - Py_RETURN_NONE; -} - -KX_PYMETHODDEF_DOC(KX_GameObject, isPlayingAction, - "isPlayingAction(layer=0)\n" - "Checks to see if there is an action playing in the given layer\n") -{ - short layer = 0; - - if (!PyArg_ParseTuple(args, "|h:isPlayingAction", &layer)) - return NULL; - - layer_check(layer, "isPlayingAction"); - - return PyBool_FromLong(!IsActionDone(layer)); -} - - -KX_PYMETHODDEF_DOC(KX_GameObject, addDebugProperty, -"addDebugProperty(name, visible=1)\n" -"Added or remove a debug property to the debug list.\n") -{ - KX_Scene *scene = KX_GetActiveScene(); - char *name; - int visible = 1; - - if (!PyArg_ParseTuple(args,"s|i:debugProperty", &name , &visible)) - return NULL; - - if (visible) { - if (!scene->PropertyInDebugList(this, name)) - scene->AddDebugProperty(this, name); - } - else { - scene->RemoveDebugProperty(this, name); - } - - Py_RETURN_NONE; -} - - -/* dict style access */ - - -/* Matches python dict.get(key, [default]) */ -PyObject *KX_GameObject::Pyget(PyObject *args) -{ - PyObject *key; - PyObject *def = Py_None; - PyObject *ret; - - if (!PyArg_ParseTuple(args, "O|O:get", &key, &def)) - return NULL; - - - if (PyUnicode_Check(key)) { - CValue *item = GetProperty(_PyUnicode_AsString(key)); - if (item) { - ret = item->ConvertValueToPython(); - if (ret) - return ret; - else - return item->GetProxy(); - } - } - - if (m_attr_dict && (ret=PyDict_GetItem(m_attr_dict, key))) { - Py_INCREF(ret); - return ret; - } - - Py_INCREF(def); - return def; -} - -bool ConvertPythonToGameObject(SCA_LogicManager *manager, PyObject *value, KX_GameObject **object, bool py_none_ok, const char *error_prefix) -{ - if (value==NULL) { - PyErr_Format(PyExc_TypeError, "%s, python pointer NULL, should never happen", error_prefix); - *object = NULL; - return false; - } - - if (value==Py_None) { - *object = NULL; - - if (py_none_ok) { - return true; - } else { - PyErr_Format(PyExc_TypeError, "%s, expected KX_GameObject or a KX_GameObject name, None is invalid", error_prefix); - return false; - } - } - - if (PyUnicode_Check(value)) { - *object = (KX_GameObject*)manager->GetGameObjectByName(STR_String( _PyUnicode_AsString(value) )); - - if (*object) { - return true; - } else { - PyErr_Format(PyExc_ValueError, "%s, requested name \"%s\" did not match any KX_GameObject in this scene", error_prefix, _PyUnicode_AsString(value)); - return false; - } - } - - if (PyObject_TypeCheck(value, &KX_GameObject::Type) || - PyObject_TypeCheck(value, &KX_LightObject::Type) || - PyObject_TypeCheck(value, &KX_Camera::Type) || - PyObject_TypeCheck(value, &KX_FontObject::Type) || - PyObject_TypeCheck(value, &KX_NavMeshObject::Type)) - { - *object = static_castBGE_PROXY_REF(value); - - /* sets the error */ - if (*object==NULL) { - PyErr_Format(PyExc_SystemError, "%s, " BGE_PROXY_ERROR_MSG, error_prefix); - return false; - } - - return true; - } - - *object = NULL; - - if (py_none_ok) { - PyErr_Format(PyExc_TypeError, "%s, expect a KX_GameObject, a string or None", error_prefix); - } else { - PyErr_Format(PyExc_TypeError, "%s, expect a KX_GameObject or a string", error_prefix); - } - - return false; -} -#endif // WITH_PYTHON diff --git a/source/gameengine/Ketsji/KX_GameObject.h b/source/gameengine/Ketsji/KX_GameObject.h deleted file mode 100644 index 9c582d3e27a..00000000000 --- a/source/gameengine/Ketsji/KX_GameObject.h +++ /dev/null @@ -1,1142 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_GameObject.h - * \ingroup ketsji - * \brief General KX game object. - */ - -#ifndef __KX_GAMEOBJECT_H__ -#define __KX_GAMEOBJECT_H__ - -#ifdef _MSC_VER - /* get rid of this stupid "warning 'this' used in initialiser list", generated by VC when including Solid/Sumo */ -# pragma warning (disable:4355) -#endif - -#include - -#include "EXP_ListValue.h" -#include "SCA_IObject.h" -#include "SG_Node.h" -#include "MT_Transform.h" -#include "MT_CmMatrix4x4.h" -#include "CTR_Map.h" -#include "CTR_HashedPtr.h" -#include "KX_Scene.h" -#include "KX_KetsjiEngine.h" /* for m_anim_framerate */ -#include "DNA_constraint_types.h" /* for constraint replication */ -#include "DNA_object_types.h" -#include "SCA_LogicManager.h" /* for ConvertPythonToGameObject to search object names */ - -//Forward declarations. -struct KX_ClientObjectInfo; -class KX_RayCast; -class RAS_MeshObject; -class PHY_IGraphicController; -class PHY_IPhysicsEnvironment; -class PHY_IPhysicsController; -class BL_ActionManager; -struct Object; -class KX_ObstacleSimulation; -struct bAction; - -#ifdef WITH_PYTHON -/* utility conversion function */ -bool ConvertPythonToGameObject(SCA_LogicManager *logicmgr, PyObject *value, KX_GameObject **object, bool py_none_ok, const char *error_prefix); -#endif - -#ifdef USE_MATHUTILS -void KX_GameObject_Mathutils_Callback_Init(void); -#endif - -/** - * KX_GameObject is the main class for dynamic objects. - */ -class KX_GameObject : public SCA_IObject -{ - Py_Header -protected: - - bool m_bDyna; - KX_ClientObjectInfo* m_pClient_info; - STR_String m_name; - STR_String m_text; - int m_layer; - std::vector m_meshes; - std::vector m_lodmeshes; - int m_currentLodLevel; - short m_previousLodLevel; - SG_QList m_meshSlots; // head of mesh slots of this - struct Object* m_pBlenderObject; - struct Object* m_pBlenderGroupObject; - - bool m_bUseObjectColor; - bool m_bIsNegativeScaling; - MT_Vector4 m_objectColor; - - // Bit fields for user control over physics collisions - unsigned short m_userCollisionGroup; - unsigned short m_userCollisionMask; - - // visible = user setting - // culled = while rendering, depending on camera - bool m_bVisible; - bool m_bCulled; - bool m_bOccluder; - - PHY_IPhysicsController* m_pPhysicsController; - PHY_IGraphicController* m_pGraphicController; - - SG_Node* m_pSGNode; - - MT_CmMatrix4x4 m_OpenGL_4x4Matrix; - std::vector m_constraints; - - KX_ObstacleSimulation* m_pObstacleSimulation; - - CListValue* m_pInstanceObjects; - KX_GameObject* m_pDupliGroupObject; - - // The action manager is used to play/stop/update actions - BL_ActionManager* m_actionManager; - - BL_ActionManager* GetActionManager(); - - bool m_bRecordAnimation; - -public: - bool m_isDeformable; - - /** - * KX_GameObject custom infos for ray cast, it contains property name, - * collision mask, xray flag and hited object. - * This structure is created during ray cast and passed as argument - * "data" to functions KX_GameObject::NeedRayCast and KX_GameObject::RayHit. - */ - struct RayCastData; - - /** - * Helper function for modules that can't include KX_ClientObjectInfo.h - */ - static KX_GameObject* GetClientObject(KX_ClientObjectInfo* info); - -#ifdef WITH_PYTHON - // Python attributes that wont convert into CValue - // - // there are 2 places attributes can be stored, in the CValue, - // where attributes are converted into BGE's CValue types - // these can be used with property actuators - // - // For the python API, For types that cannot be converted into CValues (lists, dicts, GameObjects) - // these will be put into "m_attr_dict", logic bricks cannot access them. - // - // rules for setting attributes. - // - // * there should NEVER be a CValue and a m_attr_dict attribute with matching names. get/sets make sure of this. - // * if CValue conversion fails, use a PyObject in "m_attr_dict" - // * when assigning a value, first see if it can be a CValue, if it can remove the "m_attr_dict" and set the CValue - // - PyObject* m_attr_dict; - PyObject* m_collisionCallbacks; -#endif - - virtual void /* This function should be virtual - derived classed override it */ - Relink( - CTR_Map *map - ); - - /** - * Compute an OpenGl compatible 4x4 matrix. Has the - * side effect of storing the result internally. The - * memory for the matrix remains the property of this class. - */ - float * - GetOpenGLMatrix( - ); - - /** - * Return a pointer to a MT_CmMatrix4x4 storing the - * opengl transformation for this object. This is updated - * by a call to GetOpenGLMatrix(). This class owns the - * memory for the returned matrix. - */ - - MT_CmMatrix4x4 * - GetOpenGLMatrixPtr( - ) { - return &m_OpenGL_4x4Matrix; - }; - - /** - * Update the blender object obmat field from the object world position - * if blendobj is NULL, update the object pointed by m_pBlenderObject - * The user must take action to restore the matrix before leaving the GE. - * Used in Armature evaluation - */ - void - UpdateBlenderObjectMatrix(Object* blendobj=NULL); - - /** - * Used for constraint replication for group instances. - * The list of constraints is filled during data conversion. - */ - void AddConstraint(bRigidBodyJointConstraint *cons); - std::vector GetConstraints(); - void ClearConstraints(); - - /** - * Get a pointer to the game object that is the parent of - * this object. Or NULL if there is no parent. The returned - * object is part of a reference counting scheme. Calling - * this function ups the reference count on the returned - * object. It is the responsibility of the caller to decrement - * the reference count when you have finished with it. - */ - KX_GameObject* - GetParent( - ); - - /** - * Sets the parent of this object to a game object - */ - void SetParent(KX_Scene *scene, KX_GameObject *obj, bool addToCompound=true, bool ghost=true); - - /** - * Removes the parent of this object to a game object - */ - void RemoveParent(KX_Scene *scene); - - /********************************* - * group reference API - *********************************/ - - KX_GameObject* - GetDupliGroupObject( - ); - - CListValue* - GetInstanceObjects( - ); - - void - SetDupliGroupObject(KX_GameObject* - ); - - void - AddInstanceObjects(KX_GameObject* - ); - - void - RemoveDupliGroupObject( - ); - - void - RemoveInstanceObject(KX_GameObject* - ); - /********************************* - * Animation API - *********************************/ - - /** - * Adds an action to the object's action manager - */ - bool PlayAction(const char* name, - float start, - float end, - short layer=0, - short priority=0, - float blendin=0.f, - short play_mode=0, - float layer_weight=0.f, - short ipo_flags=0, - float playback_speed=1.f, - short blend_mode=0); - - /** - * Gets the current frame of an action - */ - float GetActionFrame(short layer); - - /** - * Gets the name of the current action - */ - const char *GetActionName(short layer); - - /** - * Sets the current frame of an action - */ - void SetActionFrame(short layer, float frame); - - /** - * Gets the currently running action on the given layer - */ - bAction *GetCurrentAction(short layer); - - /** - * Sets play mode of the action on the given layer - */ - void SetPlayMode(short layer, short mode); - - /** - * Sets the start and end times of the action on the given layer - */ - void SetTimes(short layer, float start, float end); - - /** - * Stop playing the action on the given layer - */ - void StopAction(short layer); - - /** - * Remove playing tagged actions. - */ - void RemoveTaggedActions(); - - /** - * Check if an action has finished playing - */ - bool IsActionDone(short layer); - - /** - * Kick the object's action manager - */ - void UpdateActionManager(float curtime); - - /********************************* - * End Animation API - *********************************/ - - /** - * Construct a game object. This class also inherits the - * default constructors - use those with care! - */ - - KX_GameObject( - void* sgReplicationInfo, - SG_Callbacks callbacks - ); - - virtual - ~KX_GameObject( - ); - - /** - * \section Stuff which is here due to poor design. - * Inherited from CValue and needs an implementation. - * Do not expect these functions do to anything sensible. - */ - - /** - * Inherited from CValue -- does nothing! - */ - CValue* - Calc( - VALUE_OPERATOR op, - CValue *val - ); - - /** - * Inherited from CValue -- does nothing! - */ - CValue* - CalcFinal( - VALUE_DATA_TYPE dtype, - VALUE_OPERATOR op, - CValue *val - ); - - /** - * Inherited from CValue -- does nothing! - */ - const - STR_String & - GetText( - ); - - /** - * Inherited from CValue -- does nothing! - */ - double - GetNumber( - ); - - /** - * \section Inherited from CValue. These are the useful - * part of the CValue interface that this class implements. - */ - - /** - * Inherited from CValue -- returns the name of this object. - */ - STR_String& - GetName( - ); - - /** - * Inherited from CValue -- set the name of this object. - */ - void - SetName( - const char *name - ); - - /** - * Inherited from CValue -- return a new copy of this - * instance allocated on the heap. Ownership of the new - * object belongs with the caller. - */ - virtual CValue* - GetReplica( - ); - - /** - * Inherited from CValue -- Makes sure any internal - * data owned by this class is deep copied. Called internally - */ - virtual void - ProcessReplica(); - - /** - * Return the linear velocity of the game object. - */ - MT_Vector3 - GetLinearVelocity( - bool local=false - ); - - /** - * Return the linear velocity of a given point in world coordinate - * but relative to center of object ([0,0,0]=center of object) - */ - MT_Vector3 - GetVelocity( - const MT_Point3& position - ); - - /** - * Return the mass of the object - */ - MT_Scalar - GetMass(); - - /** - * Return the local inertia vector of the object - */ - MT_Vector3 - GetLocalInertia(); - - /** - * Return the angular velocity of the game object. - */ - MT_Vector3 - GetAngularVelocity( - bool local=false - ); - - /** - * Align the object to a given normal. - */ - void - AlignAxisToVect( - const MT_Vector3& vect, - int axis = 2, - float fac = 1.0 - ); - - /** - * Quick'n'dirty obcolor ipo stuff - */ - - void - SetObjectColor( - const MT_Vector4& rgbavec - ); - - const MT_Vector4& - GetObjectColor(); - - - void - ResolveCombinedVelocities( - const MT_Vector3 & lin_vel, - const MT_Vector3 & ang_vel, - bool lin_vel_local, - bool ang_vel_local - ); - - /** - * \return a pointer to the physics controller owned by this class. - */ - - PHY_IPhysicsController* GetPhysicsController(); - - void SetPhysicsController(PHY_IPhysicsController* physicscontroller,bool isDynamic) - { - m_bDyna = isDynamic; - m_pPhysicsController = physicscontroller; - } - - virtual class RAS_Deformer* GetDeformer() - { - return 0; - } - virtual void SetDeformer(class RAS_Deformer* deformer) - { - - } - - /** - * \return a pointer to the graphic controller owner by this class - */ - PHY_IGraphicController* GetGraphicController() - { - return m_pGraphicController; - } - - void SetGraphicController(PHY_IGraphicController* graphiccontroller) - { - m_pGraphicController = graphiccontroller; - } - /* - * @add/remove the graphic controller to the physic system - */ - void ActivateGraphicController(bool recurse); - - /** Set the object's collison group - * \param filter The group bitfield - */ - void SetUserCollisionGroup(unsigned short filter); - - /** Set the object's collison mask - * \param filter The mask bitfield - */ - void SetUserCollisionMask(unsigned short mask); - unsigned short GetUserCollisionGroup(); - unsigned short GetUserCollisionMask(); - /** - * Extra broadphase check for user controllable collisions - */ - bool CheckCollision(KX_GameObject *other); - - /** - * \section Coordinate system manipulation functions - */ - - void NodeSetLocalPosition(const MT_Point3& trans ); - - void NodeSetLocalOrientation(const MT_Matrix3x3& rot ); - void NodeSetGlobalOrientation(const MT_Matrix3x3& rot ); - - void NodeSetLocalScale( const MT_Vector3& scale ); - void NodeSetWorldScale( const MT_Vector3& scale ); - - void NodeSetRelativeScale( const MT_Vector3& scale ); - - // adapt local position so that world position is set to desired position - void NodeSetWorldPosition(const MT_Point3& trans); - - void - NodeUpdateGS( - double time - ); - - const MT_Matrix3x3& NodeGetWorldOrientation( ) const; - const MT_Vector3& NodeGetWorldScaling( ) const; - const MT_Point3& NodeGetWorldPosition( ) const; - - const MT_Matrix3x3& NodeGetLocalOrientation( ) const; - const MT_Vector3& NodeGetLocalScaling( ) const; - const MT_Point3& NodeGetLocalPosition( ) const; - - /** - * \section scene graph node accessor functions. - */ - - SG_Node* GetSGNode( ) - { - return m_pSGNode; - } - - const SG_Node* GetSGNode( ) const - { - return m_pSGNode; - } - - /** - * \section blender object accessor functions. - */ - - struct Object* GetBlenderObject( ) - { - return m_pBlenderObject; - } - - void SetBlenderObject(struct Object* obj) - { - m_pBlenderObject = obj; - } - - struct Object* GetBlenderGroupObject( ) - { - return m_pBlenderGroupObject; - } - - void SetBlenderGroupObject(struct Object* obj) - { - m_pBlenderGroupObject = obj; - } - - bool IsDupliGroup() - { - return (m_pBlenderObject && - (m_pBlenderObject->transflag & OB_DUPLIGROUP) && - m_pBlenderObject->dup_group != NULL) ? true : false; - } - - /** - * Set the Scene graph node for this game object. - * warning - it is your responsibility to make sure - * all controllers look at this new node. You must - * also take care of the memory associated with the - * old node. This class takes ownership of the new - * node. - */ - void SetSGNode(SG_Node* node ) - { - m_pSGNode = node; - } - - //Is it a dynamic/physics object ? - bool IsDynamic() const - { - return m_bDyna; - } - - bool IsDynamicsSuspended() const; - - /** - * Should we record animation for this object? - */ - - void SetRecordAnimation(bool recordAnimation) - { - m_bRecordAnimation = recordAnimation; - } - - bool IsRecordAnimation() const - { - return m_bRecordAnimation; - } - - /** - * Check if this object has a vertex parent relationship - */ - bool IsVertexParent( ) - { - return (m_pSGNode && m_pSGNode->GetSGParent() && m_pSGNode->GetSGParent()->IsVertexParent()); - } - - /// \see KX_RayCast - bool RayHit(KX_ClientObjectInfo *client, KX_RayCast *result, RayCastData *rayData); - /// \see KX_RayCast - bool NeedRayCast(KX_ClientObjectInfo *client, RayCastData *rayData); - - - /** - * \section Physics accessors for this node. - * - * All these calls get passed directly to the physics controller - * owned by this object. - * This is real interface bloat. Why not just use the physics controller - * directly? I think this is because the python interface is in the wrong - * place. - */ - - void - ApplyForce( - const MT_Vector3& force, bool local - ); - - void - ApplyTorque( - const MT_Vector3& torque, - bool local - ); - - void - ApplyRotation( - const MT_Vector3& drot, - bool local - ); - - void - ApplyMovement( - const MT_Vector3& dloc, - bool local - ); - - void - addLinearVelocity( - const MT_Vector3& lin_vel, - bool local - ); - - void - setLinearVelocity( - const MT_Vector3& lin_vel, - bool local - ); - - void - setAngularVelocity( - const MT_Vector3& ang_vel, - bool local - ); - - virtual float getLinearDamping() const; - virtual float getAngularDamping() const; - virtual void setLinearDamping(float damping); - virtual void setAngularDamping(float damping); - virtual void setDamping(float linear, float angular); - - /** - * Update the physics object transform based upon the current SG_Node - * position. - */ - void - UpdateTransform( - ); - - static void UpdateTransformFunc(SG_IObject* node, void* gameobj, void* scene); - - /** - * only used for sensor objects - */ - void SynchronizeTransform(); - - static void SynchronizeTransformFunc(SG_IObject* node, void* gameobj, void* scene); - - /** - * Function to set IPO option at start of IPO - */ - void - InitIPO( - bool ipo_as_force, - bool ipo_add, - bool ipo_local - ); - - /** - * Odd function to update an ipo. ??? - */ - void - UpdateIPO( - float curframetime, - bool recurse - ); - /** - * Updates Material Ipo data - */ - void - UpdateMaterialData( - dword matname_hash, - MT_Vector4 rgba, - MT_Vector3 specrgb, - MT_Scalar hard, - MT_Scalar spec, - MT_Scalar ref, - MT_Scalar emit, - MT_Scalar alpha - ); - - /** - * \section Mesh accessor functions. - */ - - /** - * Update buckets to indicate that there is a new - * user of this object's meshes. - */ - void - AddMeshUser( - ); - - /** - * Update buckets with data about the mesh after - * creating or duplicating the object, changing - * visibility, object color, .. . - */ - void - UpdateBuckets( - bool recursive - ); - - /** - * Clear the meshes associated with this class - * and remove from the bucketing system. - * Don't think this actually deletes any of the meshes. - */ - void - RemoveMeshes( - ); - - /** - * Add a mesh to the set of meshes associated with this - * node. Meshes added in this way are not deleted by this class. - * Make sure you call RemoveMeshes() before deleting the - * mesh though, - */ - void - AddMesh( - RAS_MeshObject* mesh - ) { - m_meshes.push_back(mesh); - } - - /** - * Add a level of detail mesh to the object. These should - * be added in order. - */ - void - AddLodMesh( - RAS_MeshObject* mesh - ); - - /** - * Updates the current lod level based on distance from camera. - */ - void - UpdateLod( - MT_Vector3 &cam_pos - ); - - /** - * Pick out a mesh associated with the integer 'num'. - */ - RAS_MeshObject* - GetMesh( - int num - ) const { - return m_meshes[num]; - } - - /** - * Return the number of meshes currently associated with this - * game object. - */ - int - GetMeshCount( - ) const { - return m_meshes.size(); - } - - /** - * Set the debug color of the meshes associated with this - * class. Does this still work? - */ - void - SetDebugColor( - unsigned int bgra - ); - - /** - * Reset the debug color of meshes associated with this class. - */ - void - ResetDebugColor( - ); - - /** - * Was this object marked visible? (only for the explicit - * visibility system). - */ - bool - GetVisible( - void - ); - - /** - * Set visibility flag of this object - */ - void - SetVisible( - bool b, - bool recursive - ); - - /** - * Was this object culled? - */ - inline bool - GetCulled( - void - ) { return m_bCulled; } - - /** - * Set culled flag of this object - */ - inline void - SetCulled( - bool c - ) { m_bCulled = c; } - - /** - * Is this object an occluder? - */ - inline bool - GetOccluder( - void - ) { return m_bOccluder; } - - /** - * Set occluder flag of this object - */ - void - SetOccluder( - bool v, - bool recursive - ); - - /** - * Change the layer of the object (when it is added in another layer - * than the original layer) - */ - virtual void - SetLayer( - int l - ); - - /** - * Get the object layer - */ - int - GetLayer( - void - ); - - /** - * Get the negative scaling state - */ - bool - IsNegativeScaling( - void - ) { return m_bIsNegativeScaling; } - - /** - * \section Logic bubbling methods. - */ - - void RegisterCollisionCallbacks(); - void UnregisterCollisionCallbacks(); - void RunCollisionCallbacks(KX_GameObject *collider, const MT_Vector3 &point, const MT_Vector3 &normal); - /** - * Stop making progress - */ - void Suspend(void); - - /** - * Resume making progress - */ - void Resume(void); - - void RegisterObstacle(KX_ObstacleSimulation* obstacleSimulation) - { - m_pObstacleSimulation = obstacleSimulation; - } - - void UnregisterObstacle() - { - m_pObstacleSimulation = NULL; - } - - /** - * add debug object to the debuglist. - */ - void SetUseDebugProperties(bool debug, bool recursive); - - KX_ClientObjectInfo* getClientInfo() { return m_pClient_info; } - - CListValue* GetChildren(); - CListValue* GetChildrenRecursive(); - - KX_Scene* GetScene(); - -#ifdef WITH_PYTHON - /** - * \section Python interface functions. - */ - virtual PyObject *py_repr(void) - { - return PyUnicode_From_STR_String(GetName()); - } - - KX_PYMETHOD_O(KX_GameObject,SetWorldPosition); - KX_PYMETHOD_VARARGS(KX_GameObject, ApplyForce); - KX_PYMETHOD_VARARGS(KX_GameObject, ApplyTorque); - KX_PYMETHOD_VARARGS(KX_GameObject, ApplyRotation); - KX_PYMETHOD_VARARGS(KX_GameObject, ApplyMovement); - KX_PYMETHOD_VARARGS(KX_GameObject,GetLinearVelocity); - KX_PYMETHOD_VARARGS(KX_GameObject,SetLinearVelocity); - KX_PYMETHOD_VARARGS(KX_GameObject,GetAngularVelocity); - KX_PYMETHOD_VARARGS(KX_GameObject,SetAngularVelocity); - KX_PYMETHOD_VARARGS(KX_GameObject,GetVelocity); - KX_PYMETHOD_VARARGS(KX_GameObject,SetDamping); - - KX_PYMETHOD_NOARGS(KX_GameObject,GetReactionForce); - - - KX_PYMETHOD_NOARGS(KX_GameObject,GetVisible); - KX_PYMETHOD_VARARGS(KX_GameObject,SetVisible); - KX_PYMETHOD_VARARGS(KX_GameObject,SetOcclusion); - KX_PYMETHOD_NOARGS(KX_GameObject,GetState); - KX_PYMETHOD_O(KX_GameObject,SetState); - KX_PYMETHOD_VARARGS(KX_GameObject,AlignAxisToVect); - KX_PYMETHOD_O(KX_GameObject,GetAxisVect); - KX_PYMETHOD_VARARGS(KX_GameObject,SuspendDynamics); - KX_PYMETHOD_NOARGS(KX_GameObject,RestoreDynamics); - KX_PYMETHOD_NOARGS(KX_GameObject,EnableRigidBody); - KX_PYMETHOD_NOARGS(KX_GameObject,DisableRigidBody); - KX_PYMETHOD_VARARGS(KX_GameObject,ApplyImpulse); - KX_PYMETHOD_O(KX_GameObject,SetCollisionMargin); - KX_PYMETHOD_NOARGS(KX_GameObject,GetParent); - KX_PYMETHOD_VARARGS(KX_GameObject,SetParent); - KX_PYMETHOD_NOARGS(KX_GameObject,RemoveParent); - KX_PYMETHOD_NOARGS(KX_GameObject,GetChildren); - KX_PYMETHOD_NOARGS(KX_GameObject,GetChildrenRecursive); - KX_PYMETHOD_VARARGS(KX_GameObject,GetMesh); - KX_PYMETHOD_NOARGS(KX_GameObject,GetPhysicsId); - KX_PYMETHOD_NOARGS(KX_GameObject,GetPropertyNames); - KX_PYMETHOD_VARARGS(KX_GameObject,ReplaceMesh); - KX_PYMETHOD_NOARGS(KX_GameObject,EndObject); - KX_PYMETHOD_DOC(KX_GameObject,rayCastTo); - KX_PYMETHOD_DOC(KX_GameObject,rayCast); - KX_PYMETHOD_DOC_O(KX_GameObject,getDistanceTo); - KX_PYMETHOD_DOC_O(KX_GameObject,getVectTo); - KX_PYMETHOD_DOC_VARARGS(KX_GameObject, sendMessage); - KX_PYMETHOD_VARARGS(KX_GameObject, ReinstancePhysicsMesh); - KX_PYMETHOD_DOC(KX_GameObject, addDebugProperty); - - KX_PYMETHOD_DOC(KX_GameObject, playAction); - KX_PYMETHOD_DOC(KX_GameObject, stopAction); - KX_PYMETHOD_DOC(KX_GameObject, getActionFrame); - KX_PYMETHOD_DOC(KX_GameObject, getActionName); - KX_PYMETHOD_DOC(KX_GameObject, setActionFrame); - KX_PYMETHOD_DOC(KX_GameObject, isPlayingAction); - - /* Dict access */ - KX_PYMETHOD_VARARGS(KX_GameObject,get); - - /* attributes */ - static PyObject* pyattr_get_name(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_parent(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - - static PyObject* pyattr_get_group_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_group_members(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_scene(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - - static PyObject* pyattr_get_life(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_is_suspend_dynamics(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_ang_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_ang_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_ang_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_ang_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_record_animation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_record_animation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_localInertia(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_localInertia(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_worldScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_worldScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_localTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_localTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_worldTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_worldTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_worldLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_worldLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_localLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_localLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_worldAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_worldAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_meshes(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_children(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_children_recursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_attrDict(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_obcolor(void *selv_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_obcolor(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_collisionCallbacks(void *selv_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_collisionCallbacks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_collisionGroup(void *selv_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_collisionGroup(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_collisionMask(void *selv_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_collisionMask(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_debug(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_debug(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_debugRecursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_debugRecursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_linearDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_linearDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_angularDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_angularDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - - /* Experimental! */ - static PyObject* pyattr_get_sensors(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_controllers(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_actuators(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - - /* getitem/setitem */ - static PyMappingMethods Mapping; - static PySequenceMethods Sequence; -#endif -}; - - - -#endif /* __KX_GAMEOBJECT_H__ */ diff --git a/source/gameengine/Ketsji/KX_IInterpolator.h b/source/gameengine/Ketsji/KX_IInterpolator.h deleted file mode 100644 index 6c0bf2d85cc..00000000000 --- a/source/gameengine/Ketsji/KX_IInterpolator.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_IInterpolator.h - * \ingroup ketsji - */ - -#ifndef __KX_IINTERPOLATOR_H__ -#define __KX_IINTERPOLATOR_H__ - -#include - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -class KX_IInterpolator { -public: - virtual ~KX_IInterpolator() {} - - virtual void Execute(float currentTime) const = 0; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_IInterpolator") -#endif -}; - -typedef std::vector T_InterpolatorList; - -#endif - diff --git a/source/gameengine/Ketsji/KX_IPOTransform.h b/source/gameengine/Ketsji/KX_IPOTransform.h deleted file mode 100644 index a81c432b01e..00000000000 --- a/source/gameengine/Ketsji/KX_IPOTransform.h +++ /dev/null @@ -1,87 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_IPOTransform.h - * \ingroup ketsji - * \brief An abstract object you can move around in a 3d world, and has some logic - */ - -#ifndef __KX_IPOTRANSFORM_H__ -#define __KX_IPOTRANSFORM_H__ - -#include "MT_Transform.h" - -class KX_IPOTransform { -public: - KX_IPOTransform() : - m_position(0.0f, 0.0f, 0.0f), - m_eulerAngles(0.0f, 0.0f, 0.0f), - m_scaling(1.0f, 1.0f, 1.0f), - m_deltaPosition(0.0f, 0.0f, 0.0f), - m_deltaEulerAngles(0.0f, 0.0f, 0.0f), - m_deltaScaling(0.0f, 0.0f, 0.0f) - {} - - MT_Transform GetTransform() const { - return MT_Transform(m_position + m_deltaPosition, - MT_Matrix3x3(m_eulerAngles + m_deltaEulerAngles, - m_scaling + m_deltaScaling)); - } - - MT_Point3& GetPosition() { return m_position; } - MT_Vector3& GetEulerAngles() { return m_eulerAngles; } - MT_Vector3& GetScaling() { return m_scaling; } - - const MT_Point3& GetPosition() const { return m_position; } - const MT_Vector3& GetEulerAngles() const { return m_eulerAngles; } - const MT_Vector3& GetScaling() const { return m_scaling; } - - MT_Vector3& GetDeltaPosition() { return m_deltaPosition; } - MT_Vector3& GetDeltaEulerAngles() { return m_deltaEulerAngles; } - MT_Vector3& GetDeltaScaling() { return m_deltaScaling; } - - void SetPosition(const MT_Point3& pos) { m_position = pos; } - void SetEulerAngles(const MT_Vector3& eul) { m_eulerAngles = eul; } - void SetScaling(const MT_Vector3& scaling) { m_scaling = scaling; } - - void ClearDeltaStuff() { - m_deltaPosition.setValue(0.0f, 0.0f, 0.0f); - m_deltaEulerAngles.setValue(0.0f, 0.0f, 0.0f); - m_deltaScaling.setValue(0.0f, 0.0f, 0.0f); - } - -protected: - MT_Point3 m_position; - MT_Vector3 m_eulerAngles; - MT_Vector3 m_scaling; - MT_Vector3 m_deltaPosition; - MT_Vector3 m_deltaEulerAngles; - MT_Vector3 m_deltaScaling; -}; - -#endif - diff --git a/source/gameengine/Ketsji/KX_IPO_SGController.cpp b/source/gameengine/Ketsji/KX_IPO_SGController.cpp deleted file mode 100644 index be1a4b4ef3a..00000000000 --- a/source/gameengine/Ketsji/KX_IPO_SGController.cpp +++ /dev/null @@ -1,373 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - * Scenegraph controller for ipos. - */ - -/** \file gameengine/Ketsji/KX_IPO_SGController.cpp - * \ingroup ketsji - */ - - -#if defined(_WIN64) -typedef unsigned __int64 uint_ptr; -#else -typedef unsigned long uint_ptr; -#endif - -#ifdef _MSC_VER - /* This warning tells us about truncation of __long__ stl-generated names. - * It can occasionally cause DevStudio to have internal compiler warnings. */ -# pragma warning(disable:4786) -#endif - -#include "KX_IPO_SGController.h" -#include "KX_ScalarInterpolator.h" -#include "KX_GameObject.h" -#include "PHY_IPhysicsController.h" -#include "DNA_ipo_types.h" -#include "BLI_math.h" - -// All objects should start on frame 1! Will we ever need an object to -// start on another frame, the 1.0 should change. -KX_IpoSGController::KX_IpoSGController() -: m_ipo_as_force(false), - m_ipo_add(false), - m_ipo_local(false), - m_modified(true), - m_ipotime(1.0), - m_ipo_start_initialized(false), - m_ipo_start_euler(0.0f, 0.0f, 0.0f), - m_ipo_euler_initialized(false) -{ - m_game_object = NULL; - for (int i = 0; i < KX_MAX_IPO_CHANNELS; i++) - m_ipo_channels_active[i] = false; -} - - -void KX_IpoSGController::SetOption(int option, int value) -{ - switch (option) { - case SG_CONTR_IPO_IPO_AS_FORCE: - m_ipo_as_force = (value != 0); - m_modified = true; - break; - case SG_CONTR_IPO_IPO_ADD: - m_ipo_add = (value != 0); - m_modified = true; - break; - case SG_CONTR_IPO_RESET: - if (m_ipo_start_initialized && value) { - m_ipo_start_initialized = false; - m_modified = true; - } - break; - case SG_CONTR_IPO_LOCAL: - if (value/* && ((SG_Node*)m_pObject)->GetSGParent() == NULL*/) { - // only accept local Ipo if the object has no parent - m_ipo_local = true; - } - else { - m_ipo_local = false; - } - m_modified = true; - break; - default: - ; /* just ignore the rest */ - } -} - -void KX_IpoSGController::UpdateSumoReference() -{ - if (m_game_object) { - } -} - -void KX_IpoSGController::SetGameObject(KX_GameObject *go) -{ - m_game_object = go; -} - -bool KX_IpoSGController::Update(double currentTime) -{ - if (m_modified) { - T_InterpolatorList::iterator i; - for (i = m_interpolators.begin(); i != m_interpolators.end(); ++i) { - (*i)->Execute(m_ipotime);//currentTime); - } - - SG_Spatial *ob = (SG_Spatial *)m_pObject; - - //initialization on the first frame of the IPO - if (!m_ipo_start_initialized) { - m_ipo_start_point = ob->GetLocalPosition(); - m_ipo_start_orient = ob->GetLocalOrientation(); - m_ipo_start_scale = ob->GetLocalScale(); - m_ipo_start_initialized = true; - if (!m_ipo_euler_initialized) { - // do it only once to avoid angle discontinuities - m_ipo_start_orient.getEuler(m_ipo_start_euler[0], m_ipo_start_euler[1], m_ipo_start_euler[2]); - m_ipo_euler_initialized = true; - } - } - - //modifies position? - if (m_ipo_channels_active[OB_LOC_X] || m_ipo_channels_active[OB_LOC_Y] || m_ipo_channels_active[OB_LOC_Z] || - m_ipo_channels_active[OB_DLOC_X] || m_ipo_channels_active[OB_DLOC_Y] || m_ipo_channels_active[OB_DLOC_Z]) - { - if (m_ipo_as_force == true) { - if (m_game_object && ob && m_game_object->GetPhysicsController()) { - MT_Vector3 vec = m_ipo_local ? - ob->GetWorldOrientation() * m_ipo_xform.GetPosition() : - m_ipo_xform.GetPosition(); - m_game_object->GetPhysicsController()->ApplyForce(vec, false); - } - } - else { - // Local ipo should be defined with the object position at (0,0,0) - // Local transform is applied to the object based on initial position - MT_Point3 newPosition(0.0f, 0.0f, 0.0f); - - if (!m_ipo_add) - newPosition = ob->GetLocalPosition(); - //apply separate IPO channels if there is any data in them - //Loc and dLoc act by themselves or are additive - //LocX and dLocX - if (m_ipo_channels_active[OB_LOC_X]) { - newPosition[0] = (m_ipo_channels_active[OB_DLOC_X] ? m_ipo_xform.GetPosition()[0] + m_ipo_xform.GetDeltaPosition()[0] : m_ipo_xform.GetPosition()[0]); - } - else if (m_ipo_channels_active[OB_DLOC_X] && m_ipo_start_initialized) { - newPosition[0] = (((!m_ipo_add) ? m_ipo_start_point[0] : 0.0f) + m_ipo_xform.GetDeltaPosition()[0]); - } - //LocY and dLocY - if (m_ipo_channels_active[OB_LOC_Y]) { - newPosition[1] = (m_ipo_channels_active[OB_DLOC_Y] ? m_ipo_xform.GetPosition()[1] + m_ipo_xform.GetDeltaPosition()[1] : m_ipo_xform.GetPosition()[1]); - } - else if (m_ipo_channels_active[OB_DLOC_Y] && m_ipo_start_initialized) { - newPosition[1] = (((!m_ipo_add) ? m_ipo_start_point[1] : 0.0f) + m_ipo_xform.GetDeltaPosition()[1]); - } - //LocZ and dLocZ - if (m_ipo_channels_active[OB_LOC_Z]) { - newPosition[2] = (m_ipo_channels_active[OB_DLOC_Z] ? m_ipo_xform.GetPosition()[2] + m_ipo_xform.GetDeltaPosition()[2] : m_ipo_xform.GetPosition()[2]); - } - else if (m_ipo_channels_active[OB_DLOC_Z] && m_ipo_start_initialized) { - newPosition[2] = (((!m_ipo_add) ? m_ipo_start_point[2] : 0.0f) + m_ipo_xform.GetDeltaPosition()[2]); - } - if (m_ipo_add) { - if (m_ipo_local) - newPosition = m_ipo_start_point + m_ipo_start_scale*(m_ipo_start_orient*newPosition); - else - newPosition = m_ipo_start_point + newPosition; - } - if (m_game_object) - m_game_object->NodeSetLocalPosition(newPosition); - } - } - //modifies orientation? - if (m_ipo_channels_active[OB_ROT_X] || m_ipo_channels_active[OB_ROT_Y] || m_ipo_channels_active[OB_ROT_Z] || - m_ipo_channels_active[OB_DROT_X] || m_ipo_channels_active[OB_DROT_Y] || m_ipo_channels_active[OB_DROT_Z]) - { - if (m_ipo_as_force) { - if (m_game_object && ob) { - m_game_object->ApplyTorque(m_ipo_local ? - ob->GetWorldOrientation() * m_ipo_xform.GetEulerAngles() : - m_ipo_xform.GetEulerAngles(), false); - } - } - else if (m_ipo_add) { - if (m_ipo_start_initialized) { - double yaw = 0.0, pitch = 0.0, roll = 0.0; //delta Euler angles - - //RotX and dRotX - if (m_ipo_channels_active[OB_ROT_X]) - yaw += m_ipo_xform.GetEulerAngles()[0]; - if (m_ipo_channels_active[OB_DROT_X]) - yaw += m_ipo_xform.GetDeltaEulerAngles()[0]; - - //RotY dRotY - if (m_ipo_channels_active[OB_ROT_Y]) - pitch += m_ipo_xform.GetEulerAngles()[1]; - if (m_ipo_channels_active[OB_DROT_Y]) - pitch += m_ipo_xform.GetDeltaEulerAngles()[1]; - - //RotZ and dRotZ - if (m_ipo_channels_active[OB_ROT_Z]) - roll += m_ipo_xform.GetEulerAngles()[2]; - if (m_ipo_channels_active[OB_DROT_Z]) - roll += m_ipo_xform.GetDeltaEulerAngles()[2]; - - MT_Matrix3x3 rotation(MT_Vector3(yaw, pitch, roll)); - if (m_ipo_local) - rotation = m_ipo_start_orient * rotation; - else - rotation = rotation * m_ipo_start_orient; - if (m_game_object) - m_game_object->NodeSetLocalOrientation(rotation); - } - } - else if (m_ipo_channels_active[OB_ROT_X] || m_ipo_channels_active[OB_ROT_Y] || m_ipo_channels_active[OB_ROT_Z]) { - if (m_ipo_euler_initialized) { - // assume all channel absolute - // All 3 channels should be specified but if they are not, we will take - // the value at the start of the game to avoid angle sign reversal - double yaw = m_ipo_start_euler[0], pitch = m_ipo_start_euler[1], roll = m_ipo_start_euler[2]; - - //RotX and dRotX - if (m_ipo_channels_active[OB_ROT_X]) { - yaw = (m_ipo_channels_active[OB_DROT_X] ? (m_ipo_xform.GetEulerAngles()[0] + m_ipo_xform.GetDeltaEulerAngles()[0]) : m_ipo_xform.GetEulerAngles()[0] ); - } - else if (m_ipo_channels_active[OB_DROT_X]) { - yaw += m_ipo_xform.GetDeltaEulerAngles()[0]; - } - - //RotY dRotY - if (m_ipo_channels_active[OB_ROT_Y]) { - pitch = (m_ipo_channels_active[OB_DROT_Y] ? (m_ipo_xform.GetEulerAngles()[1] + m_ipo_xform.GetDeltaEulerAngles()[1]) : m_ipo_xform.GetEulerAngles()[1] ); - } - else if (m_ipo_channels_active[OB_DROT_Y]) { - pitch += m_ipo_xform.GetDeltaEulerAngles()[1]; - } - - //RotZ and dRotZ - if (m_ipo_channels_active[OB_ROT_Z]) { - roll = (m_ipo_channels_active[OB_DROT_Z] ? (m_ipo_xform.GetEulerAngles()[2] + m_ipo_xform.GetDeltaEulerAngles()[2]) : m_ipo_xform.GetEulerAngles()[2] ); - } - else if (m_ipo_channels_active[OB_DROT_Z]) { - roll += m_ipo_xform.GetDeltaEulerAngles()[2]; - } - if (m_game_object) - m_game_object->NodeSetLocalOrientation(MT_Vector3(yaw, pitch, roll)); - } - } - else if (m_ipo_start_initialized) { - // only DROT, treat as Add - double yaw = 0.0, pitch = 0.0, roll = 0.0; //delta Euler angles - - //dRotX - if (m_ipo_channels_active[OB_DROT_X]) - yaw = m_ipo_xform.GetDeltaEulerAngles()[0]; - - //dRotY - if (m_ipo_channels_active[OB_DROT_Y]) - pitch = m_ipo_xform.GetDeltaEulerAngles()[1]; - - //dRotZ - if (m_ipo_channels_active[OB_DROT_Z]) - roll = m_ipo_xform.GetDeltaEulerAngles()[2]; - - // dRot are always local - MT_Matrix3x3 rotation(MT_Vector3(yaw, pitch, roll)); - rotation = m_ipo_start_orient * rotation; - if (m_game_object) - m_game_object->NodeSetLocalOrientation(rotation); - } - } - //modifies scale? - if (m_ipo_channels_active[OB_SIZE_X] || m_ipo_channels_active[OB_SIZE_Y] || m_ipo_channels_active[OB_SIZE_Z] || - m_ipo_channels_active[OB_DSIZE_X] || m_ipo_channels_active[OB_DSIZE_Y] || m_ipo_channels_active[OB_DSIZE_Z]) - { - //default is no scale change - MT_Vector3 newScale(1.0f, 1.0f, 1.0f); - if (!m_ipo_add) - newScale = ob->GetLocalScale(); - - if (m_ipo_channels_active[OB_SIZE_X]) { - newScale[0] = (m_ipo_channels_active[OB_DSIZE_X] ? (m_ipo_xform.GetScaling()[0] + m_ipo_xform.GetDeltaScaling()[0]) : m_ipo_xform.GetScaling()[0]); - } - else if (m_ipo_channels_active[OB_DSIZE_X] && m_ipo_start_initialized) { - newScale[0] = (m_ipo_xform.GetDeltaScaling()[0] + ((!m_ipo_add) ? m_ipo_start_scale[0] : 0.0f)); - } - - //RotY dRotY - if (m_ipo_channels_active[OB_SIZE_Y]) { - newScale[1] = (m_ipo_channels_active[OB_DSIZE_Y] ? (m_ipo_xform.GetScaling()[1] + m_ipo_xform.GetDeltaScaling()[1]): m_ipo_xform.GetScaling()[1]); - } - else if (m_ipo_channels_active[OB_DSIZE_Y] && m_ipo_start_initialized) { - newScale[1] = (m_ipo_xform.GetDeltaScaling()[1] + ((!m_ipo_add)?m_ipo_start_scale[1] : 0.0f)); - } - - //RotZ and dRotZ - if (m_ipo_channels_active[OB_SIZE_Z]) { - newScale[2] = (m_ipo_channels_active[OB_DSIZE_Z] ? (m_ipo_xform.GetScaling()[2] + m_ipo_xform.GetDeltaScaling()[2]) : m_ipo_xform.GetScaling()[2]); - } - else if (m_ipo_channels_active[OB_DSIZE_Z] && m_ipo_start_initialized) { - newScale[2] = (m_ipo_xform.GetDeltaScaling()[2] + ((!m_ipo_add)?m_ipo_start_scale[2] : 1.0f)); - } - - if (m_ipo_add) { - newScale = m_ipo_start_scale * newScale; - } - if (m_game_object) - m_game_object->NodeSetLocalScale(newScale); - } - m_modified = false; - } - return false; -} - -void KX_IpoSGController::AddInterpolator(KX_IInterpolator *interp) -{ - m_interpolators.push_back(interp); -} - -SG_Controller *KX_IpoSGController::GetReplica(SG_Node *destnode) -{ - KX_IpoSGController *iporeplica = new KX_IpoSGController(*this); - // clear object that ipo acts on in the replica. - iporeplica->ClearObject(); - iporeplica->SetGameObject((KX_GameObject *)destnode->GetSGClientObject()); - - // dirty hack, ask Gino for a better solution in the ipo implementation - // hacken en zagen, in what we call datahiding, not written for replication :( - - T_InterpolatorList oldlist = m_interpolators; - iporeplica->m_interpolators.clear(); - - T_InterpolatorList::iterator i; - for (i = oldlist.begin(); i != oldlist.end(); ++i) { - KX_ScalarInterpolator *copyipo = new KX_ScalarInterpolator(*((KX_ScalarInterpolator *)*i)); - iporeplica->AddInterpolator(copyipo); - - MT_Scalar *scaal = ((KX_ScalarInterpolator *)*i)->GetTarget(); - uint_ptr orgbase = (uint_ptr)&m_ipo_xform; - uint_ptr orgloc = (uint_ptr)scaal; - uint_ptr offset = orgloc - orgbase; - uint_ptr newaddrbase = (uint_ptr)&iporeplica->m_ipo_xform; - newaddrbase += offset; - MT_Scalar *blaptr = (MT_Scalar *) newaddrbase; - copyipo->SetNewTarget((MT_Scalar *)blaptr); - } - - return iporeplica; -} - -KX_IpoSGController::~KX_IpoSGController() -{ - T_InterpolatorList::iterator i; - for (i = m_interpolators.begin(); i != m_interpolators.end(); ++i) { - delete (*i); - } -} diff --git a/source/gameengine/Ketsji/KX_IPO_SGController.h b/source/gameengine/Ketsji/KX_IPO_SGController.h deleted file mode 100644 index 3318761bb88..00000000000 --- a/source/gameengine/Ketsji/KX_IPO_SGController.h +++ /dev/null @@ -1,124 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_IPO_SGController.h - * \ingroup ketsji - */ - -#ifndef __KX_IPO_SGCONTROLLER_H__ -#define __KX_IPO_SGCONTROLLER_H__ - -#include "SG_Controller.h" -#include "SG_Spatial.h" - -#include "KX_IPOTransform.h" -#include "KX_IInterpolator.h" - -#define KX_MAX_IPO_CHANNELS 19 //note- [0] is not used - -class KX_IpoSGController : public SG_Controller -{ - KX_IPOTransform m_ipo_xform; - T_InterpolatorList m_interpolators; - - /** Flag for each IPO channel that can be applied to a game object */ - bool m_ipo_channels_active[KX_MAX_IPO_CHANNELS]; - - /** Interpret the ipo as a force rather than a displacement? */ - bool m_ipo_as_force; - - /** Add Ipo curve to current loc/rot/scale */ - bool m_ipo_add; - - /** Ipo must be applied in local coordinate rather than in global coordinates (used for force and Add mode)*/ - bool m_ipo_local; - - /** Were settings altered since the last update? */ - bool m_modified; - - /** Local time of this ipo.*/ - double m_ipotime; - - /** Location of the object when the IPO is first fired (for local transformations) */ - MT_Point3 m_ipo_start_point; - - /** Orientation of the object when the IPO is first fired (for local transformations) */ - MT_Matrix3x3 m_ipo_start_orient; - - /** Scale of the object when the IPO is first fired (for local transformations) */ - MT_Vector3 m_ipo_start_scale; - - /** if IPO initial position has been set for local normal IPO */ - bool m_ipo_start_initialized; - - /** Euler angles at the start of the game, needed for incomplete ROT Ipo curves */ - MT_Vector3 m_ipo_start_euler; - - /** true is m_ipo_start_euler has been initialized */ - bool m_ipo_euler_initialized; - - /** A reference to the original game object. */ - class KX_GameObject *m_game_object; - -public: - KX_IpoSGController(); - - virtual ~KX_IpoSGController(); - - virtual SG_Controller *GetReplica(class SG_Node *destnode); - - void SetOption(int option, int value); - - /** Set sumo data. */ - void UpdateSumoReference(); - /** Set reference to the corresponding game object. */ - void SetGameObject(class KX_GameObject *go); - - void SetIPOChannelActive(int index, bool value) { - //indexes found in makesdna\DNA_ipo_types.h - m_ipo_channels_active[index] = value; - } - - KX_IPOTransform &GetIPOTransform() - { - return m_ipo_xform; - } - - void AddInterpolator(KX_IInterpolator *interp); - virtual bool Update(double time); - virtual void SetSimulatedTime(double time) - { - m_ipotime = time; - m_modified = true; - } - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_IpoSGController") -#endif -}; - -#endif /* __KX_IPO_SGCONTROLLER_H__ */ diff --git a/source/gameengine/Ketsji/KX_IScalarInterpolator.h b/source/gameengine/Ketsji/KX_IScalarInterpolator.h deleted file mode 100644 index 1e822c49c6d..00000000000 --- a/source/gameengine/Ketsji/KX_IScalarInterpolator.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_IScalarInterpolator.h - * \ingroup ketsji - */ - -#ifndef __KX_ISCALARINTERPOLATOR_H__ -#define __KX_ISCALARINTERPOLATOR_H__ - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -class KX_IScalarInterpolator { -public: - virtual ~KX_IScalarInterpolator() {} - - virtual float GetValue(float currentTime) const = 0; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_IScalarInterpolator") -#endif -}; - -#endif - diff --git a/source/gameengine/Ketsji/KX_ISceneConverter.h b/source/gameengine/Ketsji/KX_ISceneConverter.h deleted file mode 100644 index 1963fc7c48f..00000000000 --- a/source/gameengine/Ketsji/KX_ISceneConverter.h +++ /dev/null @@ -1,103 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_ISceneConverter.h - * \ingroup ketsji - */ - -#ifndef __KX_ISCENECONVERTER_H__ -#define __KX_ISCENECONVERTER_H__ - -#include "STR_String.h" -#include "EXP_Python.h" - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -struct Scene; - -class KX_ISceneConverter -{ - -public: - KX_ISceneConverter() {} - virtual ~KX_ISceneConverter () {} - - /* - * scenename: name of the scene to be converted, - * if the scenename is empty, convert the 'default' scene (whatever this means) - * destinationscene: pass an empty scene, everything goes into this - * dictobj: python dictionary (for pythoncontrollers) - */ - virtual void ConvertScene( - class KX_Scene* destinationscene, - class RAS_IRasterizer* rendertools, - class RAS_ICanvas* canvas, - bool libloading=false)=0; - - virtual void RemoveScene(class KX_Scene *scene)=0; - - // handle any pending merges from asynchronous loads - virtual void MergeAsyncLoads()=0; - virtual void FinalizeAsyncLoads() = 0; - - virtual void SetAlwaysUseExpandFraming(bool to_what) = 0; - - virtual void SetNewFileName(const STR_String& filename) = 0; - virtual bool TryAndLoadNewFile() = 0; - - virtual void ResetPhysicsObjectsAnimationIpo(bool clearIpo) = 0; - - ///this generates ipo curves for position, rotation, allowing to use game physics in animation - virtual void WritePhysicsObjectToAnimationIpo(int frameNumber) = 0; - virtual void TestHandlesPhysicsObjectToAnimationIpo() = 0; - - ///this is for reseting the position,rotation and scale of the gameobjet that is not dynamic - virtual void resetNoneDynamicObjectToIpo()=0; - - // use blender materials - virtual void SetMaterials(bool val) =0; - virtual bool GetMaterials()=0; - - // use blender glsl materials - virtual void SetGLSLMaterials(bool val) =0; - virtual bool GetGLSLMaterials()=0; - - // cache materials during conversion - virtual void SetCacheMaterials(bool val) =0; - virtual bool GetCacheMaterials()=0; - - virtual struct Scene* GetBlenderSceneForName(const STR_String& name)=0; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_ISceneConverter") -#endif -}; - -#endif /* __KX_ISCENECONVERTER_H__ */ diff --git a/source/gameengine/Ketsji/KX_ISystem.h b/source/gameengine/Ketsji/KX_ISystem.h deleted file mode 100644 index 4ba71f8d239..00000000000 --- a/source/gameengine/Ketsji/KX_ISystem.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_ISystem.h - * \ingroup ketsji - * \brief Abstract system - */ - -#ifndef __KX_ISYSTEM_H__ -#define __KX_ISYSTEM_H__ - -#include -using namespace std; - -#include "STR_String.h" - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -/** - * System Abstraction, needed only for getting some timing stuff from the host. - */ -class KX_ISystem -{ -public: - KX_ISystem() {}; - virtual ~KX_ISystem() {}; - - virtual double GetTimeInSeconds()=0; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_ISystem") -#endif -}; - -#endif - diff --git a/source/gameengine/Ketsji/KX_IpoConvert.cpp b/source/gameengine/Ketsji/KX_IpoConvert.cpp deleted file mode 100644 index 7b00760ee7b..00000000000 --- a/source/gameengine/Ketsji/KX_IpoConvert.cpp +++ /dev/null @@ -1,441 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_IpoConvert.cpp - * \ingroup bgeconv - */ - -#ifdef _MSC_VER - /* don't show stl-warnings */ -# pragma warning (disable:4786) -#endif - -#include "BKE_material.h" /* give_current_material */ - -#include "KX_GameObject.h" -#include "KX_IpoConvert.h" -#include "KX_IInterpolator.h" -#include "KX_ScalarInterpolator.h" - -#include "KX_BlenderScalarInterpolator.h" -#include "KX_BlenderSceneConverter.h" - - -/* This little block needed for linking to Blender... */ -#ifdef WIN32 -#include "BLI_winstuff.h" -#endif - -#include "DNA_object_types.h" -#include "DNA_action_types.h" -#include "DNA_anim_types.h" -#include "DNA_ipo_types.h" -#include "DNA_lamp_types.h" -#include "DNA_world_types.h" -#include "DNA_camera_types.h" -#include "DNA_material_types.h" -/* end of blender include block */ - -#include "KX_IPO_SGController.h" -#include "KX_LightIpoSGController.h" -#include "KX_CameraIpoSGController.h" -#include "KX_WorldIpoController.h" -#include "KX_ObColorIpoSGController.h" -#include "KX_MaterialIpoController.h" - -#include "SG_Node.h" - -#include "STR_HashedString.h" - -static BL_InterpolatorList *GetAdtList(struct bAction *for_act, KX_BlenderSceneConverter *converter) -{ - BL_InterpolatorList *adtList= converter->FindInterpolatorList(for_act); - - if (!adtList) { - adtList = new BL_InterpolatorList(for_act); - converter->RegisterInterpolatorList(adtList, for_act); - } - - return adtList; -} - -SG_Controller *BL_CreateIPO(struct bAction *action, KX_GameObject* gameobj, KX_BlenderSceneConverter *converter) -{ - KX_IpoSGController* ipocontr = new KX_IpoSGController(); - ipocontr->SetGameObject(gameobj); - - Object* blenderobject = gameobj->GetBlenderObject(); - - ipocontr->GetIPOTransform().SetPosition(MT_Point3(blenderobject->loc)); - ipocontr->GetIPOTransform().SetEulerAngles(MT_Vector3(blenderobject->rot)); - ipocontr->GetIPOTransform().SetScaling(MT_Vector3(blenderobject->size)); - - const char *rotmode, *drotmode; - - switch (blenderobject->rotmode) { - case ROT_MODE_AXISANGLE: - rotmode = "rotation_axis_angle"; - drotmode = "delta_rotation_axis_angle"; - break; - case ROT_MODE_QUAT: /* XXX, this isn't working, currently only eulers are supported [#28853] */ - rotmode = "rotation_quaternion"; - drotmode = "delta_rotation_quaternion"; - break; - default: - rotmode = "rotation_euler"; - drotmode = "delta_rotation_euler"; - break; - } - - BL_InterpolatorList *adtList= GetAdtList(action, converter); - - // For each active channel in the adtList add an - // interpolator to the game object. - - KX_IInterpolator *interpolator; - KX_IScalarInterpolator *interp; - - for (int i=0; i<3; i++) { - if ((interp = adtList->GetScalarInterpolator("location", i))) { - interpolator= new KX_ScalarInterpolator(&(ipocontr->GetIPOTransform().GetPosition()[i]), interp); - ipocontr->AddInterpolator(interpolator); - ipocontr->SetIPOChannelActive(OB_LOC_X+i, true); - } - } - for (int i=0; i<3; i++) { - if ((interp = adtList->GetScalarInterpolator("delta_location", i))) { - interpolator= new KX_ScalarInterpolator(&(ipocontr->GetIPOTransform().GetDeltaPosition()[i]), interp); - ipocontr->AddInterpolator(interpolator); - ipocontr->SetIPOChannelActive(OB_DLOC_X+i, true); - } - } - for (int i=0; i<3; i++) { - if ((interp = adtList->GetScalarInterpolator(rotmode, i))) { - interpolator= new KX_ScalarInterpolator(&(ipocontr->GetIPOTransform().GetEulerAngles()[i]), interp); - ipocontr->AddInterpolator(interpolator); - ipocontr->SetIPOChannelActive(OB_ROT_X+i, true); - } - } - for (int i=0; i<3; i++) { - if ((interp = adtList->GetScalarInterpolator(drotmode, i))) { - interpolator= new KX_ScalarInterpolator(&(ipocontr->GetIPOTransform().GetDeltaEulerAngles()[i]), interp); - ipocontr->AddInterpolator(interpolator); - ipocontr->SetIPOChannelActive(OB_DROT_X+i, true); - } - } - for (int i=0; i<3; i++) { - if ((interp = adtList->GetScalarInterpolator("scale", i))) { - interpolator= new KX_ScalarInterpolator(&(ipocontr->GetIPOTransform().GetScaling()[i]), interp); - ipocontr->AddInterpolator(interpolator); - ipocontr->SetIPOChannelActive(OB_SIZE_X+i, true); - } - } - for (int i=0; i<3; i++) { - if ((interp = adtList->GetScalarInterpolator("delta_scale", i))) { - interpolator= new KX_ScalarInterpolator(&(ipocontr->GetIPOTransform().GetDeltaScaling()[i]), interp); - ipocontr->AddInterpolator(interpolator); - ipocontr->SetIPOChannelActive(OB_DSIZE_X+i, true); - } - } - - - return ipocontr; -} - - -SG_Controller *BL_CreateObColorIPO(struct bAction *action, KX_GameObject* gameobj, KX_BlenderSceneConverter *converter) -{ - KX_ObColorIpoSGController* ipocontr_obcol=NULL; - KX_IInterpolator *interpolator; - KX_IScalarInterpolator *interp; - BL_InterpolatorList *adtList= GetAdtList(action, converter); - - for (int i=0; i<4; i++) { - if ((interp = adtList->GetScalarInterpolator("color", i))) { - if (!ipocontr_obcol) { - ipocontr_obcol = new KX_ObColorIpoSGController(); - } - interpolator= new KX_ScalarInterpolator(&ipocontr_obcol->m_rgba[i], interp); - ipocontr_obcol->AddInterpolator(interpolator); - } - } - - return ipocontr_obcol; -} - -SG_Controller *BL_CreateLampIPO(struct bAction *action, KX_GameObject* lightobj, KX_BlenderSceneConverter *converter) -{ - KX_LightIpoSGController* ipocontr = new KX_LightIpoSGController(); - - Lamp *blenderlamp = (Lamp*)lightobj->GetBlenderObject()->data; - - ipocontr->m_energy = blenderlamp->energy; - ipocontr->m_col_rgb[0] = blenderlamp->r; - ipocontr->m_col_rgb[1] = blenderlamp->g; - ipocontr->m_col_rgb[2] = blenderlamp->b; - ipocontr->m_dist = blenderlamp->dist; - - BL_InterpolatorList *adtList= GetAdtList(action, converter); - - // For each active channel in the adtList add an - // interpolator to the game object. - - KX_IInterpolator *interpolator; - KX_IScalarInterpolator *interp; - - if ((interp= adtList->GetScalarInterpolator("energy", 0))) { - interpolator= new KX_ScalarInterpolator(&ipocontr->m_energy, interp); - ipocontr->AddInterpolator(interpolator); - ipocontr->SetModifyEnergy(true); - } - - if ((interp = adtList->GetScalarInterpolator("distance", 0))) { - interpolator= new KX_ScalarInterpolator(&ipocontr->m_dist, interp); - ipocontr->AddInterpolator(interpolator); - ipocontr->SetModifyDist(true); - } - - for (int i=0; i<3; i++) { - if ((interp = adtList->GetScalarInterpolator("color", i))) { - interpolator= new KX_ScalarInterpolator(&ipocontr->m_col_rgb[i], interp); - ipocontr->AddInterpolator(interpolator); - ipocontr->SetModifyColor(true); - } - } - - return ipocontr; -} - -SG_Controller *BL_CreateCameraIPO(struct bAction *action, KX_GameObject* cameraobj, KX_BlenderSceneConverter *converter) -{ - KX_CameraIpoSGController* ipocontr = new KX_CameraIpoSGController(); - - Camera *blendercamera = (Camera*)cameraobj->GetBlenderObject()->data; - - ipocontr->m_lens = blendercamera->lens; - ipocontr->m_clipstart = blendercamera->clipsta; - ipocontr->m_clipend = blendercamera->clipend; - - BL_InterpolatorList *adtList= GetAdtList(action, converter); - - // For each active channel in the adtList add an - // interpolator to the game object. - - KX_IInterpolator *interpolator; - KX_IScalarInterpolator *interp; - - if ((interp = adtList->GetScalarInterpolator("lens", 0))) { - interpolator= new KX_ScalarInterpolator(&ipocontr->m_lens, interp); - ipocontr->AddInterpolator(interpolator); - ipocontr->SetModifyLens(true); - } - - if ((interp = adtList->GetScalarInterpolator("clip_start", 0))) { - interpolator= new KX_ScalarInterpolator(&ipocontr->m_clipstart, interp); - ipocontr->AddInterpolator(interpolator); - ipocontr->SetModifyClipStart(true); - } - - if ((interp = adtList->GetScalarInterpolator("clip_end", 0))) { - interpolator= new KX_ScalarInterpolator(&ipocontr->m_clipend, interp); - ipocontr->AddInterpolator(interpolator); - ipocontr->SetModifyClipEnd(true); - } - - return ipocontr; -} - - -SG_Controller * BL_CreateWorldIPO( bAction *action, struct World *blenderworld, KX_BlenderSceneConverter *converter ) -{ - KX_WorldIpoController *ipocontr = NULL; - - if (blenderworld) { - BL_InterpolatorList *adtList = GetAdtList(action, converter); - - // For each active channel in the adtList add an interpolator to the game object. - KX_IInterpolator *interpolator; - KX_IScalarInterpolator *interp; - - for (int i=0; i<3; i++) { - if ((interp = adtList->GetScalarInterpolator("ambient_color", i))) { - if (!ipocontr) { - ipocontr = new KX_WorldIpoController(); - } - interpolator = new KX_ScalarInterpolator(&ipocontr->m_ambi_rgb[i], interp); - ipocontr->AddInterpolator(interpolator); - ipocontr->SetModifyAmbientColor(true); - } - } - - for (int i=0; i<3; i++) { - if ((interp = adtList->GetScalarInterpolator("horizon_color", i))) { - if (!ipocontr) { - ipocontr = new KX_WorldIpoController(); - } - interpolator = new KX_ScalarInterpolator(&ipocontr->m_hori_rgb[i], interp); - ipocontr->AddInterpolator(interpolator); - ipocontr->SetModifyHorizonColor(true); - } - } - - if ((interp = adtList->GetScalarInterpolator("mist_settings.start", 0))) { - if (!ipocontr) { - ipocontr = new KX_WorldIpoController(); - } - interpolator = new KX_ScalarInterpolator(&ipocontr->m_mist_start, interp); - ipocontr->AddInterpolator(interpolator); - ipocontr->SetModifyMistStart(true); - } - - if ((interp = adtList->GetScalarInterpolator("mist_settings.depth", 0))) { - if (!ipocontr) { - ipocontr = new KX_WorldIpoController(); - } - interpolator = new KX_ScalarInterpolator(&ipocontr->m_mist_dist, interp); - ipocontr->AddInterpolator(interpolator); - ipocontr->SetModifyMistDist(true); - } - - if ((interp = adtList->GetScalarInterpolator("mist_settings.intensity", 0))) { - if (!ipocontr) { - ipocontr = new KX_WorldIpoController(); - } - interpolator = new KX_ScalarInterpolator(&ipocontr->m_mist_intensity, interp); - ipocontr->AddInterpolator(interpolator); - ipocontr->SetModifyMistIntensity(true); - } - - if (ipocontr) { - ipocontr->m_mist_start = blenderworld->miststa; - ipocontr->m_mist_dist = blenderworld->mistdist; - ipocontr->m_mist_intensity = blenderworld->misi; - ipocontr->m_hori_rgb[0] = blenderworld->horr; - ipocontr->m_hori_rgb[1] = blenderworld->horg; - ipocontr->m_hori_rgb[2] = blenderworld->horb; - ipocontr->m_ambi_rgb[0] = blenderworld->ambr; - ipocontr->m_ambi_rgb[1] = blenderworld->ambg; - ipocontr->m_ambi_rgb[2] = blenderworld->ambb; - } - } - return ipocontr; -} - -SG_Controller *BL_CreateMaterialIpo( - struct bAction *action, - Material* blendermaterial, - dword matname_hash, - KX_GameObject* gameobj, - KX_BlenderSceneConverter *converter - ) -{ - KX_MaterialIpoController* ipocontr = NULL; - - BL_InterpolatorList *adtList= GetAdtList(action, converter); - KX_IInterpolator *interpolator; - KX_IScalarInterpolator *sinterp; - - // -- - for (int i=0; i<3; i++) { - if ((sinterp = adtList->GetScalarInterpolator("diffuse_color", i))) { - if (!ipocontr) { - ipocontr = new KX_MaterialIpoController(matname_hash); - } - interpolator= new KX_ScalarInterpolator(&ipocontr->m_rgba[i], sinterp); - ipocontr->AddInterpolator(interpolator); - } - } - - if ((sinterp = adtList->GetScalarInterpolator("alpha", 0))) { - if (!ipocontr) { - ipocontr = new KX_MaterialIpoController(matname_hash); - } - interpolator= new KX_ScalarInterpolator(&ipocontr->m_rgba[3], sinterp); - ipocontr->AddInterpolator(interpolator); - } - - for (int i=0; i<3; i++) { - if ((sinterp = adtList->GetScalarInterpolator("specular_color", i))) { - if (!ipocontr) { - ipocontr = new KX_MaterialIpoController(matname_hash); - } - interpolator= new KX_ScalarInterpolator(&ipocontr->m_specrgb[i], sinterp); - ipocontr->AddInterpolator(interpolator); - } - } - - if ((sinterp = adtList->GetScalarInterpolator("specular_hardness", 0))) { - if (!ipocontr) { - ipocontr = new KX_MaterialIpoController(matname_hash); - } - interpolator= new KX_ScalarInterpolator(&ipocontr->m_hard, sinterp); - ipocontr->AddInterpolator(interpolator); - } - - if ((sinterp = adtList->GetScalarInterpolator("specular_intensity", 0))) { - if (!ipocontr) { - ipocontr = new KX_MaterialIpoController(matname_hash); - } - interpolator= new KX_ScalarInterpolator(&ipocontr->m_spec, sinterp); - ipocontr->AddInterpolator(interpolator); - } - - if ((sinterp = adtList->GetScalarInterpolator("diffuse_intensity", 0))) { - if (!ipocontr) { - ipocontr = new KX_MaterialIpoController(matname_hash); - } - interpolator= new KX_ScalarInterpolator(&ipocontr->m_ref, sinterp); - ipocontr->AddInterpolator(interpolator); - } - - if ((sinterp = adtList->GetScalarInterpolator("emit", 0))) { - if (!ipocontr) { - ipocontr = new KX_MaterialIpoController(matname_hash); - } - interpolator= new KX_ScalarInterpolator(&ipocontr->m_emit, sinterp); - ipocontr->AddInterpolator(interpolator); - } - - if (ipocontr) { - ipocontr->m_rgba[0] = blendermaterial->r; - ipocontr->m_rgba[1] = blendermaterial->g; - ipocontr->m_rgba[2] = blendermaterial->b; - ipocontr->m_rgba[3] = blendermaterial->alpha; - - ipocontr->m_specrgb[0] = blendermaterial->specr; - ipocontr->m_specrgb[1] = blendermaterial->specg; - ipocontr->m_specrgb[2] = blendermaterial->specb; - - ipocontr->m_hard = blendermaterial->har; - ipocontr->m_spec = blendermaterial->spec; - ipocontr->m_ref = blendermaterial->ref; - ipocontr->m_emit = blendermaterial->emit; - ipocontr->m_alpha = blendermaterial->alpha; - } - - return ipocontr; -} diff --git a/source/gameengine/Ketsji/KX_IpoConvert.h b/source/gameengine/Ketsji/KX_IpoConvert.h deleted file mode 100644 index 6db43552811..00000000000 --- a/source/gameengine/Ketsji/KX_IpoConvert.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_IpoConvert.h - * \ingroup bgeconv - */ - -#ifndef __KX_IPOCONVERT_H__ -#define __KX_IPOCONVERT_H__ - -struct Object; -struct bAction; -class SG_Controller; -class KX_GameObject; -class KX_BlenderSceneConverter; - -SG_Controller *BL_CreateIPO(bAction *action, - KX_GameObject* gameobj, - KX_BlenderSceneConverter *converter); - -SG_Controller *BL_CreateObColorIPO(bAction *action, - KX_GameObject* gameobj, - KX_BlenderSceneConverter *converter); - -SG_Controller *BL_CreateLampIPO(bAction *action, - KX_GameObject* lightobj, - KX_BlenderSceneConverter *converter); - -SG_Controller *BL_CreateWorldIPO(bAction *action, - struct World *blenderworld, - KX_BlenderSceneConverter *converter); - -SG_Controller *BL_CreateCameraIPO(bAction *action, - KX_GameObject* cameraobj, - KX_BlenderSceneConverter *converter); - -SG_Controller *BL_CreateMaterialIpo( - bAction *action, - struct Material* blendermaterial, - dword matname_hash, - KX_GameObject* gameobj, - KX_BlenderSceneConverter *converter); - - -#endif /* __KX_IPOCONVERT_H__ */ diff --git a/source/gameengine/Ketsji/KX_KetsjiEngine.cpp b/source/gameengine/Ketsji/KX_KetsjiEngine.cpp deleted file mode 100644 index d82a0fd533b..00000000000 --- a/source/gameengine/Ketsji/KX_KetsjiEngine.cpp +++ /dev/null @@ -1,2081 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - * The engine ties all game modules together. - */ - -/** \file gameengine/Ketsji/KX_KetsjiEngine.cpp - * \ingroup ketsji - */ - -#ifdef _MSC_VER -# pragma warning (disable:4786) -#endif - -#include -#include - -#include "BLI_task.h" - -#include "KX_KetsjiEngine.h" - -#include "EXP_ListValue.h" -#include "EXP_IntValue.h" -#include "EXP_VectorValue.h" -#include "EXP_BoolValue.h" -#include "EXP_FloatValue.h" - -#include "RAS_BucketManager.h" -#include "RAS_Rect.h" -#include "RAS_IRasterizer.h" -#include "RAS_ICanvas.h" -#include "RAS_ILightObject.h" -#include "MT_Vector3.h" -#include "MT_Transform.h" -#include "SCA_IInputDevice.h" -#include "KX_Camera.h" -#include "KX_Dome.h" -#include "KX_Light.h" -#include "KX_PythonInit.h" -#include "KX_PyConstraintBinding.h" -#include "PHY_IPhysicsEnvironment.h" - -#include "NG_NetworkScene.h" -#include "NG_NetworkDeviceInterface.h" - -#include "KX_WorldInfo.h" -#include "KX_ISceneConverter.h" -#include "KX_TimeCategoryLogger.h" - -#include "RAS_FramingManager.h" -#include "DNA_world_types.h" -#include "DNA_scene_types.h" - -#include "KX_NavMeshObject.h" - -#include "BL_Action.h" // For managing action lock. - -#define DEFAULT_LOGIC_TIC_RATE 60.0 -//#define DEFAULT_PHYSICS_TIC_RATE 60.0 - -const char KX_KetsjiEngine::m_profileLabels[tc_numCategories][15] = { - "Physics:", // tc_physics - "Logic:", // tc_logic - "Animations:", // tc_animations - "Network:", // tc_network - "Scenegraph:", // tc_scenegraph - "Rasterizer:", // tc_rasterizer - "Services:", // tc_services - "Overhead:", // tc_overhead - "Outside:", // tc_outside - "GPU Latency:" // tc_latency -}; - -double KX_KetsjiEngine::m_ticrate = DEFAULT_LOGIC_TIC_RATE; -int KX_KetsjiEngine::m_maxLogicFrame = 5; -int KX_KetsjiEngine::m_maxPhysicsFrame = 5; -double KX_KetsjiEngine::m_anim_framerate = 25.0; -double KX_KetsjiEngine::m_suspendedtime = 0.0; -double KX_KetsjiEngine::m_suspendeddelta = 0.0; -double KX_KetsjiEngine::m_average_framerate = 0.0; -bool KX_KetsjiEngine::m_restrict_anim_fps = false; -short KX_KetsjiEngine::m_exitkey = 130; // ESC Key -bool KX_KetsjiEngine::m_doRender = true; - -/** - * Constructor of the Ketsji Engine - */ -KX_KetsjiEngine::KX_KetsjiEngine(KX_ISystem* system) - : m_canvas(NULL), - m_rasterizer(NULL), - m_kxsystem(system), - m_sceneconverter(NULL), - m_networkdevice(NULL), -#ifdef WITH_PYTHON - m_pythondictionary(NULL), -#endif - m_keyboarddevice(NULL), - m_mousedevice(NULL), - - m_bInitialized(false), - m_activecam(0), - m_bFixedTime(false), - m_useExternalClock(false), - - m_firstframe(true), - - m_frameTime(0.f), - m_clockTime(0.f), - m_previousClockTime(0.f), - m_previousAnimTime(0.f), - m_timescale(1.0f), - m_previousRealTime(0.0f), - - - m_exitcode(KX_EXIT_REQUEST_NO_REQUEST), - m_exitstring(""), - - m_cameraZoom(1.0f), - - m_overrideCam(false), - m_overrideCamUseOrtho(false), - m_overrideCamNear(0.0f), - m_overrideCamFar(0.0f), - m_overrideCamZoom(1.0f), - - m_stereo(false), - m_curreye(0), - - m_logger(NULL), - - // Set up timing info display variables - m_show_framerate(false), - m_show_profile(false), - m_showProperties(false), - m_showBackground(false), - m_show_debug_properties(false), - m_autoAddDebugProperties(true), - - m_animation_record(false), - - // Default behavior is to hide the cursor every frame. - m_hideCursor(false), - - m_overrideFrameColor(false), - m_overrideFrameColorR(0.0f), - m_overrideFrameColorG(0.0f), - m_overrideFrameColorB(0.0f), - m_overrideFrameColorA(0.0f), - - m_usedome(false) -{ - // Initialize the time logger - m_logger = new KX_TimeCategoryLogger (25); - - for (int i = tc_first; i < tc_numCategories; i++) - m_logger->AddCategory((KX_TimeCategory)i); - -#ifdef WITH_PYTHON - m_pyprofiledict = PyDict_New(); -#endif - - m_taskscheduler = BLI_task_scheduler_create(TASK_SCHEDULER_AUTO_THREADS); - - BL_Action::InitLock(); -} - - - -/** - * Destructor of the Ketsji Engine, release all memory - */ -KX_KetsjiEngine::~KX_KetsjiEngine() -{ - delete m_logger; - if (m_usedome) - delete m_dome; - -#ifdef WITH_PYTHON - Py_CLEAR(m_pyprofiledict); -#endif - - if (m_taskscheduler) - BLI_task_scheduler_free(m_taskscheduler); - - BL_Action::EndLock(); -} - - - -void KX_KetsjiEngine::SetKeyboardDevice(SCA_IInputDevice* keyboarddevice) -{ - MT_assert(keyboarddevice); - m_keyboarddevice = keyboarddevice; -} - - - -void KX_KetsjiEngine::SetMouseDevice(SCA_IInputDevice* mousedevice) -{ - MT_assert(mousedevice); - m_mousedevice = mousedevice; -} - - - -void KX_KetsjiEngine::SetNetworkDevice(NG_NetworkDeviceInterface* networkdevice) -{ - MT_assert(networkdevice); - m_networkdevice = networkdevice; -} - - -void KX_KetsjiEngine::SetCanvas(RAS_ICanvas* canvas) -{ - MT_assert(canvas); - m_canvas = canvas; -} - - - -void KX_KetsjiEngine::SetRasterizer(RAS_IRasterizer* rasterizer) -{ - MT_assert(rasterizer); - m_rasterizer = rasterizer; -} - -#ifdef WITH_PYTHON -/* - * At the moment the bge.logic module is imported into 'pythondictionary' after this function is called. - * if this function ever changes to assign a copy, make sure the game logic module is imported into this dictionary before hand. - */ -void KX_KetsjiEngine::SetPyNamespace(PyObject *pythondictionary) -{ - MT_assert(pythondictionary); - m_pythondictionary = pythondictionary; -} - -PyObject* KX_KetsjiEngine::GetPyProfileDict() -{ - Py_INCREF(m_pyprofiledict); - return m_pyprofiledict; -} -#endif - - -void KX_KetsjiEngine::SetSceneConverter(KX_ISceneConverter* sceneconverter) -{ - MT_assert(sceneconverter); - m_sceneconverter = sceneconverter; -} - -void KX_KetsjiEngine::InitDome(short res, short mode, short angle, float resbuf, short tilt, struct Text* text) -{ - m_dome = new KX_Dome(m_canvas, m_rasterizer,this, res, mode, angle, resbuf, tilt, text); - m_usedome = true; -} - -void KX_KetsjiEngine::RenderDome() -{ - const GLint *viewport = m_canvas->GetViewPort(); - - m_dome->SetViewPort(viewport); - - KX_Scene* firstscene = *m_scenes.begin(); - const RAS_FrameSettings &framesettings = firstscene->GetFramingType(); - - m_logger->StartLog(tc_rasterizer, m_kxsystem->GetTimeInSeconds(), true); - - // hiding mouse cursor each frame - // (came back when going out of focus and then back in again) - if (m_hideCursor) - m_canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE); - - // clear the entire game screen with the border color - // only once per frame - - m_canvas->BeginDraw(); - - // BeginFrame() sets the actual drawing area. You can use a part of the window - if (!BeginFrame()) - return; - - KX_SceneList::iterator sceneit; - KX_Scene* scene = NULL; - - int n_renders=m_dome->GetNumberRenders(); // usually 4 or 6 - for (int i=0;iClearBuffer(RAS_ICanvas::COLOR_BUFFER|RAS_ICanvas::DEPTH_BUFFER); - for (sceneit = m_scenes.begin();sceneit != m_scenes.end(); sceneit++) - // for each scene, call the proceed functions - { - scene = *sceneit; - KX_SetActiveScene(scene); - KX_Camera* cam = scene->GetActiveCamera(); - - // pass the scene's worldsettings to the rasterizer - scene->GetWorldInfo()->UpdateWorldSettings(); - - // shadow buffers - if (i == 0) { - RenderShadowBuffers(scene); - } - // Avoid drawing the scene with the active camera twice when its viewport is enabled - if (cam && !cam->GetViewport()) - { - if (scene->IsClearingZBuffer()) - m_rasterizer->ClearDepthBuffer(); - - m_rasterizer->SetAuxilaryClientInfo(scene); - - // do the rendering - m_dome->RenderDomeFrame(scene,cam, i); - // render all the font objects for this scene - scene->RenderFonts(); - } - - list* cameras = scene->GetCameras(); - - // Draw the scene once for each camera with an enabled viewport - list::iterator it = cameras->begin(); - while (it != cameras->end()) { - if ((*it)->GetViewport()) - { - if (scene->IsClearingZBuffer()) - m_rasterizer->ClearDepthBuffer(); - - m_rasterizer->SetAuxilaryClientInfo(scene); - - // do the rendering - m_dome->RenderDomeFrame(scene, (*it),i); - // render all the font objects for this scene - scene->RenderFonts(); - } - - it++; - } - // Part of PostRenderScene() - m_rasterizer->MotionBlur(); - scene->Render2DFilters(m_canvas); - // no RunDrawingCallBacks - // no FlushDebugLines - } - m_dome->BindImages(i); - } - - m_canvas->EndFrame();//XXX do we really need that? - - m_canvas->SetViewPort(0, 0, m_canvas->GetWidth(), m_canvas->GetHeight()); - - if (m_overrideFrameColor) //XXX why do we want - { - // Do not use the framing bar color set in the Blender scenes - m_canvas->ClearColor( - m_overrideFrameColorR, - m_overrideFrameColorG, - m_overrideFrameColorB, - m_overrideFrameColorA - ); - } - else - { - // Use the framing bar color set in the Blender scenes - m_canvas->ClearColor( - framesettings.BarRed(), - framesettings.BarGreen(), - framesettings.BarBlue(), - 1.0 - ); - } - m_dome->Draw(); - - // Draw Callback for the last scene -#ifdef WITH_PYTHON - PHY_SetActiveEnvironment(scene->GetPhysicsEnvironment()); - scene->RunDrawingCallbacks(scene->GetPostDrawCB()); -#endif - EndFrame(); -} - -/** - * Ketsji Init(), Initializes data-structures and converts data from - * Blender into Ketsji native (realtime) format also sets up the - * graphics context - */ -void KX_KetsjiEngine::StartEngine(bool clearIpo) -{ - m_clockTime = m_kxsystem->GetTimeInSeconds(); - m_frameTime = m_kxsystem->GetTimeInSeconds(); - m_previousClockTime = m_kxsystem->GetTimeInSeconds(); - m_previousRealTime = m_kxsystem->GetTimeInSeconds(); - - m_firstframe = true; - m_bInitialized = true; - // there is always one scene enabled at startup - Scene* scene = m_scenes[0]->GetBlenderScene(); - if (scene) - { - m_ticrate = scene->gm.ticrate ? scene->gm.ticrate : DEFAULT_LOGIC_TIC_RATE; - m_maxLogicFrame = scene->gm.maxlogicstep ? scene->gm.maxlogicstep : 5; - m_maxPhysicsFrame = scene->gm.maxphystep ? scene->gm.maxlogicstep : 5; - } - else - { - m_ticrate = DEFAULT_LOGIC_TIC_RATE; - m_maxLogicFrame = 5; - m_maxPhysicsFrame = 5; - } - - if (m_animation_record) - { - m_sceneconverter->ResetPhysicsObjectsAnimationIpo(clearIpo); - m_sceneconverter->WritePhysicsObjectToAnimationIpo(m_currentFrame); - } -} - -void KX_KetsjiEngine::ClearFrame() -{ - // clear unless we're drawing overlapping stereo - if (m_rasterizer->InterlacedStereo() && - m_rasterizer->GetEye() == RAS_IRasterizer::RAS_STEREO_RIGHTEYE) - return; - - // clear the viewports with the background color of the first scene - bool doclear = false; - KX_SceneList::iterator sceneit; - RAS_Rect clearvp, area, viewport; - - for (sceneit = m_scenes.begin(); sceneit != m_scenes.end(); sceneit++) - { - KX_Scene* scene = *sceneit; - //const RAS_FrameSettings &framesettings = scene->GetFramingType(); - list* cameras = scene->GetCameras(); - - list::iterator it; - for (it = cameras->begin(); it != cameras->end(); it++) - { - GetSceneViewport(scene, (*it), area, viewport); - - if (!doclear) { - clearvp = viewport; - doclear = true; - } - else { - if (viewport.GetLeft() < clearvp.GetLeft()) - clearvp.SetLeft(viewport.GetLeft()); - if (viewport.GetBottom() < clearvp.GetBottom()) - clearvp.SetBottom(viewport.GetBottom()); - if (viewport.GetRight() > clearvp.GetRight()) - clearvp.SetRight(viewport.GetRight()); - if (viewport.GetTop() > clearvp.GetTop()) - clearvp.SetTop(viewport.GetTop()); - - } - } - } - - if (doclear) { - KX_Scene* firstscene = *m_scenes.begin(); - firstscene->GetWorldInfo()->UpdateBackGround(); - - m_canvas->SetViewPort(clearvp.GetLeft(), clearvp.GetBottom(), - clearvp.GetRight(), clearvp.GetTop()); - m_rasterizer->ClearColorBuffer(); - } -} - -bool KX_KetsjiEngine::BeginFrame() -{ - // set the area used for rendering (stereo can assign only a subset) - m_rasterizer->SetRenderArea(); - - if (m_canvas->BeginDraw()) - { - ClearFrame(); - - m_rasterizer->BeginFrame(m_kxsystem->GetTimeInSeconds()); - - return true; - } - - return false; -} - - -void KX_KetsjiEngine::EndFrame() -{ - m_rasterizer->MotionBlur(); - - // Show profiling info - m_logger->StartLog(tc_overhead, m_kxsystem->GetTimeInSeconds(), true); - if (m_show_framerate || m_show_profile || (m_show_debug_properties)) - { - RenderDebugProperties(); - } - - double tottime = m_logger->GetAverage(); - if (tottime < 1e-6) - tottime = 1e-6; - -#ifdef WITH_PYTHON - for (int i = tc_first; i < tc_numCategories; ++i) { - double time = m_logger->GetAverage((KX_TimeCategory)i); - PyObject *val = PyTuple_New(2); - PyTuple_SetItem(val, 0, PyFloat_FromDouble(time*1000.0)); - PyTuple_SetItem(val, 1, PyFloat_FromDouble(time/tottime * 100.0)); - - PyDict_SetItemString(m_pyprofiledict, m_profileLabels[i], val); - Py_DECREF(val); - } -#endif - - m_average_framerate = 1.0/tottime; - - // Go to next profiling measurement, time spent after this call is shown in the next frame. - m_logger->NextMeasurement(m_kxsystem->GetTimeInSeconds()); - - m_logger->StartLog(tc_rasterizer, m_kxsystem->GetTimeInSeconds(), true); - m_rasterizer->EndFrame(); - // swap backbuffer (drawing into this buffer) <-> front/visible buffer - m_logger->StartLog(tc_latency, m_kxsystem->GetTimeInSeconds(), true); - m_rasterizer->SwapBuffers(); - m_logger->StartLog(tc_rasterizer, m_kxsystem->GetTimeInSeconds(), true); - - m_canvas->EndDraw(); -} - -//#include "PIL_time.h" -//#include "LinearMath/btQuickprof.h" - - -bool KX_KetsjiEngine::NextFrame() -{ - double timestep = m_timescale / m_ticrate; - double framestep = timestep; - // static hidden::Clock sClock; - - m_logger->StartLog(tc_services, m_kxsystem->GetTimeInSeconds(),true); - - //float dt = sClock.getTimeMicroseconds() * 0.000001f; - //sClock.reset(); - - /* - * Clock advancement. There is basically three case: - * - m_useExternalClock is true, the user is responsible to advance the time - * manually using setClockTime, so here, we do not do anything. - * - m_useExternalClock is false, m_bFixedTime is true, we advance for one - * timestep, which already handle the time scaling parameter - * - m_useExternalClock is false, m_bFixedTime is false, we consider how much - * time has elapsed since last call and we scale this time by the time - * scaling parameter. If m_timescale is 1.0 (default value), the clock - * corresponds to the computer clock. - * - * Once clockTime has been computed, we will compute how many logic frames - * will be executed before the next rendering phase (which will occur at "clockTime"). - * The game time elapsing between two logic frames (called framestep) - * depends on several variables: - * - ticrate - * - max_physic_frame - * - max_logic_frame - * XXX The logic over computation framestep is definitively not clear (and - * I'm not even sure it is correct). If needed frame is strictly greater - * than max_physics_frame, we are doing a jump in game time, but keeping - * framestep = 1 / ticrate, while if frames is greater than - * max_logic_frame, we increase framestep. - * - * XXX render.fps is not considred anywhere. - */ - if (!m_useExternalClock) { - if (m_bFixedTime) { - m_clockTime += timestep; - } - else { - double current_time = m_kxsystem->GetTimeInSeconds(); - double dt = current_time - m_previousRealTime; - m_previousRealTime = current_time; - // m_clockTime += dt; - m_clockTime += dt * m_timescale; - } - } - - double deltatime = m_clockTime - m_frameTime; - if (deltatime<0.0) - { - // We got here too quickly, which means there is nothing to do, just return and don't render. - // Not sure if this is the best fix, but it seems to stop the jumping framerate issue (#33088) - return false; - } - - // Compute the number of logic frames to do each update (fixed tic bricks) - int frames = int(deltatime * m_ticrate / m_timescale + 1e-6); -// if (frames>1) -// printf("****************************************"); -// printf("dt = %f, deltatime = %f, frames = %d\n",dt, deltatime,frames); - -// if (!frames) -// PIL_sleep_ms(1); - KX_SceneList::iterator sceneit; - - if (frames>m_maxPhysicsFrame) - { - - // printf("framedOut: %d\n",frames); - m_frameTime+=(frames-m_maxPhysicsFrame)*timestep; - frames = m_maxPhysicsFrame; - } - - - bool doRender = frames>0; - - if (frames > m_maxLogicFrame) - { - framestep = (frames*timestep)/m_maxLogicFrame; - frames = m_maxLogicFrame; - } - - while (frames) - { - - - m_frameTime += framestep; - - m_sceneconverter->MergeAsyncLoads(); - - for (sceneit = m_scenes.begin();sceneit != m_scenes.end(); ++sceneit) - // for each scene, call the proceed functions - { - KX_Scene* scene = *sceneit; - - /* Suspension holds the physics and logic processing for an - * entire scene. Objects can be suspended individually, and - * the settings for that precede the logic and physics - * update. */ - m_logger->StartLog(tc_logic, m_kxsystem->GetTimeInSeconds(), true); - - m_sceneconverter->resetNoneDynamicObjectToIpo(); // this is for none dynamic objects with ipo - - scene->UpdateObjectActivity(); - - if (!scene->IsSuspended()) - { - // if the scene was suspended recalculate the delta tu "curtime" - m_suspendedtime = scene->getSuspendedTime(); - if (scene->getSuspendedTime()!=0.0) - scene->setSuspendedDelta(scene->getSuspendedDelta()+m_clockTime-scene->getSuspendedTime()); - m_suspendeddelta = scene->getSuspendedDelta(); - - - m_logger->StartLog(tc_network, m_kxsystem->GetTimeInSeconds(), true); - SG_SetActiveStage(SG_STAGE_NETWORK); - scene->GetNetworkScene()->proceed(m_frameTime); - - //m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true); - //SG_SetActiveStage(SG_STAGE_NETWORK_UPDATE); - //scene->UpdateParents(m_frameTime); - - m_logger->StartLog(tc_physics, m_kxsystem->GetTimeInSeconds(), true); - SG_SetActiveStage(SG_STAGE_PHYSICS1); - // set Python hooks for each scene -#ifdef WITH_PYTHON - PHY_SetActiveEnvironment(scene->GetPhysicsEnvironment()); -#endif - KX_SetActiveScene(scene); - - scene->GetPhysicsEnvironment()->EndFrame(); - - // Update scenegraph after physics step. This maps physics calculations - // into node positions. - //m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true); - //SG_SetActiveStage(SG_STAGE_PHYSICS1_UPDATE); - //scene->UpdateParents(m_frameTime); - - // Process sensors, and controllers - m_logger->StartLog(tc_logic, m_kxsystem->GetTimeInSeconds(), true); - SG_SetActiveStage(SG_STAGE_CONTROLLER); - scene->LogicBeginFrame(m_frameTime); - - // Scenegraph needs to be updated again, because Logic Controllers - // can affect the local matrices. - m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true); - SG_SetActiveStage(SG_STAGE_CONTROLLER_UPDATE); - scene->UpdateParents(m_frameTime); - - // Process actuators - - // Do some cleanup work for this logic frame - m_logger->StartLog(tc_logic, m_kxsystem->GetTimeInSeconds(), true); - SG_SetActiveStage(SG_STAGE_ACTUATOR); - scene->LogicUpdateFrame(m_frameTime, true); - - scene->LogicEndFrame(); - - // Actuators can affect the scenegraph - m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true); - SG_SetActiveStage(SG_STAGE_ACTUATOR_UPDATE); - scene->UpdateParents(m_frameTime); - - // update levels of detail - scene->UpdateObjectLods(); - - m_logger->StartLog(tc_physics, m_kxsystem->GetTimeInSeconds(), true); - SG_SetActiveStage(SG_STAGE_PHYSICS2); - scene->GetPhysicsEnvironment()->BeginFrame(); - - // Perform physics calculations on the scene. This can involve - // many iterations of the physics solver. - scene->GetPhysicsEnvironment()->ProceedDeltaTime(m_frameTime,timestep,framestep);//m_deltatimerealDeltaTime); - - m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true); - SG_SetActiveStage(SG_STAGE_PHYSICS2_UPDATE); - scene->UpdateParents(m_frameTime); - - - if (m_animation_record) - { - m_sceneconverter->WritePhysicsObjectToAnimationIpo(++m_currentFrame); - } - - scene->setSuspendedTime(0.0); - } // suspended - else - if (scene->getSuspendedTime()==0.0) - scene->setSuspendedTime(m_clockTime); - - m_logger->StartLog(tc_services, m_kxsystem->GetTimeInSeconds(), true); - - // invalidates the shadow buffer from previous render/ImageRender because the scene has changed - scene->SetShadowDone(false); - } - - // update system devices - m_logger->StartLog(tc_logic, m_kxsystem->GetTimeInSeconds(), true); - if (m_keyboarddevice) - m_keyboarddevice->NextFrame(); - - if (m_mousedevice) - m_mousedevice->NextFrame(); - - if (m_networkdevice) - m_networkdevice->NextFrame(); - - // scene management - ProcessScheduledScenes(); - - frames--; - } - - // Start logging time spent outside main loop - m_logger->StartLog(tc_outside, m_kxsystem->GetTimeInSeconds(), true); - - return doRender && m_doRender; -} - - - -void KX_KetsjiEngine::Render() -{ - if (m_usedome) { - RenderDome(); - return; - } - KX_Scene* firstscene = *m_scenes.begin(); - const RAS_FrameSettings &framesettings = firstscene->GetFramingType(); - - m_logger->StartLog(tc_rasterizer, m_kxsystem->GetTimeInSeconds(), true); - SG_SetActiveStage(SG_STAGE_RENDER); - - // hiding mouse cursor each frame - // (came back when going out of focus and then back in again) - if (m_hideCursor) - m_canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE); - - // clear the entire game screen with the border color - // only once per frame - m_canvas->BeginDraw(); - if (m_rasterizer->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED) { - m_canvas->SetViewPort(0, 0, m_canvas->GetWidth(), m_canvas->GetHeight()); - if (m_overrideFrameColor) - { - // Do not use the framing bar color set in the Blender scenes - m_canvas->ClearColor( - m_overrideFrameColorR, - m_overrideFrameColorG, - m_overrideFrameColorB, - m_overrideFrameColorA - ); - } - else - { - // Use the framing bar color set in the Blender scenes - m_canvas->ClearColor( - framesettings.BarRed(), - framesettings.BarGreen(), - framesettings.BarBlue(), - 1.0 - ); - } - // clear the -whole- viewport - m_canvas->ClearBuffer(RAS_ICanvas::COLOR_BUFFER|RAS_ICanvas::DEPTH_BUFFER); - } - - m_rasterizer->SetEye(RAS_IRasterizer::RAS_STEREO_LEFTEYE); - - // BeginFrame() sets the actual drawing area. You can use a part of the window - if (!BeginFrame()) - return; - - KX_SceneList::iterator sceneit; - for (sceneit = m_scenes.begin();sceneit != m_scenes.end(); sceneit++) - // for each scene, call the proceed functions - { - KX_Scene* scene = *sceneit; - KX_Camera* cam = scene->GetActiveCamera(); - // pass the scene's worldsettings to the rasterizer - scene->GetWorldInfo()->UpdateWorldSettings(); - - // this is now done incrementally in KX_Scene::CalculateVisibleMeshes - //scene->UpdateMeshTransformations(); - - // shadow buffers - RenderShadowBuffers(scene); - - // Avoid drawing the scene with the active camera twice when its viewport is enabled - if (cam && !cam->GetViewport()) - { - if (scene->IsClearingZBuffer()) - m_rasterizer->ClearDepthBuffer(); - - m_rasterizer->SetAuxilaryClientInfo(scene); - - // do the rendering - RenderFrame(scene, cam); - } - - list* cameras = scene->GetCameras(); - - // Draw the scene once for each camera with an enabled viewport - list::iterator it = cameras->begin(); - while (it != cameras->end()) { - if ((*it)->GetViewport()) - { - if (scene->IsClearingZBuffer()) - m_rasterizer->ClearDepthBuffer(); - - m_rasterizer->SetAuxilaryClientInfo(scene); - - // do the rendering - RenderFrame(scene, (*it)); - } - - it++; - } - PostRenderScene(scene); - } - - // only one place that checks for stereo - if (m_rasterizer->Stereo()) - { - m_rasterizer->SetEye(RAS_IRasterizer::RAS_STEREO_RIGHTEYE); - - if (!BeginFrame()) - return; - - - for (sceneit = m_scenes.begin();sceneit != m_scenes.end(); sceneit++) - // for each scene, call the proceed functions - { - KX_Scene* scene = *sceneit; - KX_Camera* cam = scene->GetActiveCamera(); - - // pass the scene's worldsettings to the rasterizer - scene->GetWorldInfo()->UpdateWorldSettings(); - - if (scene->IsClearingZBuffer()) - m_rasterizer->ClearDepthBuffer(); - - // pass the scene, for picking and raycasting (shadows) - m_rasterizer->SetAuxilaryClientInfo(scene); - - // do the rendering - //RenderFrame(scene); - RenderFrame(scene, cam); - - list* cameras = scene->GetCameras(); - - // Draw the scene once for each camera with an enabled viewport - list::iterator it = cameras->begin(); - while (it != cameras->end()) { - if ((*it)->GetViewport()) - { - if (scene->IsClearingZBuffer()) - m_rasterizer->ClearDepthBuffer(); - - m_rasterizer->SetAuxilaryClientInfo(scene); - - // do the rendering - RenderFrame(scene, (*it)); - } - - it++; - } - PostRenderScene(scene); - } - } // if (m_rasterizer->Stereo()) - - EndFrame(); -} - - - -void KX_KetsjiEngine::RequestExit(int exitrequestmode) -{ - m_exitcode = exitrequestmode; -} - - - -void KX_KetsjiEngine::SetNameNextGame(const STR_String& nextgame) -{ - m_exitstring = nextgame; -} - - - -int KX_KetsjiEngine::GetExitCode() -{ - // if a game actuator has set an exit code or if there are no scenes left - if (!m_exitcode) - { - if (m_scenes.begin() == m_scenes.end()) - m_exitcode = KX_EXIT_REQUEST_NO_SCENES_LEFT; - } - - // check if the window has been closed. - if (!m_exitcode) - { - //if (!m_canvas->Check()) { - // m_exitcode = KX_EXIT_REQUEST_OUTSIDE; - //} - } - - return m_exitcode; -} - - - -const STR_String& KX_KetsjiEngine::GetExitString() -{ - return m_exitstring; -} - -void KX_KetsjiEngine::EnableCameraOverride(const STR_String& forscene) -{ - m_overrideCam = true; - m_overrideSceneName = forscene; -} - -void KX_KetsjiEngine::SetCameraZoom(float camzoom) -{ - m_cameraZoom = camzoom; -} - -void KX_KetsjiEngine::SetCameraOverrideUseOrtho(bool useOrtho) -{ - m_overrideCamUseOrtho = useOrtho; -} - -void KX_KetsjiEngine::SetCameraOverrideProjectionMatrix(const MT_CmMatrix4x4& mat) -{ - m_overrideCamProjMat = mat; -} - -void KX_KetsjiEngine::SetCameraOverrideViewMatrix(const MT_CmMatrix4x4& mat) -{ - m_overrideCamViewMat = mat; -} - -void KX_KetsjiEngine::SetCameraOverrideClipping(float nearfrust, float farfrust) -{ - m_overrideCamNear = nearfrust; - m_overrideCamFar = farfrust; -} - -void KX_KetsjiEngine::SetCameraOverrideLens(float lens) -{ - m_overrideCamLens = lens; -} - -void KX_KetsjiEngine::SetCameraOverrideZoom(float camzoom) -{ - m_overrideCamZoom = camzoom; -} - -void KX_KetsjiEngine::GetSceneViewport(KX_Scene *scene, KX_Camera* cam, RAS_Rect& area, RAS_Rect& viewport) -{ - // In this function we make sure the rasterizer settings are up-to-date. - // We compute the viewport so that logic using this information is up-to-date. - - // Note we postpone computation of the projection matrix - // so that we are using the latest camera position. - if (cam->GetViewport()) { - RAS_Rect userviewport; - - userviewport.SetLeft(cam->GetViewportLeft()); - userviewport.SetBottom(cam->GetViewportBottom()); - userviewport.SetRight(cam->GetViewportRight()); - userviewport.SetTop(cam->GetViewportTop()); - - // Don't do bars on user specified viewport - RAS_FrameSettings settings = scene->GetFramingType(); - if (settings.FrameType() == RAS_FrameSettings::e_frame_bars) - settings.SetFrameType(RAS_FrameSettings::e_frame_extend); - - RAS_FramingManager::ComputeViewport( - scene->GetFramingType(), - userviewport, - viewport - ); - - area = userviewport; - } - else if ( !m_overrideCam || (scene->GetName() != m_overrideSceneName) || m_overrideCamUseOrtho ) { - RAS_FramingManager::ComputeViewport( - scene->GetFramingType(), - m_canvas->GetDisplayArea(), - viewport - ); - - area = m_canvas->GetDisplayArea(); - } else { - viewport.SetLeft(0); - viewport.SetBottom(0); - viewport.SetRight(int(m_canvas->GetWidth())); - viewport.SetTop(int(m_canvas->GetHeight())); - - area = m_canvas->GetDisplayArea(); - } -} - -void KX_KetsjiEngine::UpdateAnimations(KX_Scene *scene) -{ - if (scene->IsSuspended()) { - return; - } - - // Handle the animations independently of the logic time step - if (GetRestrictAnimationFPS()) { - double anim_timestep = 1.0 / KX_GetActiveScene()->GetAnimationFPS(); - if (m_frameTime - m_previousAnimTime > anim_timestep || m_frameTime == m_previousAnimTime) { - // Sanity/debug print to make sure we're actually going at the fps we want (should be close to anim_timestep) - // printf("Anim fps: %f\n", 1.0/(m_frameTime - m_previousAnimTime)); - m_previousAnimTime = m_frameTime; - for (KX_SceneList::iterator sceneit = m_scenes.begin(); sceneit != m_scenes.end(); ++sceneit) - (*sceneit)->UpdateAnimations(m_frameTime); - } - } - else - scene->UpdateAnimations(m_frameTime); -} - -void KX_KetsjiEngine::RenderShadowBuffers(KX_Scene *scene) -{ - CListValue *lightlist = scene->GetLightList(); - int i, drawmode; - - m_rasterizer->SetAuxilaryClientInfo(scene); - - for (i=0; iGetCount(); i++) { - KX_GameObject *gameobj = (KX_GameObject*)lightlist->GetValue(i); - - KX_LightObject *light = (KX_LightObject*)gameobj; - RAS_ILightObject *raslight = light->GetLightData(); - - raslight->Update(); - - if (light->GetVisible() && m_rasterizer->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED && - raslight->HasShadowBuffer()) - { - /* make temporary camera */ - RAS_CameraData camdata = RAS_CameraData(); - KX_Camera *cam = new KX_Camera(scene, scene->m_callbacks, camdata, true, true); - cam->SetName("__shadow__cam__"); - - MT_Transform camtrans; - - /* switch drawmode for speed */ - drawmode = m_rasterizer->GetDrawingMode(); - m_rasterizer->SetDrawingMode(RAS_IRasterizer::KX_SHADOW); - - /* binds framebuffer object, sets up camera .. */ - raslight->BindShadowBuffer(m_canvas, cam, camtrans); - - /* update scene */ - scene->CalculateVisibleMeshes(m_rasterizer, cam, raslight->GetShadowLayer()); - - m_logger->StartLog(tc_animations, m_kxsystem->GetTimeInSeconds(), true); - SG_SetActiveStage(SG_STAGE_ANIMATION_UPDATE); - UpdateAnimations(scene); - m_logger->StartLog(tc_rasterizer, m_kxsystem->GetTimeInSeconds(), true); - SG_SetActiveStage(SG_STAGE_RENDER); - - /* render */ - m_rasterizer->ClearDepthBuffer(); - m_rasterizer->ClearColorBuffer(); - scene->RenderBuckets(camtrans, m_rasterizer); - - /* unbind framebuffer object, restore drawmode, free camera */ - raslight->UnbindShadowBuffer(); - m_rasterizer->SetDrawingMode(drawmode); - cam->Release(); - } - } - /* remember that we have a valid shadow buffer for that scene */ - scene->SetShadowDone(true); -} - -// update graphics -void KX_KetsjiEngine::RenderFrame(KX_Scene* scene, KX_Camera* cam) -{ - bool override_camera; - RAS_Rect viewport, area; - float nearfrust, farfrust, focallength; -// KX_Camera* cam = scene->GetActiveCamera(); - - if (!cam) - return; - - KX_SetActiveScene(scene); - -#ifdef WITH_PYTHON - scene->RunDrawingCallbacks(scene->GetPreDrawSetupCB()); -#endif - - GetSceneViewport(scene, cam, area, viewport); - - // store the computed viewport in the scene - scene->SetSceneViewport(viewport); - - // set the viewport for this frame and scene - m_canvas->SetViewPort(viewport.GetLeft(), viewport.GetBottom(), - viewport.GetRight(), viewport.GetTop()); - - // see KX_BlenderMaterial::Activate - //m_rasterizer->SetAmbient(); - m_rasterizer->DisplayFog(); - - override_camera = m_overrideCam && (scene->GetName() == m_overrideSceneName); - override_camera = override_camera && (cam->GetName() == "__default__cam__"); - - if (override_camera && m_overrideCamUseOrtho) { - m_rasterizer->SetProjectionMatrix(m_overrideCamProjMat); - if (!cam->hasValidProjectionMatrix()) { - // needed to get frustum planes for culling - MT_Matrix4x4 projmat; - projmat.setValue(m_overrideCamProjMat.getPointer()); - cam->SetProjectionMatrix(projmat); - } - } else if (cam->hasValidProjectionMatrix()) - { - m_rasterizer->SetProjectionMatrix(cam->GetProjectionMatrix()); - } else - { - RAS_FrameFrustum frustum; - bool orthographic = !cam->GetCameraData()->m_perspective; - nearfrust = cam->GetCameraNear(); - farfrust = cam->GetCameraFar(); - focallength = cam->GetFocalLength(); - MT_Matrix4x4 projmat; - - if (override_camera) { - nearfrust = m_overrideCamNear; - farfrust = m_overrideCamFar; - } - - float camzoom = override_camera ? m_overrideCamZoom : m_cameraZoom; - if (orthographic) { - - RAS_FramingManager::ComputeOrtho( - scene->GetFramingType(), - area, - viewport, - cam->GetScale(), - nearfrust, - farfrust, - cam->GetSensorFit(), - cam->GetShiftHorizontal(), - cam->GetShiftVertical(), - frustum - ); - if (!cam->GetViewport()) { - frustum.x1 *= camzoom; - frustum.x2 *= camzoom; - frustum.y1 *= camzoom; - frustum.y2 *= camzoom; - } - projmat = m_rasterizer->GetOrthoMatrix( - frustum.x1, frustum.x2, frustum.y1, frustum.y2, frustum.camnear, frustum.camfar); - - } else { - RAS_FramingManager::ComputeFrustum( - scene->GetFramingType(), - area, - viewport, - cam->GetLens(), - cam->GetSensorWidth(), - cam->GetSensorHeight(), - cam->GetSensorFit(), - cam->GetShiftHorizontal(), - cam->GetShiftVertical(), - nearfrust, - farfrust, - frustum - ); - - if (!cam->GetViewport()) { - frustum.x1 *= camzoom; - frustum.x2 *= camzoom; - frustum.y1 *= camzoom; - frustum.y2 *= camzoom; - } - projmat = m_rasterizer->GetFrustumMatrix( - frustum.x1, frustum.x2, frustum.y1, frustum.y2, frustum.camnear, frustum.camfar, focallength); - } - cam->SetProjectionMatrix(projmat); - - // Otherwise the projection matrix for each eye will be the same... - if (!orthographic && m_rasterizer->Stereo()) - cam->InvalidateProjectionMatrix(); - } - - MT_Transform camtrans(cam->GetWorldToCamera()); - MT_Matrix4x4 viewmat(camtrans); - - m_rasterizer->SetViewMatrix(viewmat, cam->NodeGetWorldOrientation(), cam->NodeGetWorldPosition(), cam->NodeGetLocalScaling(), cam->GetCameraData()->m_perspective); - cam->SetModelviewMatrix(viewmat); - - // The following actually reschedules all vertices to be - // redrawn. There is a cache between the actual rescheduling - // and this call though. Visibility is imparted when this call - // runs through the individual objects. - - m_logger->StartLog(tc_scenegraph, m_kxsystem->GetTimeInSeconds(), true); - SG_SetActiveStage(SG_STAGE_CULLING); - - scene->CalculateVisibleMeshes(m_rasterizer,cam); - - m_logger->StartLog(tc_animations, m_kxsystem->GetTimeInSeconds(), true); - SG_SetActiveStage(SG_STAGE_ANIMATION_UPDATE); - UpdateAnimations(scene); - - m_logger->StartLog(tc_rasterizer, m_kxsystem->GetTimeInSeconds(), true); - SG_SetActiveStage(SG_STAGE_RENDER); - -#ifdef WITH_PYTHON - PHY_SetActiveEnvironment(scene->GetPhysicsEnvironment()); - // Run any pre-drawing python callbacks - scene->RunDrawingCallbacks(scene->GetPreDrawCB()); -#endif - - scene->RenderBuckets(camtrans, m_rasterizer); - - // render all the font objects for this scene - scene->RenderFonts(); - - if (scene->GetPhysicsEnvironment()) - scene->GetPhysicsEnvironment()->DebugDrawWorld(); -} - -/* - * To run once per scene - */ -void KX_KetsjiEngine::PostRenderScene(KX_Scene* scene) -{ - KX_SetActiveScene(scene); - - // We need to first make sure our viewport is correct (enabling multiple viewports can mess this up) - m_canvas->SetViewPort(0, 0, m_canvas->GetWidth(), m_canvas->GetHeight()); - - m_rasterizer->FlushDebugShapes(scene); - scene->Render2DFilters(m_canvas); - -#ifdef WITH_PYTHON - PHY_SetActiveEnvironment(scene->GetPhysicsEnvironment()); - scene->RunDrawingCallbacks(scene->GetPostDrawCB()); - - // Python draw callback can also call debug draw functions, so we have to clear debug shapes. - m_rasterizer->FlushDebugShapes(scene); -#endif -} - -void KX_KetsjiEngine::StopEngine() -{ - if (m_bInitialized) - { - m_sceneconverter->FinalizeAsyncLoads(); - - if (m_animation_record) - { -// printf("TestHandlesPhysicsObjectToAnimationIpo\n"); - m_sceneconverter->TestHandlesPhysicsObjectToAnimationIpo(); - } - - KX_SceneList::iterator sceneit; - for (sceneit = m_scenes.begin();sceneit != m_scenes.end() ; sceneit++) - { - KX_Scene* scene = *sceneit; - m_sceneconverter->RemoveScene(scene); - } - m_scenes.clear(); - - // cleanup all the stuff - m_rasterizer->Exit(); - } -} - -// Scene Management is able to switch between scenes -// and have several scenes running in parallel -void KX_KetsjiEngine::AddScene(KX_Scene* scene) -{ - m_scenes.push_back(scene); - PostProcessScene(scene); -} - - - -void KX_KetsjiEngine::PostProcessScene(KX_Scene* scene) -{ - bool override_camera = (m_overrideCam && (scene->GetName() == m_overrideSceneName)); - - SG_SetActiveStage(SG_STAGE_SCENE); - - // if there is no activecamera, or the camera is being - // overridden we need to construct a temporary camera - if (!scene->GetActiveCamera() || override_camera) - { - KX_Camera* activecam = NULL; - - RAS_CameraData camdata = RAS_CameraData(); - if (override_camera) - { - camdata.m_lens = m_overrideCamLens; - camdata.m_clipstart = m_overrideCamNear; - camdata.m_clipend = m_overrideCamFar; - - camdata.m_perspective= !m_overrideCamUseOrtho; - } - activecam = new KX_Camera(scene,KX_Scene::m_callbacks,camdata); - activecam->SetName("__default__cam__"); - - // set transformation - if (override_camera) { - const MT_CmMatrix4x4& cammatdata = m_overrideCamViewMat; - MT_Transform trans = MT_Transform(cammatdata.getPointer()); - MT_Transform camtrans; - camtrans.invert(trans); - - activecam->NodeSetLocalPosition(camtrans.getOrigin()); - activecam->NodeSetLocalOrientation(camtrans.getBasis()); - activecam->NodeUpdateGS(0); - } else { - activecam->NodeSetLocalPosition(MT_Point3(0.0f, 0.0f, 0.0f)); - activecam->NodeSetLocalOrientation(MT_Vector3(0.0f, 0.0f, 0.0f)); - activecam->NodeUpdateGS(0); - } - - scene->AddCamera(activecam); - scene->SetActiveCamera(activecam); - scene->GetObjectList()->Add(activecam->AddRef()); - scene->GetRootParentList()->Add(activecam->AddRef()); - // done with activecam - activecam->Release(); - } - - scene->UpdateParents(0.0); -} - - - -void KX_KetsjiEngine::RenderDebugProperties() -{ - STR_String debugtxt; - int title_xmargin = -7; - int title_y_top_margin = 4; - int title_y_bottom_margin = 2; - - int const_xindent = 4; - int const_ysize = 14; - - int xcoord = 12; // mmmm, these constants were taken from blender source - int ycoord = 17; // to 'mimic' behavior - - int profile_indent = 72; - - float tottime = m_logger->GetAverage(); - if (tottime < 1e-6f) { - tottime = 1e-6f; - } - - // Set viewport to entire canvas - RAS_Rect viewport; - m_canvas->SetViewPort(0, 0, int(m_canvas->GetWidth()), int(m_canvas->GetHeight())); - - if (m_show_framerate || m_show_profile) { - /* Title for profiling("Profile") */ - m_rasterizer->RenderText2D(RAS_IRasterizer::RAS_TEXT_PADDED, - "Profile", - xcoord + const_xindent + title_xmargin, // Adds the constant x indent (0 for now) to the title x margin - ycoord, - m_canvas->GetWidth() /* RdV, TODO ?? */, - m_canvas->GetHeight() /* RdV, TODO ?? */); - - // Increase the indent by default increase - ycoord += const_ysize; - // Add the title indent afterwards - ycoord += title_y_bottom_margin; - } - - /* Framerate display */ - if (m_show_framerate) { - m_rasterizer->RenderText2D(RAS_IRasterizer::RAS_TEXT_PADDED, - "Frametime :", - xcoord + const_xindent, - ycoord, - m_canvas->GetWidth() /* RdV, TODO ?? */, - m_canvas->GetHeight() /* RdV, TODO ?? */); - - debugtxt.Format("%5.1fms (%.1ffps)", tottime * 1000.0f, 1.0f/tottime); - m_rasterizer->RenderText2D(RAS_IRasterizer::RAS_TEXT_PADDED, - debugtxt.ReadPtr(), - xcoord + const_xindent + profile_indent, - ycoord, - m_canvas->GetWidth() /* RdV, TODO ?? */, - m_canvas->GetHeight() /* RdV, TODO ?? */); - // Increase the indent by default increase - ycoord += const_ysize; - } - - /* Profile display */ - if (m_show_profile) { - for (int j = tc_first; j < tc_numCategories; j++) { - m_rasterizer->RenderText2D(RAS_IRasterizer::RAS_TEXT_PADDED, - m_profileLabels[j], - xcoord + const_xindent, - ycoord, - m_canvas->GetWidth(), - m_canvas->GetHeight()); - - double time = m_logger->GetAverage((KX_TimeCategory)j); - - debugtxt.Format("%5.2fms | %d%%", (float)time*1000.f, (int)((float)time/tottime * 100.f)); - m_rasterizer->RenderText2D(RAS_IRasterizer::RAS_TEXT_PADDED, - debugtxt.ReadPtr(), - xcoord + const_xindent + profile_indent, ycoord, - m_canvas->GetWidth(), - m_canvas->GetHeight()); - - m_rasterizer->RenderBox2D(xcoord + (int)(2.2f * profile_indent), ycoord, m_canvas->GetWidth(), m_canvas->GetHeight(), (float)time/tottime); - ycoord += const_ysize; - } - } - // Add the ymargin for titles below the other section of debug info - ycoord += title_y_top_margin; - - /* Property display */ - if (m_show_debug_properties) { - - /* Title for debugging("Debug properties") */ - m_rasterizer->RenderText2D(RAS_IRasterizer::RAS_TEXT_PADDED, - "Debug Properties", - xcoord + const_xindent + title_xmargin, // Adds the constant x indent (0 for now) to the title x margin - ycoord, - m_canvas->GetWidth() /* RdV, TODO ?? */, - m_canvas->GetHeight() /* RdV, TODO ?? */); - - // Increase the indent by default increase - ycoord += const_ysize; - // Add the title indent afterwards - ycoord += title_y_bottom_margin; - - /* Calculate amount of properties that can displayed. */ - unsigned propsAct = 0; - unsigned propsMax = (m_canvas->GetHeight() - ycoord) / const_ysize; - - KX_SceneList::iterator sceneit; - for (sceneit = m_scenes.begin();sceneit != m_scenes.end(); sceneit++) { - KX_Scene* scene = *sceneit; - /* the 'normal' debug props */ - vector& debugproplist = scene->GetDebugProperties(); - - for (unsigned i=0; i < debugproplist.size() && propsAct < propsMax; i++) - { - CValue *propobj = debugproplist[i]->m_obj; - STR_String objname = propobj->GetName(); - STR_String propname = debugproplist[i]->m_name; - propsAct++; - if (propname == "__state__") { - // reserve name for object state - KX_GameObject* gameobj = static_cast(propobj); - unsigned int state = gameobj->GetState(); - debugtxt = objname + "." + propname + " = "; - bool first = true; - for (int statenum=1;state;state >>= 1, statenum++) - { - if (state & 1) - { - if (!first) - { - debugtxt += ","; - } - debugtxt += STR_String(statenum); - first = false; - } - } - m_rasterizer->RenderText2D(RAS_IRasterizer::RAS_TEXT_PADDED, - debugtxt.ReadPtr(), - xcoord + const_xindent, - ycoord, - m_canvas->GetWidth(), - m_canvas->GetHeight()); - ycoord += const_ysize; - } - else { - CValue *propval = propobj->GetProperty(propname); - if (propval) { - STR_String text = propval->GetText(); - debugtxt = objname + ": '" + propname + "' = " + text; - m_rasterizer->RenderText2D(RAS_IRasterizer::RAS_TEXT_PADDED, - debugtxt.ReadPtr(), - xcoord + const_xindent, - ycoord, - m_canvas->GetWidth(), - m_canvas->GetHeight()); - ycoord += const_ysize; - } - } - } - } - } -} - - -KX_SceneList* KX_KetsjiEngine::CurrentScenes() -{ - return &m_scenes; -} - - - -KX_Scene* KX_KetsjiEngine::FindScene(const STR_String& scenename) -{ - KX_SceneList::iterator sceneit = m_scenes.begin(); - - // bit risky :) better to split the second clause - while ( (sceneit != m_scenes.end()) - && ((*sceneit)->GetName() != scenename)) - { - sceneit++; - } - - return ((sceneit == m_scenes.end()) ? NULL : *sceneit); -} - - - -void KX_KetsjiEngine::ConvertAndAddScene(const STR_String& scenename,bool overlay) -{ - // only add scene when it doesn't exist! - if (FindScene(scenename)) { - printf("warning: scene %s already exists, not added!\n",scenename.ReadPtr()); - } - else { - if (overlay) { - m_addingOverlayScenes.push_back(scenename); - } - else { - m_addingBackgroundScenes.push_back(scenename); - } - } -} - - - - -void KX_KetsjiEngine::RemoveScene(const STR_String& scenename) -{ - if (FindScene(scenename)) - { - m_removingScenes.push_back(scenename); - } - else - { -// STR_String tmpname = scenename; - std::cout << "warning: scene " << scenename << " does not exist, not removed!" << std::endl; - } -} - - - -void KX_KetsjiEngine::RemoveScheduledScenes() -{ - if (m_removingScenes.size()) - { - vector::iterator scenenameit; - for (scenenameit=m_removingScenes.begin();scenenameit != m_removingScenes.end();scenenameit++) - { - STR_String scenename = *scenenameit; - - KX_SceneList::iterator sceneit; - for (sceneit = m_scenes.begin();sceneit != m_scenes.end() ; sceneit++) - { - KX_Scene* scene = *sceneit; - if (scene->GetName()==scenename) - { - m_sceneconverter->RemoveScene(scene); - m_scenes.erase(sceneit); - break; - } - } - } - m_removingScenes.clear(); - } -} - -KX_Scene* KX_KetsjiEngine::CreateScene(Scene *scene, bool libloading) -{ - KX_Scene* tmpscene = new KX_Scene(m_keyboarddevice, - m_mousedevice, - m_networkdevice, - scene->id.name+2, - scene, - m_canvas); - - m_sceneconverter->ConvertScene(tmpscene, - m_rasterizer, - m_canvas, - libloading); - - return tmpscene; -} - -KX_Scene* KX_KetsjiEngine::CreateScene(const STR_String& scenename) -{ - Scene *scene = m_sceneconverter->GetBlenderSceneForName(scenename); - if (!scene) - return NULL; - return CreateScene(scene); -} - -void KX_KetsjiEngine::AddScheduledScenes() -{ - vector::iterator scenenameit; - - if (m_addingOverlayScenes.size()) - { - for (scenenameit = m_addingOverlayScenes.begin(); - scenenameit != m_addingOverlayScenes.end(); - scenenameit++) - { - STR_String scenename = *scenenameit; - KX_Scene* tmpscene = CreateScene(scenename); - if (tmpscene) { - m_scenes.push_back(tmpscene); - PostProcessScene(tmpscene); - } else { - printf("warning: scene %s could not be found, not added!\n",scenename.ReadPtr()); - } - } - m_addingOverlayScenes.clear(); - } - - if (m_addingBackgroundScenes.size()) - { - for (scenenameit = m_addingBackgroundScenes.begin(); - scenenameit != m_addingBackgroundScenes.end(); - scenenameit++) - { - STR_String scenename = *scenenameit; - KX_Scene* tmpscene = CreateScene(scenename); - if (tmpscene) { - m_scenes.insert(m_scenes.begin(),tmpscene); - PostProcessScene(tmpscene); - } else { - printf("warning: scene %s could not be found, not added!\n",scenename.ReadPtr()); - } - } - m_addingBackgroundScenes.clear(); - } -} - - - -bool KX_KetsjiEngine::ReplaceScene(const STR_String& oldscene,const STR_String& newscene) -{ - // Don't allow replacement if the new scene doesn't exist. - // Allows smarter game design (used to have no check here). - // Note that it creates a small backward compatbility issue - // for a game that did a replace followed by a lib load with the - // new scene in the lib => it won't work anymore, the lib - // must be loaded before doing the replace. - if (m_sceneconverter->GetBlenderSceneForName(newscene) != NULL) { - m_replace_scenes.push_back(std::make_pair(oldscene,newscene)); - return true; - } - return false; -} - -// replace scene is not the same as removing and adding because the -// scene must be in exact the same place (to maintain drawingorder) -// (nzc) - should that not be done with a scene-display list? It seems -// stupid to rely on the mem allocation order... -void KX_KetsjiEngine::ReplaceScheduledScenes() -{ - if (m_replace_scenes.size()) - { - vector >::iterator scenenameit; - - for (scenenameit = m_replace_scenes.begin(); - scenenameit != m_replace_scenes.end(); - scenenameit++) - { - STR_String oldscenename = (*scenenameit).first; - STR_String newscenename = (*scenenameit).second; - int i=0; - /* Scenes are not supposed to be included twice... I think */ - KX_SceneList::iterator sceneit; - for (sceneit = m_scenes.begin();sceneit != m_scenes.end() ; sceneit++) { - KX_Scene* scene = *sceneit; - if (scene->GetName() == oldscenename) { - // avoid crash if the new scene doesn't exist, just do nothing - Scene *blScene = m_sceneconverter->GetBlenderSceneForName(newscenename); - if (blScene) { - m_sceneconverter->RemoveScene(scene); - KX_Scene* tmpscene = CreateScene(blScene); - m_scenes[i]=tmpscene; - PostProcessScene(tmpscene); - } - else { - printf("warning: scene %s could not be found, not replaced!\n",newscenename.ReadPtr()); - } - } - i++; - } - } - m_replace_scenes.clear(); - } -} - - - -void KX_KetsjiEngine::SuspendScene(const STR_String& scenename) -{ - KX_Scene* scene = FindScene(scenename); - if (scene) scene->Suspend(); -} - - - -void KX_KetsjiEngine::ResumeScene(const STR_String& scenename) -{ - KX_Scene* scene = FindScene(scenename); - if (scene) scene->Resume(); -} - - - -void KX_KetsjiEngine::SetUseFixedTime(bool bUseFixedTime) -{ - m_bFixedTime = bUseFixedTime; -} - -void KX_KetsjiEngine::SetUseExternalClock(bool useExternalClock) -{ - m_useExternalClock = useExternalClock; -} - -void KX_KetsjiEngine::SetAnimRecordMode(bool animation_record, int startFrame) -{ - m_animation_record = animation_record; - if (animation_record) - { - // when recording physics keyframes, run at a variable (capped) frame rate (fixed time == full speed) - m_bFixedTime = false; - } - m_currentFrame = startFrame; -} - -int KX_KetsjiEngine::getAnimRecordFrame() const -{ - return m_currentFrame; -} - -void KX_KetsjiEngine::setAnimRecordFrame(int framenr) -{ - m_currentFrame = framenr; -} - -bool KX_KetsjiEngine::GetUseFixedTime(void) const -{ - return m_bFixedTime; -} - -bool KX_KetsjiEngine::GetUseExternalClock(void) const -{ - return m_useExternalClock; -} - -double KX_KetsjiEngine::GetSuspendedDelta() -{ - return m_suspendeddelta; -} - -double KX_KetsjiEngine::GetTicRate() -{ - return m_ticrate; -} - -void KX_KetsjiEngine::SetTicRate(double ticrate) -{ - m_ticrate = ticrate; -} - -double KX_KetsjiEngine::GetTimeScale() const -{ - return m_timescale; -} - -void KX_KetsjiEngine::SetTimeScale(double timescale) -{ - m_timescale = timescale; -} - -int KX_KetsjiEngine::GetMaxLogicFrame() -{ - return m_maxLogicFrame; -} - -void KX_KetsjiEngine::SetMaxLogicFrame(int frame) -{ - m_maxLogicFrame = frame; -} - -int KX_KetsjiEngine::GetMaxPhysicsFrame() -{ - return m_maxPhysicsFrame; -} - -void KX_KetsjiEngine::SetMaxPhysicsFrame(int frame) -{ - m_maxPhysicsFrame = frame; -} - -bool KX_KetsjiEngine::GetRestrictAnimationFPS() -{ - return m_restrict_anim_fps; -} - -void KX_KetsjiEngine::SetRestrictAnimationFPS(bool bRestrictAnimFPS) -{ - m_restrict_anim_fps = bRestrictAnimFPS; -} - -double KX_KetsjiEngine::GetAnimFrameRate() -{ - return m_anim_framerate; -} - -double KX_KetsjiEngine::GetClockTime(void) const -{ - return m_clockTime; -} - -void KX_KetsjiEngine::SetClockTime(double externalClockTime) -{ - m_clockTime = externalClockTime; -} - -double KX_KetsjiEngine::GetFrameTime(void) const -{ - return m_frameTime; -} - -double KX_KetsjiEngine::GetRealTime(void) const -{ - return m_kxsystem->GetTimeInSeconds(); -} - -void KX_KetsjiEngine::SetAnimFrameRate(double framerate) -{ - m_anim_framerate = framerate; -} - -double KX_KetsjiEngine::GetAverageFrameRate() -{ - return m_average_framerate; -} - -void KX_KetsjiEngine::SetExitKey(short key) -{ - m_exitkey = key; -} - -short KX_KetsjiEngine::GetExitKey() -{ - return m_exitkey; -} - -void KX_KetsjiEngine::SetRender(bool render) -{ - m_doRender = render; -} - -bool KX_KetsjiEngine::GetRender() -{ - return m_doRender; -} - -void KX_KetsjiEngine::SetShowFramerate(bool frameRate) -{ - m_show_framerate = frameRate; -} - -bool KX_KetsjiEngine::GetShowFramerate() -{ - return m_show_framerate; -} - -void KX_KetsjiEngine::SetShowProfile(bool profile) -{ - m_show_profile = profile; -} - -bool KX_KetsjiEngine::GetShowProfile() -{ - return m_show_profile; -} - -void KX_KetsjiEngine::SetShowProperties(bool properties) -{ - m_show_debug_properties = properties; -} - -bool KX_KetsjiEngine::GetShowProperties() -{ - return m_show_debug_properties; -} - -void KX_KetsjiEngine::SetAutoAddDebugProperties(bool add) -{ - m_autoAddDebugProperties = add; -} - -bool KX_KetsjiEngine::GetAutoAddDebugProperties() -{ - return m_autoAddDebugProperties; -} - -void KX_KetsjiEngine::SetTimingDisplay(bool frameRate, bool profile, bool properties) -{ - m_show_framerate = frameRate; - m_show_profile = profile; - m_show_debug_properties = properties; -} - - - -void KX_KetsjiEngine::GetTimingDisplay(bool& frameRate, bool& profile, bool& properties) const -{ - frameRate = m_show_framerate; - profile = m_show_profile; - properties = m_show_debug_properties; -} - - - -void KX_KetsjiEngine::ProcessScheduledScenes(void) -{ - // Check whether there will be changes to the list of scenes - if (m_addingOverlayScenes.size() || - m_addingBackgroundScenes.size() || - m_replace_scenes.size() || - m_removingScenes.size()) { - - // Change the scene list - ReplaceScheduledScenes(); - RemoveScheduledScenes(); - AddScheduledScenes(); - } -} - - -void KX_KetsjiEngine::SetHideCursor(bool hideCursor) -{ - m_hideCursor = hideCursor; -} - - -bool KX_KetsjiEngine::GetHideCursor(void) const -{ - return m_hideCursor; -} - - -void KX_KetsjiEngine::SetUseOverrideFrameColor(bool overrideFrameColor) -{ - m_overrideFrameColor = overrideFrameColor; -} - - -bool KX_KetsjiEngine::GetUseOverrideFrameColor(void) const -{ - return m_overrideFrameColor; -} - - -void KX_KetsjiEngine::SetOverrideFrameColor(float r, float g, float b, float a) -{ - m_overrideFrameColorR = r; - m_overrideFrameColorG = g; - m_overrideFrameColorB = b; - m_overrideFrameColorA = a; -} - - -void KX_KetsjiEngine::GetOverrideFrameColor(float& r, float& g, float& b, float& a) const -{ - r = m_overrideFrameColorR; - g = m_overrideFrameColorG; - b = m_overrideFrameColorB; - a = m_overrideFrameColorA; -} - - -void KX_KetsjiEngine::Resize() -{ - KX_SceneList::iterator sceneit; - - /* extended mode needs to recalculate camera frusta when */ - KX_Scene* firstscene = *m_scenes.begin(); - const RAS_FrameSettings &framesettings = firstscene->GetFramingType(); - - if (framesettings.FrameType() == RAS_FrameSettings::e_frame_extend) { - for (sceneit = m_scenes.begin(); sceneit != m_scenes.end(); sceneit++) { - KX_Camera* cam = ((KX_Scene *)*sceneit)->GetActiveCamera(); - cam->InvalidateProjectionMatrix(); - } - } -} - - -void KX_KetsjiEngine::SetGlobalSettings(GlobalSettings* gs) -{ - m_globalsettings.matmode = gs->matmode; - m_globalsettings.glslflag = gs->glslflag; -} - -GlobalSettings* KX_KetsjiEngine::GetGlobalSettings(void) -{ - return &m_globalsettings; -} - diff --git a/source/gameengine/Ketsji/KX_KetsjiEngine.h b/source/gameengine/Ketsji/KX_KetsjiEngine.h deleted file mode 100644 index 1756214b6dd..00000000000 --- a/source/gameengine/Ketsji/KX_KetsjiEngine.h +++ /dev/null @@ -1,553 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - * - */ - -/** \file KX_KetsjiEngine.h - * \ingroup ketsji - */ - -#ifndef __KX_KETSJIENGINE_H__ -#define __KX_KETSJIENGINE_H__ - -#include "MT_CmMatrix4x4.h" -#include "MT_Matrix4x4.h" -#include "STR_String.h" -#include "KX_ISystem.h" -#include "KX_Scene.h" -#include "EXP_Python.h" -#include "KX_WorldInfo.h" -#include - -struct TaskScheduler; -class KX_TimeCategoryLogger; - -#define LEFT_EYE 1 -#define RIGHT_EYE 2 - -enum KX_ExitRequestMode -{ - KX_EXIT_REQUEST_NO_REQUEST = 0, - KX_EXIT_REQUEST_QUIT_GAME, - KX_EXIT_REQUEST_RESTART_GAME, - KX_EXIT_REQUEST_START_OTHER_GAME, - KX_EXIT_REQUEST_NO_SCENES_LEFT, - KX_EXIT_REQUEST_BLENDER_ESC, - KX_EXIT_REQUEST_OUTSIDE, - KX_EXIT_REQUEST_MAX -}; - -typedef struct { - short matmode; - short glslflag; -} GlobalSettings; - -/** - * KX_KetsjiEngine is the core game engine class. - */ -class KX_KetsjiEngine -{ - -private: - class RAS_ICanvas* m_canvas; // 2D Canvas (2D Rendering Device Context) - class RAS_IRasterizer* m_rasterizer; // 3D Rasterizer (3D Rendering) - class KX_ISystem* m_kxsystem; - class KX_ISceneConverter* m_sceneconverter; - class NG_NetworkDeviceInterface* m_networkdevice; -#ifdef WITH_PYTHON - /* borrowed from sys.modules["__main__"], don't manage ref's */ - PyObject* m_pythondictionary; - PyObject* m_pyprofiledict; -#endif - class SCA_IInputDevice* m_keyboarddevice; - class SCA_IInputDevice* m_mousedevice; - class KX_Dome* m_dome; // dome stereo mode - - /** Lists of scenes scheduled to be removed at the end of the frame. */ - std::vector m_removingScenes; - /** Lists of overley scenes scheduled to be added at the end of the frame. */ - std::vector m_addingOverlayScenes; - /** Lists of background scenes scheduled to be added at the end of the frame. */ - std::vector m_addingBackgroundScenes; - /** Lists of scenes scheduled to be replaced at the end of the frame. */ - std::vector > m_replace_scenes; - - /* The current list of scenes. */ - KX_SceneList m_scenes; - /* State variable recording the presence of object debug info in the current scene list. */ - bool m_propertiesPresent; - - bool m_bInitialized; - int m_activecam; - bool m_bFixedTime; - bool m_useExternalClock; - - - bool m_firstframe; - int m_currentFrame; - - double m_frameTime; // current logic game time - double m_clockTime; // game time for the next rendering step - double m_previousClockTime; // game time of the previous rendering step - double m_previousAnimTime; //game time when the animations were last updated - double m_remainingTime; - double m_timescale; // time scaling parameter. if > 1.0, time goes faster than real-time. If < 1.0, times goes slower than real-time. - double m_previousRealTime; - - static int m_maxLogicFrame; /* maximum number of consecutive logic frame */ - static int m_maxPhysicsFrame; /* maximum number of consecutive physics frame */ - static double m_ticrate; - static double m_anim_framerate; /* for animation playback only - ipo and action */ - - static bool m_restrict_anim_fps; - - static double m_suspendedtime; - static double m_suspendeddelta; - - static short m_exitkey; /* Key used to exit the BGE */ - - static bool m_doRender; /* whether or not the scene should be rendered after the logic frame */ - - int m_exitcode; - STR_String m_exitstring; - - float m_cameraZoom; - - bool m_overrideCam; - STR_String m_overrideSceneName; - - bool m_overrideCamUseOrtho; - MT_CmMatrix4x4 m_overrideCamProjMat; - MT_CmMatrix4x4 m_overrideCamViewMat; - float m_overrideCamNear; - float m_overrideCamFar; - float m_overrideCamLens; - /// Default camera zoom. - float m_overrideCamZoom; - - bool m_stereo; - int m_curreye; - - /** Categories for profiling display. */ - typedef enum { - tc_first = 0, - tc_physics = 0, - tc_logic, - tc_animations, - tc_network, - tc_scenegraph, - tc_rasterizer, - tc_services, // time spent in miscelaneous activities - tc_overhead, // profile info drawing overhead - tc_outside, // time spent outside main loop - tc_latency, // time spent waiting on the gpu - tc_numCategories - } KX_TimeCategory; - - /** Time logger. */ - KX_TimeCategoryLogger* m_logger; - - /** Labels for profiling display. */ - static const char m_profileLabels[tc_numCategories][15]; - /** Last estimated framerate */ - static double m_average_framerate; - /** Show the framerate on the game display? */ - bool m_show_framerate; - /** Show profiling info on the game display? */ - bool m_show_profile; - /** Show any debug (scene) object properties on the game display? */ - bool m_showProperties; - /** Show background behind text for readability? */ - bool m_showBackground; - /** Show debug properties on the game display*/ - bool m_show_debug_properties; - /** Automatic add debug properties to the debug list*/ - bool m_autoAddDebugProperties; - - /** record physics into keyframes */ - bool m_animation_record; - - /** Hide cursor every frame? */ - bool m_hideCursor; - - /** Override framing bars color? */ - bool m_overrideFrameColor; - /** Red component of framing bar color. */ - float m_overrideFrameColorR; - /** Green component of framing bar color. */ - float m_overrideFrameColorG; - /** Blue component of framing bar color. */ - float m_overrideFrameColorB; - /** alpha component of framing bar color. */ - float m_overrideFrameColorA; - - /** Settings that doesn't go away with Game Actuator */ - GlobalSettings m_globalsettings; - - /** Task scheduler for multi-threading */ - TaskScheduler* m_taskscheduler; - - void RenderFrame(KX_Scene* scene, KX_Camera* cam); - void PostRenderScene(KX_Scene* scene); - void RenderDebugProperties(); - -public: - KX_KetsjiEngine(class KX_ISystem* system); - virtual ~KX_KetsjiEngine(); - - // set the devices and stuff. the client must take care of creating these - void SetKeyboardDevice(SCA_IInputDevice* keyboarddevice); - void SetMouseDevice(SCA_IInputDevice* mousedevice); - void SetNetworkDevice(NG_NetworkDeviceInterface* networkdevice); - void SetCanvas(RAS_ICanvas* canvas); - void SetRasterizer(RAS_IRasterizer* rasterizer); -#ifdef WITH_PYTHON - void SetPyNamespace(PyObject *pythondictionary); - PyObject* GetPyNamespace() { return m_pythondictionary; } - PyObject* GetPyProfileDict(); -#endif - void SetSceneConverter(KX_ISceneConverter* sceneconverter); - KX_ISceneConverter* GetSceneConverter() { return m_sceneconverter; } - void SetAnimRecordMode(bool animation_record, int startFrame); - - int getAnimRecordFrame() const; - void setAnimRecordFrame(int framenr); - - RAS_IRasterizer* GetRasterizer() { return m_rasterizer; } - RAS_ICanvas* GetCanvas() { return m_canvas; } - SCA_IInputDevice* GetKeyboardDevice() { return m_keyboarddevice; } - SCA_IInputDevice* GetMouseDevice() { return m_mousedevice; } - - TaskScheduler* GetTaskScheduler() { return m_taskscheduler; } - - /// Dome functions - void InitDome(short res, short mode, short angle, float resbuf, short tilt, struct Text* text); - void EndDome(); - void RenderDome(); - bool m_usedome; - - ///returns true if an update happened to indicate -> Render - bool NextFrame(); - void Render(); - void RenderShadowBuffers(KX_Scene *scene); - - void StartEngine(bool clearIpo); - void StopEngine(); - void Export(const STR_String& filename); - - void RequestExit(int exitrequestmode); - void SetNameNextGame(const STR_String& nextgame); - int GetExitCode(); - const STR_String& GetExitString(); - - KX_SceneList* CurrentScenes(); - KX_Scene* FindScene(const STR_String& scenename); - void AddScene(class KX_Scene* scene); - void ConvertAndAddScene(const STR_String& scenename,bool overlay); - - void RemoveScene(const STR_String& scenename); - bool ReplaceScene(const STR_String& oldscene,const STR_String& newscene); - void SuspendScene(const STR_String& scenename); - void ResumeScene(const STR_String& scenename); - - void GetSceneViewport(KX_Scene* scene, KX_Camera* cam, RAS_Rect& area, RAS_Rect& viewport); - - /// Sets zoom for camera objects, useful only with extend and scale framing mode. - void SetCameraZoom(float camzoom); - - void EnableCameraOverride(const STR_String& forscene); - - void SetCameraOverrideUseOrtho(bool useOrtho); - void SetCameraOverrideProjectionMatrix(const MT_CmMatrix4x4& mat); - void SetCameraOverrideViewMatrix(const MT_CmMatrix4x4& mat); - void SetCameraOverrideClipping(float near, float far); - void SetCameraOverrideLens(float lens); - /// Sets zoom for default camera, = 2 in embedded mode. - void SetCameraOverrideZoom(float camzoom); - - // Update animations for object in this scene - void UpdateAnimations(KX_Scene *scene); - - /** - * Sets display of all frames. - * \param bUseFixedTime New setting for display all frames. - */ - void SetUseFixedTime(bool bUseFixedTime); - - /** - * Returns display of all frames. - * \return Current setting for display all frames. - */ - bool GetUseFixedTime(void) const; - - /** - * Sets if the BGE relies on a external clock or its own internal clock - */ - void SetUseExternalClock(bool bUseExternalClock); - - /** - * Returns if we rely on an external clock - * \return Current setting - */ - bool GetUseExternalClock(void) const; - - /** - * Returns next render frame game time - */ - double GetClockTime(void) const; - - /** - * Set the next render frame game time. It will impact also frame time, as - * this one is derived from clocktime - */ - void SetClockTime(double externalClockTime); - - /** - * Returns current logic frame game time - */ - double GetFrameTime(void) const; - - /** - * Returns the real (system) time - */ - double GetRealTime(void) const; - - /** - * Returns the difference between the local time of the scene (when it - * was running and not suspended) and the "curtime" - */ - static double GetSuspendedDelta(); - - /** - * Gets the number of logic updates per second. - */ - static double GetTicRate(); - /** - * Sets the number of logic updates per second. - */ - static void SetTicRate(double ticrate); - /** - * Gets the maximum number of logic frame before render frame - */ - static int GetMaxLogicFrame(); - /** - * Sets the maximum number of logic frame before render frame - */ - static void SetMaxLogicFrame(int frame); - /** - * Gets the maximum number of physics frame before render frame - */ - static int GetMaxPhysicsFrame(); - /** - * Sets the maximum number of physics frame before render frame - */ - static void SetMaxPhysicsFrame(int frame); - - /** - * Gets whether or not to lock animation updates to the animframerate - */ - static bool GetRestrictAnimationFPS(); - - /** - * Sets whether or not to lock animation updates to the animframerate - */ - static void SetRestrictAnimationFPS(bool bRestrictAnimFPS); - - /** - * Gets the framerate for playing animations. (actions and ipos) - */ - static double GetAnimFrameRate(); - /** - * Sets the framerate for playing animations. (actions and ipos) - */ - static void SetAnimFrameRate(double framerate); - - /** - * Gets the last estimated average framerate - */ - static double GetAverageFrameRate(); - - /** - * Gets the time scale multiplier - */ - double GetTimeScale() const; - - /** - * Sets the time scale multiplier - */ - void SetTimeScale(double scale); - - static void SetExitKey(short key); - - static short GetExitKey(); - - /** - * Activate or deactivates the render of the scene after the logic frame - * \param render true (render) or false (do not render) - */ - static void SetRender(bool render); - /** - * Get the current render flag value - */ - static bool GetRender(); - - /** - * \Sets the display for frame rate on or off. - */ - void SetShowFramerate(bool frameRate); - - /** - * \Gets the display for frame rate on or off. - */ - bool GetShowFramerate(); - - /** - * \Sets the display for individual components on or off. - */ - void SetShowProfile(bool profile); - - /** - * \Gets the display for individual components on or off. - */ - bool GetShowProfile(); - - /** - * \Sets the display of scene object debug properties on or off. - */ - void SetShowProperties(bool properties); - - /** - * \Gets the display of scene object debug properties on or off. - */ - bool GetShowProperties(); - - /** - * \Sets if the auto adding of scene object debug properties on or off. - */ - bool GetAutoAddDebugProperties(); - - /** - * \Sets the auto adding of scene object debug properties on or off. - */ - void SetAutoAddDebugProperties(bool add); - - /** - * Activates or deactivates timing information display. - * \param frameRate Display for frame rate on or off. - * \param profile Display for individual components on or off. - * \param properties Display of scene object debug properties on or off. - */ - void SetTimingDisplay(bool frameRate, bool profile, bool properties); - - /** - * Returns status of timing information display. - * \param frameRate Display for frame rate on or off. - * \param profile Display for individual components on or off. - * \param properties Display of scene object debug properties on or off. - */ - void GetTimingDisplay(bool& frameRate, bool& profile, bool& properties) const; - - /** - * Sets cursor hiding on every frame. - * \param hideCursor Turns hiding on or off. - */ - void SetHideCursor(bool hideCursor); - - /** - * Returns the current setting for cursor hiding. - * \return The current setting for cursor hiding. - */ - bool GetHideCursor(void) const; - - /** - * Enables/disables the use of the framing bar color of the Blender file's scenes. - * \param overrideFrameColor The new setting. - */ - void SetUseOverrideFrameColor(bool overrideFrameColor); - - /** - * Check if the frame color is being overridden. - */ - bool GetUseOverrideFrameColor(void) const; - - /** - * Set the color used for framing bar color instead of the one in the Blender file's scenes. - * \param r Red component of the override color. - * \param g Green component of the override color. - * \param b Blue component of the override color. - */ - void SetOverrideFrameColor(float r, float g, float b, float a); - - /** - * Returns the color used for framing bar color instead of the one in the Blender file's scenes. - * \param r Red component of the override color. - * \param g Green component of the override color. - * \param b Blue component of the override color. - */ - void GetOverrideFrameColor(float& r, float& g, float& b, float& a) const; - - KX_Scene* CreateScene(const STR_String& scenename); - KX_Scene* CreateScene(Scene *scene, bool libloading=false); - - GlobalSettings* GetGlobalSettings(void); - void SetGlobalSettings(GlobalSettings* gs); - - /** - * Invalidate all the camera matrices and handle other - * needed changes when resized. - * It's only called from Blenderplayer. - */ - void Resize(); - -protected: - /** - * Processes all scheduled scene activity. - * At the end, if the scene lists have changed, - * SceneListsChanged(void) is called. - * \see SceneListsChanged(void). - */ - void ProcessScheduledScenes(void); - - /** - * This method is invoked when the scene lists have changed. - */ - - void RemoveScheduledScenes(void); - void AddScheduledScenes(void); - void ReplaceScheduledScenes(void); - void PostProcessScene(class KX_Scene* scene); - - bool BeginFrame(); - void ClearFrame(); - void EndFrame(); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_KetsjiEngine") -#endif -}; - -#endif /* __KX_KETSJIENGINE_H__ */ diff --git a/source/gameengine/Ketsji/KX_Light.cpp b/source/gameengine/Ketsji/KX_Light.cpp deleted file mode 100644 index fcdcdf4a02a..00000000000 --- a/source/gameengine/Ketsji/KX_Light.cpp +++ /dev/null @@ -1,479 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_Light.cpp - * \ingroup ketsji - */ - -#ifdef _MSC_VER -# pragma warning (disable:4786) -#endif - -#include -#include "DNA_scene_types.h" - -#include "KX_Light.h" -#include "KX_Camera.h" -#include "RAS_IRasterizer.h" -#include "RAS_ICanvas.h" -#include "RAS_ILightObject.h" - -#include "KX_PyMath.h" - -#include "DNA_object_types.h" -#include "DNA_lamp_types.h" - -#include "BKE_scene.h" -#include "MEM_guardedalloc.h" - -#include "BLI_math.h" - -KX_LightObject::KX_LightObject(void* sgReplicationInfo,SG_Callbacks callbacks, - RAS_IRasterizer* rasterizer, - RAS_ILightObject* lightobj, - bool glsl) - : KX_GameObject(sgReplicationInfo,callbacks), - m_rasterizer(rasterizer) -{ - m_lightobj = lightobj; - m_lightobj->m_scene = sgReplicationInfo; - m_lightobj->m_light = this; - m_rasterizer->AddLight(m_lightobj); - m_lightobj->m_glsl = glsl; - m_blenderscene = ((KX_Scene*)sgReplicationInfo)->GetBlenderScene(); -}; - - -KX_LightObject::~KX_LightObject() -{ - if (m_lightobj) { - m_rasterizer->RemoveLight(m_lightobj); - delete(m_lightobj); - } -} - - -CValue* KX_LightObject::GetReplica() -{ - - KX_LightObject* replica = new KX_LightObject(*this); - - replica->ProcessReplica(); - - replica->m_lightobj = m_lightobj->Clone(); - replica->m_lightobj->m_light = replica; - m_rasterizer->AddLight(replica->m_lightobj); - - return replica; -} - -void KX_LightObject::UpdateScene(KX_Scene *kxscene) -{ - m_lightobj->m_scene = (void*)kxscene; - m_blenderscene = kxscene->GetBlenderScene(); -} - -void KX_LightObject::SetLayer(int layer) -{ - KX_GameObject::SetLayer(layer); - m_lightobj->m_layer = layer; -} - -#ifdef WITH_PYTHON -/* ------------------------------------------------------------------------- */ -/* Python Integration Hooks */ -/* ------------------------------------------------------------------------- */ - -PyTypeObject KX_LightObject::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_LightObject", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0, - &KX_GameObject::Sequence, - &KX_GameObject::Mapping, - 0,0,0, - NULL, - NULL, - 0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &KX_GameObject::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_LightObject::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_LightObject::Attributes[] = { - KX_PYATTRIBUTE_RW_FUNCTION("layer", KX_LightObject, pyattr_get_layer, pyattr_set_layer), - KX_PYATTRIBUTE_RW_FUNCTION("energy", KX_LightObject, pyattr_get_energy, pyattr_set_energy), - KX_PYATTRIBUTE_RW_FUNCTION("distance", KX_LightObject, pyattr_get_distance, pyattr_set_distance), - KX_PYATTRIBUTE_RW_FUNCTION("color", KX_LightObject, pyattr_get_color, pyattr_set_color), - KX_PYATTRIBUTE_RW_FUNCTION("lin_attenuation", KX_LightObject, pyattr_get_lin_attenuation, pyattr_set_lin_attenuation), - KX_PYATTRIBUTE_RW_FUNCTION("quad_attenuation", KX_LightObject, pyattr_get_quad_attenuation, pyattr_set_quad_attenuation), - KX_PYATTRIBUTE_RW_FUNCTION("spotsize", KX_LightObject, pyattr_get_spotsize, pyattr_set_spotsize), - KX_PYATTRIBUTE_RW_FUNCTION("spotblend", KX_LightObject, pyattr_get_spotblend, pyattr_set_spotblend), - KX_PYATTRIBUTE_RO_FUNCTION("shadowClipStart", KX_LightObject, pyattr_get_shadow_clip_start), - KX_PYATTRIBUTE_RO_FUNCTION("shadowClipEnd", KX_LightObject, pyattr_get_shadow_clip_end), - KX_PYATTRIBUTE_RO_FUNCTION("shadowFrustumSize", KX_LightObject, pyattr_get_shadow_frustum_size), - KX_PYATTRIBUTE_RO_FUNCTION("shadowBias", KX_LightObject, pyattr_get_shadow_bias), - KX_PYATTRIBUTE_RO_FUNCTION("shadowBleedBias", KX_LightObject, pyattr_get_shadow_bleed_bias), - KX_PYATTRIBUTE_RO_FUNCTION("shadowBindId", KX_LightObject, pyattr_get_shadow_bind_code), - KX_PYATTRIBUTE_RO_FUNCTION("shadowMapType", KX_LightObject, pyattr_get_shadow_map_type), - KX_PYATTRIBUTE_RO_FUNCTION("shadowColor", KX_LightObject, pyattr_get_shadow_color), - KX_PYATTRIBUTE_RO_FUNCTION("useShadow", KX_LightObject, pyattr_get_shadow_active), - KX_PYATTRIBUTE_RO_FUNCTION("shadowMatrix", KX_LightObject, pyattr_get_shadow_matrix), - KX_PYATTRIBUTE_RO_FUNCTION("SPOT", KX_LightObject, pyattr_get_typeconst), - KX_PYATTRIBUTE_RO_FUNCTION("SUN", KX_LightObject, pyattr_get_typeconst), - KX_PYATTRIBUTE_RO_FUNCTION("NORMAL", KX_LightObject, pyattr_get_typeconst), - KX_PYATTRIBUTE_RW_FUNCTION("type", KX_LightObject, pyattr_get_type, pyattr_set_type), - { NULL } //Sentinel -}; - -PyObject *KX_LightObject::pyattr_get_layer(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_LightObject *self = static_cast(self_v); - return PyLong_FromLong(self->m_lightobj->m_layer); -} - -int KX_LightObject::pyattr_set_layer(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_LightObject *self = static_cast(self_v); - int layer = PyLong_AsLong(value); - - if (layer == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_TypeError, "expected an integer for attribute \"%s\"", attrdef->m_name); - return PY_SET_ATTR_FAIL; - } - - if (layer < 1) { - PyErr_Format(PyExc_TypeError, "expected an integer greater than 1 for attribute \"%s\"", attrdef->m_name); - return PY_SET_ATTR_FAIL; - } - else if (layer > MAX_LIGHT_LAYERS) { - PyErr_Format(PyExc_TypeError, "expected an integer less than %i for attribute \"%s\"", MAX_LIGHT_LAYERS, attrdef->m_name); - return PY_SET_ATTR_FAIL; - } - - self->SetLayer(layer); - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_LightObject::pyattr_get_energy(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_LightObject* self = static_cast(self_v); - return PyFloat_FromDouble(self->m_lightobj->m_energy); -} - -int KX_LightObject::pyattr_set_energy(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_LightObject* self = static_cast(self_v); - - if (PyFloat_Check(value)) { - float val = PyFloat_AsDouble(value); - if (val < 0) - val = 0; - else if (val > 10) - val = 10; - - self->m_lightobj->m_energy = val; - return PY_SET_ATTR_SUCCESS; - } - - PyErr_Format(PyExc_TypeError, "expected float value for attribute \"%s\"", attrdef->m_name); - return PY_SET_ATTR_FAIL; -} - -PyObject *KX_LightObject::pyattr_get_shadow_clip_start(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_LightObject *self = static_cast(self_v); - return PyFloat_FromDouble(self->m_lightobj->m_shadowclipstart); -} - -PyObject *KX_LightObject::pyattr_get_shadow_clip_end(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_LightObject *self = static_cast(self_v); - return PyFloat_FromDouble(self->m_lightobj->m_shadowclipend); -} - -PyObject *KX_LightObject::pyattr_get_shadow_frustum_size(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_LightObject *self = static_cast(self_v); - return PyFloat_FromDouble(self->m_lightobj->m_shadowfrustumsize); -} - -PyObject *KX_LightObject::pyattr_get_shadow_bind_code(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_LightObject *self = static_cast(self_v); - return PyLong_FromLong(self->m_lightobj->GetShadowBindCode()); -} - -PyObject *KX_LightObject::pyattr_get_shadow_bias(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_LightObject *self = static_cast(self_v); - return PyFloat_FromDouble(self->m_lightobj->m_shadowbias); -} - -PyObject *KX_LightObject::pyattr_get_shadow_bleed_bias(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_LightObject *self = static_cast(self_v); - return PyFloat_FromDouble(self->m_lightobj->m_shadowbleedbias); -} - -PyObject *KX_LightObject::pyattr_get_shadow_map_type(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_LightObject *self = static_cast(self_v); - return PyLong_FromLong(self->m_lightobj->m_shadowmaptype); -} - -PyObject *KX_LightObject::pyattr_get_shadow_matrix(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_LightObject *self = static_cast(self_v); - return PyObjectFrom(self->m_lightobj->GetShadowMatrix()); -} - -PyObject *KX_LightObject::pyattr_get_shadow_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_LightObject *self = static_cast(self_v); - return PyColorFromVector(MT_Vector3(self->m_lightobj->m_shadowcolor)); -} - -PyObject *KX_LightObject::pyattr_get_shadow_active(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_LightObject *self = static_cast(self_v); - return PyBool_FromLong(self->m_lightobj->HasShadowBuffer()); -} - -PyObject *KX_LightObject::pyattr_get_distance(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_LightObject* self = static_cast(self_v); - return PyFloat_FromDouble(self->m_lightobj->m_distance); -} - -int KX_LightObject::pyattr_set_distance(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_LightObject* self = static_cast(self_v); - - if (PyFloat_Check(value)) { - float val = PyFloat_AsDouble(value); - if (val < 0.01f) - val = 0.01f; - else if (val > 5000.f) - val = 5000.f; - - self->m_lightobj->m_distance = val; - return PY_SET_ATTR_SUCCESS; - } - - PyErr_Format(PyExc_TypeError, "expected float value for attribute \"%s\"", attrdef->m_name); - return PY_SET_ATTR_FAIL; -} - -PyObject *KX_LightObject::pyattr_get_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_LightObject* self = static_cast(self_v); - return Py_BuildValue("[fff]", self->m_lightobj->m_color[0], self->m_lightobj->m_color[1], self->m_lightobj->m_color[2]); -} - -int KX_LightObject::pyattr_set_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_LightObject* self = static_cast(self_v); - - MT_Vector3 color; - if (PyVecTo(value, color)) - { - self->m_lightobj->m_color[0] = color[0]; - self->m_lightobj->m_color[1] = color[1]; - self->m_lightobj->m_color[2] = color[2]; - return PY_SET_ATTR_SUCCESS; - } - return PY_SET_ATTR_FAIL; -} - -PyObject *KX_LightObject::pyattr_get_lin_attenuation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_LightObject* self = static_cast(self_v); - return PyFloat_FromDouble(self->m_lightobj->m_att1); -} - -int KX_LightObject::pyattr_set_lin_attenuation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_LightObject* self = static_cast(self_v); - - if (PyFloat_Check(value)) { - float val = PyFloat_AsDouble(value); - if (val < 0.f) - val = 0.f; - else if (val > 1.f) - val = 1.f; - - self->m_lightobj->m_att1 = val; - return PY_SET_ATTR_SUCCESS; - } - - PyErr_Format(PyExc_TypeError, "expected float value for attribute \"%s\"", attrdef->m_name); - return PY_SET_ATTR_FAIL; -} - -PyObject *KX_LightObject::pyattr_get_quad_attenuation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_LightObject* self = static_cast(self_v); - return PyFloat_FromDouble(self->m_lightobj->m_att2); -} - -int KX_LightObject::pyattr_set_quad_attenuation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_LightObject* self = static_cast(self_v); - - if (PyFloat_Check(value)) { - float val = PyFloat_AsDouble(value); - if (val < 0.f) - val = 0.f; - else if (val > 1.f) - val = 1.f; - - self->m_lightobj->m_att2 = val; - return PY_SET_ATTR_SUCCESS; - } - - PyErr_Format(PyExc_TypeError, "expected float value for attribute \"%s\"", attrdef->m_name); - return PY_SET_ATTR_FAIL; -} - -PyObject *KX_LightObject::pyattr_get_spotsize(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_LightObject* self = static_cast(self_v); - return PyFloat_FromDouble(RAD2DEG(self->m_lightobj->m_spotsize)); -} - -int KX_LightObject::pyattr_set_spotsize(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_LightObject* self = static_cast(self_v); - - if (PyFloat_Check(value)) { - double val = PyFloat_AsDouble(value); - if (val < 0.0) - val = 0.0; - else if (val > 180.0) - val = 180.0; - - self->m_lightobj->m_spotsize = (float)DEG2RAD(val); - return PY_SET_ATTR_SUCCESS; - } - - PyErr_Format(PyExc_TypeError, "expected float value for attribute \"%s\"", attrdef->m_name); - return PY_SET_ATTR_FAIL; -} -PyObject *KX_LightObject::pyattr_get_spotblend(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_LightObject* self = static_cast(self_v); - return PyFloat_FromDouble(self->m_lightobj->m_spotblend); -} - -int KX_LightObject::pyattr_set_spotblend(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_LightObject* self = static_cast(self_v); - - if (PyFloat_Check(value)) { - float val = (float)PyFloat_AsDouble(value); - if (val < 0.f) - val = 0.f; - else if (val > 1.f) - val = 1.f; - - self->m_lightobj->m_spotblend = val; - return PY_SET_ATTR_SUCCESS; - } - - PyErr_Format(PyExc_TypeError, "expected float value for attribute \"%s\"", attrdef->m_name); - return PY_SET_ATTR_FAIL; -} - -PyObject *KX_LightObject::pyattr_get_typeconst(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - PyObject *retvalue; - - const char* type = attrdef->m_name; - - if (!strcmp(type, "SPOT")) { - retvalue = PyLong_FromLong(RAS_ILightObject::LIGHT_SPOT); - } else if (!strcmp(type, "SUN")) { - retvalue = PyLong_FromLong(RAS_ILightObject::LIGHT_SUN); - } else if (!strcmp(type, "NORMAL")) { - retvalue = PyLong_FromLong(RAS_ILightObject::LIGHT_NORMAL); - } - else { - /* should never happen */ - PyErr_SetString(PyExc_TypeError, "light.type: internal error, invalid light type"); - retvalue = NULL; - } - - return retvalue; -} - -PyObject *KX_LightObject::pyattr_get_type(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_LightObject* self = static_cast(self_v); - return PyLong_FromLong(self->m_lightobj->m_type); -} - -int KX_LightObject::pyattr_set_type(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_LightObject* self = static_cast(self_v); - const int val = PyLong_AsLong(value); - if ((val==-1 && PyErr_Occurred()) || val<0 || val>2) { - PyErr_SetString(PyExc_ValueError, "light.type= val: KX_LightObject, expected an int between 0 and 2"); - return PY_SET_ATTR_FAIL; - } - - switch (val) { - case 0: - self->m_lightobj->m_type = self->m_lightobj->LIGHT_SPOT; - break; - case 1: - self->m_lightobj->m_type = self->m_lightobj->LIGHT_SUN; - break; - case 2: - self->m_lightobj->m_type = self->m_lightobj->LIGHT_NORMAL; - break; - } - - return PY_SET_ATTR_SUCCESS; -} -#endif // WITH_PYTHON diff --git a/source/gameengine/Ketsji/KX_Light.h b/source/gameengine/Ketsji/KX_Light.h deleted file mode 100644 index b354fca4d41..00000000000 --- a/source/gameengine/Ketsji/KX_Light.h +++ /dev/null @@ -1,100 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_Light.h - * \ingroup ketsji - */ - -#ifndef __KX_LIGHT_H__ -#define __KX_LIGHT_H__ - -#include "KX_GameObject.h" - -#define MAX_LIGHT_LAYERS ((1 << 20) - 1) - -struct GPULamp; -struct Scene; -struct Base; -class KX_Camera; -class RAS_IRasterizer; -class RAS_ILightObject; -class MT_Transform; - -class KX_LightObject : public KX_GameObject -{ - Py_Header -protected: - RAS_ILightObject* m_lightobj; - class RAS_IRasterizer* m_rasterizer; //needed for registering and replication of lightobj - Scene* m_blenderscene; - -public: - KX_LightObject(void* sgReplicationInfo,SG_Callbacks callbacks,RAS_IRasterizer* rasterizer,RAS_ILightObject* lightobj, bool glsl); - virtual ~KX_LightObject(); - virtual CValue* GetReplica(); - RAS_ILightObject* GetLightData() { return m_lightobj;} - - void UpdateScene(class KX_Scene *kxscene); - virtual void SetLayer(int layer); - - virtual int GetGameObjectType() { return OBJ_LIGHT; } - -#ifdef WITH_PYTHON - /* attributes */ - static PyObject* pyattr_get_layer(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_layer(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_energy(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_energy(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject *pyattr_get_shadow_clip_start(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_shadow_clip_end(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_shadow_frustum_size(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_shadow_bind_code(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_shadow_bias(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_shadow_bleed_bias(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_shadow_map_type(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_shadow_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_shadow_active(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_shadow_matrix(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_distance(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_distance(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_color(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_color(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_lin_attenuation(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_lin_attenuation(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_quad_attenuation(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_quad_attenuation(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_spotsize(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_spotsize(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_spotblend(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_spotblend(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_typeconst(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_type(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_type(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); -#endif -}; - -#endif /* __KX_LIGHT_H__ */ diff --git a/source/gameengine/Ketsji/KX_LightIpoSGController.cpp b/source/gameengine/Ketsji/KX_LightIpoSGController.cpp deleted file mode 100644 index 6b641f7a63f..00000000000 --- a/source/gameengine/Ketsji/KX_LightIpoSGController.cpp +++ /dev/null @@ -1,122 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_LightIpoSGController.cpp - * \ingroup ketsji - */ - - -#include "KX_LightIpoSGController.h" -#include "KX_ScalarInterpolator.h" -#include "KX_Light.h" -#include "RAS_ILightObject.h" - -#if defined(_WIN64) -typedef unsigned __int64 uint_ptr; -#else -typedef unsigned long uint_ptr; -#endif - -bool KX_LightIpoSGController::Update(double currentTime) -{ - if (m_modified) - { - T_InterpolatorList::iterator i; - for (i = m_interpolators.begin(); !(i == m_interpolators.end()); ++i) { - (*i)->Execute(m_ipotime);//currentTime); - } - - RAS_ILightObject *lightobj; - - SG_Spatial* ob = (SG_Spatial*)m_pObject; - KX_LightObject* kxlight = (KX_LightObject*) ob->GetSGClientObject(); - lightobj = kxlight->GetLightData(); - //lightobj = (KX_Light*) - - if (m_modify_energy) { - lightobj->m_energy = m_energy; - } - - if (m_modify_color) { - lightobj->m_color[0] = m_col_rgb[0]; - lightobj->m_color[1] = m_col_rgb[1]; - lightobj->m_color[2] = m_col_rgb[2]; - } - - if (m_modify_dist) { - lightobj->m_distance = m_dist; - } - - m_modified=false; - } - return false; -} - - -void KX_LightIpoSGController::AddInterpolator(KX_IInterpolator* interp) -{ - this->m_interpolators.push_back(interp); -} - -SG_Controller* KX_LightIpoSGController::GetReplica(class SG_Node* destnode) -{ - KX_LightIpoSGController* iporeplica = new KX_LightIpoSGController(*this); - // clear object that ipo acts on - iporeplica->ClearObject(); - - // dirty hack, ask Gino for a better solution in the ipo implementation - // hacken en zagen, in what we call datahiding, not written for replication :( - - T_InterpolatorList oldlist = m_interpolators; - iporeplica->m_interpolators.clear(); - - T_InterpolatorList::iterator i; - for (i = oldlist.begin(); !(i == oldlist.end()); ++i) { - KX_ScalarInterpolator* copyipo = new KX_ScalarInterpolator(*((KX_ScalarInterpolator*)*i)); - iporeplica->AddInterpolator(copyipo); - - MT_Scalar* scaal = ((KX_ScalarInterpolator*)*i)->GetTarget(); - uint_ptr orgbase = (uint_ptr)this; - uint_ptr orgloc = (uint_ptr)scaal; - uint_ptr offset = orgloc-orgbase; - uint_ptr newaddrbase = (uint_ptr)iporeplica + offset; - MT_Scalar* blaptr = (MT_Scalar*) newaddrbase; - copyipo->SetNewTarget((MT_Scalar*)blaptr); - } - - return iporeplica; -} - -KX_LightIpoSGController::~KX_LightIpoSGController() -{ - - T_InterpolatorList::iterator i; - for (i = m_interpolators.begin(); !(i == m_interpolators.end()); ++i) { - delete (*i); - } - -} diff --git a/source/gameengine/Ketsji/KX_LightIpoSGController.h b/source/gameengine/Ketsji/KX_LightIpoSGController.h deleted file mode 100644 index 151ced6b8f8..00000000000 --- a/source/gameengine/Ketsji/KX_LightIpoSGController.h +++ /dev/null @@ -1,105 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_LightIpoSGController.h - * \ingroup ketsji - */ - -#ifndef __KX_LIGHTIPOSGCONTROLLER_H__ -#define __KX_LIGHTIPOSGCONTROLLER_H__ - -#include "SG_Controller.h" -#include "SG_Spatial.h" - -#include "KX_IInterpolator.h" - -class RAS_ILightObject; - -class KX_LightIpoSGController : public SG_Controller -{ -public: - MT_Scalar m_energy; - MT_Scalar m_col_rgb[3]; - MT_Scalar m_dist; - -private: - T_InterpolatorList m_interpolators; - unsigned short m_modify_energy : 1; - unsigned short m_modify_color : 1; - unsigned short m_modify_dist : 1; - bool m_modified; - - double m_ipotime; -public: - KX_LightIpoSGController() : - m_modify_energy(false), - m_modify_color(false), - m_modify_dist(false), - m_modified(true), - m_ipotime(0.0) - {} - - virtual ~KX_LightIpoSGController(); - - virtual SG_Controller* GetReplica(class SG_Node* destnode); - - virtual bool Update(double time); - - virtual void SetSimulatedTime(double time) { - m_ipotime = time; - m_modified = true; - } - - void SetModifyEnergy(bool modify) { - m_modify_energy = modify; - } - - void SetModifyColor(bool modify) { - m_modify_color = modify; - } - - void SetModifyDist(bool modify) { - m_modify_dist = modify; - } - - void - SetOption( - int option, - int value - ) { - // intentionally empty - }; - - void AddInterpolator(KX_IInterpolator* interp); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_LightIpoSGController") -#endif -}; - -#endif /* __KX_LIGHTIPOSGCONTROLLER_H__ */ diff --git a/source/gameengine/Ketsji/KX_MaterialIpoController.cpp b/source/gameengine/Ketsji/KX_MaterialIpoController.cpp deleted file mode 100644 index 1faf8f17d54..00000000000 --- a/source/gameengine/Ketsji/KX_MaterialIpoController.cpp +++ /dev/null @@ -1,105 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_MaterialIpoController.cpp - * \ingroup ketsji - */ - -#include "KX_MaterialIpoController.h" -#include "KX_ScalarInterpolator.h" -#include "KX_GameObject.h" - -#include "BLI_sys_types.h" // for intptr_t support - -bool KX_MaterialIpoController::Update(double currentTime) -{ - if (m_modified) - { - T_InterpolatorList::iterator i; - for (i = m_interpolators.begin(); !(i == m_interpolators.end()); ++i) { - (*i)->Execute(m_ipotime); - } - - - SG_Spatial* ob = (SG_Spatial*)m_pObject; - KX_GameObject* kxgameobj= (KX_GameObject*) ob->GetSGClientObject(); - - //kxgameobj->SetObjectColor(m_rgba); - kxgameobj->UpdateMaterialData( - m_matname_hash, - m_rgba, - m_specrgb, - m_hard, - m_spec, - m_ref, - m_emit, - m_alpha - ); - - m_modified=false; - } - return false; -} - - -void KX_MaterialIpoController::AddInterpolator(KX_IInterpolator* interp) -{ - this->m_interpolators.push_back(interp); -} - -SG_Controller* KX_MaterialIpoController::GetReplica(class SG_Node* destnode) -{ - KX_MaterialIpoController* iporeplica = new KX_MaterialIpoController(*this); - // clear object that ipo acts on - iporeplica->ClearObject(); - - // dirty hack, ask Gino for a better solution in the ipo implementation - // hacken en zagen, in what we call datahiding, not written for replication :( - - T_InterpolatorList oldlist = m_interpolators; - iporeplica->m_interpolators.clear(); - - T_InterpolatorList::iterator i; - for (i = oldlist.begin(); !(i == oldlist.end()); ++i) { - KX_ScalarInterpolator* copyipo = new KX_ScalarInterpolator(*((KX_ScalarInterpolator*)*i)); - iporeplica->AddInterpolator(copyipo); - - MT_Scalar* scaal = ((KX_ScalarInterpolator*)*i)->GetTarget(); - intptr_t orgbase = (intptr_t)this; - intptr_t orgloc = (intptr_t)scaal; - intptr_t offset = orgloc-orgbase; - intptr_t newaddrbase = (intptr_t)iporeplica + offset; - MT_Scalar* blaptr = (MT_Scalar*) newaddrbase; - copyipo->SetNewTarget((MT_Scalar*)blaptr); - } - - return iporeplica; -} - -KX_MaterialIpoController::~KX_MaterialIpoController() -{ - - T_InterpolatorList::iterator i; - for (i = m_interpolators.begin(); !(i == m_interpolators.end()); ++i) { - delete (*i); - } - -} - diff --git a/source/gameengine/Ketsji/KX_MaterialIpoController.h b/source/gameengine/Ketsji/KX_MaterialIpoController.h deleted file mode 100644 index a7e9c2cc1c5..00000000000 --- a/source/gameengine/Ketsji/KX_MaterialIpoController.h +++ /dev/null @@ -1,65 +0,0 @@ - -/** \file KX_MaterialIpoController.h - * \ingroup ketsji - */ - -#ifndef __KX_MATERIALIPOCONTROLLER_H__ -#define __KX_MATERIALIPOCONTROLLER_H__ - - - -#include "SG_Controller.h" -#include "SG_Spatial.h" -#include "KX_IInterpolator.h" - -#include "STR_String.h" //typedef dword - -class KX_MaterialIpoController : public SG_Controller -{ -public: - MT_Vector4 m_rgba; - MT_Vector3 m_specrgb; - MT_Scalar m_hard; - MT_Scalar m_spec; - MT_Scalar m_ref; - MT_Scalar m_emit; - MT_Scalar m_alpha; - -private: - T_InterpolatorList m_interpolators; - bool m_modified; - - double m_ipotime; - dword m_matname_hash; -public: - KX_MaterialIpoController(dword matname_hash) : - m_modified(true), - m_ipotime(0.0), - m_matname_hash(matname_hash) - {} - virtual ~KX_MaterialIpoController(); - virtual SG_Controller* GetReplica(class SG_Node* destnode); - virtual bool Update(double time); - virtual void SetSimulatedTime(double time) { - m_ipotime = time; - m_modified = true; - } - - void - SetOption( - int option, - int value - ) { - // intentionally empty - }; - - - void AddInterpolator(KX_IInterpolator* interp); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_MaterialIpoController") -#endif -}; - -#endif /* __KX_MATERIALIPOCONTROLLER_H__ */ diff --git a/source/gameengine/Ketsji/KX_MeshProxy.cpp b/source/gameengine/Ketsji/KX_MeshProxy.cpp deleted file mode 100644 index 8da3542b4d6..00000000000 --- a/source/gameengine/Ketsji/KX_MeshProxy.cpp +++ /dev/null @@ -1,464 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_MeshProxy.cpp - * \ingroup ketsji - */ - - -#ifdef WITH_PYTHON - -#include "KX_MeshProxy.h" -#include "RAS_IPolygonMaterial.h" -#include "RAS_MeshObject.h" - -#include "KX_VertexProxy.h" -#include "KX_PolyProxy.h" - -#include "KX_BlenderMaterial.h" - -#include "KX_PyMath.h" - -#include "SCA_LogicManager.h" - -#include "EXP_PyObjectPlus.h" - -PyTypeObject KX_MeshProxy::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_MeshProxy", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &CValue::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_MeshProxy::Methods[] = { - {"getMaterialName", (PyCFunction)KX_MeshProxy::sPyGetMaterialName,METH_VARARGS}, - {"getTextureName", (PyCFunction)KX_MeshProxy::sPyGetTextureName,METH_VARARGS}, - {"getVertexArrayLength", (PyCFunction)KX_MeshProxy::sPyGetVertexArrayLength,METH_VARARGS}, - {"getVertex", (PyCFunction)KX_MeshProxy::sPyGetVertex,METH_VARARGS}, - {"getPolygon", (PyCFunction)KX_MeshProxy::sPyGetPolygon,METH_VARARGS}, - {"transform", (PyCFunction)KX_MeshProxy::sPyTransform,METH_VARARGS}, - {"transformUV", (PyCFunction)KX_MeshProxy::sPyTransformUV,METH_VARARGS}, - //{"getIndexArrayLength", (PyCFunction)KX_MeshProxy::sPyGetIndexArrayLength,METH_VARARGS}, - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_MeshProxy::Attributes[] = { - KX_PYATTRIBUTE_RO_FUNCTION("materials", KX_MeshProxy, pyattr_get_materials), - KX_PYATTRIBUTE_RO_FUNCTION("numPolygons", KX_MeshProxy, pyattr_get_numPolygons), - KX_PYATTRIBUTE_RO_FUNCTION("numMaterials", KX_MeshProxy, pyattr_get_numMaterials), - - { NULL } //Sentinel -}; - -void KX_MeshProxy::SetMeshModified(bool v) -{ - m_meshobj->SetMeshModified(v); -} - -KX_MeshProxy::KX_MeshProxy(RAS_MeshObject* mesh) - : CValue(), m_meshobj(mesh) -{ -} - -KX_MeshProxy::~KX_MeshProxy() -{ -} - - - -// stuff for cvalue related things -CValue* KX_MeshProxy::Calc(VALUE_OPERATOR op, CValue *val) { return NULL;} -CValue* KX_MeshProxy::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val) { return NULL;} - -const STR_String & KX_MeshProxy::GetText() {return m_meshobj->GetName();}; -double KX_MeshProxy::GetNumber() { return -1;} -STR_String& KX_MeshProxy::GetName() { return m_meshobj->GetName();} -void KX_MeshProxy::SetName(const char *name) { }; -CValue* KX_MeshProxy::GetReplica() { return NULL;} - - -// stuff for python integration - -PyObject *KX_MeshProxy::PyGetMaterialName(PyObject *args, PyObject *kwds) -{ - int matid= 1; - STR_String matname; - - if (PyArg_ParseTuple(args,"i:getMaterialName",&matid)) - { - matname = m_meshobj->GetMaterialName(matid); - } - else { - return NULL; - } - - return PyUnicode_From_STR_String(matname); - -} - - -PyObject *KX_MeshProxy::PyGetTextureName(PyObject *args, PyObject *kwds) -{ - int matid= 1; - STR_String matname; - - if (PyArg_ParseTuple(args,"i:getTextureName",&matid)) - { - matname = m_meshobj->GetTextureName(matid); - } - else { - return NULL; - } - - return PyUnicode_From_STR_String(matname); - -} - -PyObject *KX_MeshProxy::PyGetVertexArrayLength(PyObject *args, PyObject *kwds) -{ - int matid= 0; - int length = 0; - - - if (!PyArg_ParseTuple(args,"i:getVertexArrayLength",&matid)) - return NULL; - - - RAS_MeshMaterial *mmat = m_meshobj->GetMeshMaterial(matid); /* can be NULL*/ - - if (mmat) - { - RAS_IPolyMaterial* mat = mmat->m_bucket->GetPolyMaterial(); - if (mat) - length = m_meshobj->NumVertices(mat); - } - - return PyLong_FromLong(length); -} - - -PyObject *KX_MeshProxy::PyGetVertex(PyObject *args, PyObject *kwds) -{ - int vertexindex; - int matindex; - - if (!PyArg_ParseTuple(args,"ii:getVertex",&matindex,&vertexindex)) - return NULL; - - RAS_TexVert* vertex = m_meshobj->GetVertex(matindex,vertexindex); - - if (vertex==NULL) { - PyErr_SetString(PyExc_ValueError, "mesh.getVertex(mat_idx, vert_idx): KX_MeshProxy, could not get a vertex at the given indices"); - return NULL; - } - - return (new KX_VertexProxy(this, vertex))->NewProxy(true); -} - -PyObject *KX_MeshProxy::PyGetPolygon(PyObject *args, PyObject *kwds) -{ - int polyindex= 1; - PyObject *polyob = NULL; - - if (!PyArg_ParseTuple(args,"i:getPolygon",&polyindex)) - return NULL; - - if (polyindex<0 || polyindex >= m_meshobj->NumPolygons()) - { - PyErr_SetString(PyExc_AttributeError, "mesh.getPolygon(int): KX_MeshProxy, invalid polygon index"); - return NULL; - } - - - RAS_Polygon* polygon = m_meshobj->GetPolygon(polyindex); - if (polygon) - { - polyob = (new KX_PolyProxy(m_meshobj, polygon))->NewProxy(true); - } - else { - PyErr_SetString(PyExc_AttributeError, "mesh.getPolygon(int): KX_MeshProxy, polygon is NULL, unknown reason"); - } - return polyob; -} - -PyObject *KX_MeshProxy::PyTransform(PyObject *args, PyObject *kwds) -{ - int matindex; - PyObject *pymat; - bool ok = false; - - MT_Matrix4x4 transform; - - if (!PyArg_ParseTuple(args,"iO:transform", &matindex, &pymat) || - !PyMatTo(pymat, transform)) - { - return NULL; - } - - MT_Matrix4x4 ntransform = transform.inverse().transposed(); - ntransform[0][3] = ntransform[1][3] = ntransform[2][3] = 0.0f; - - /* transform mesh verts */ - unsigned int mit_index = 0; - for (list::iterator mit = m_meshobj->GetFirstMaterial(); - (mit != m_meshobj->GetLastMaterial()); - ++mit, ++mit_index) - { - if (matindex == -1) { - /* always transform */ - } - else if (matindex == mit_index) { - /* we found the right index! */ - } - else { - continue; - } - - RAS_MeshSlot *slot = mit->m_baseslot; - RAS_MeshSlot::iterator it; - ok = true; - - for (slot->begin(it); !slot->end(it); slot->next(it)) { - size_t i; - for (i = it.startvertex; i < it.endvertex; i++) { - RAS_TexVert *vert = &it.vertex[i]; - vert->Transform(transform, ntransform); - } - } - - /* if we set a material index, quit when done */ - if (matindex == mit_index) { - break; - } - } - - if (ok == false) { - PyErr_Format(PyExc_ValueError, - "mesh.transform(...): invalid material index %d", matindex); - return NULL; - } - - m_meshobj->SetMeshModified(true); - - Py_RETURN_NONE; -} - -PyObject *KX_MeshProxy::PyTransformUV(PyObject *args, PyObject *kwds) -{ - int matindex; - PyObject *pymat; - int uvindex = -1; - int uvindex_from = -1; - bool ok = false; - - MT_Matrix4x4 transform; - - if (!PyArg_ParseTuple(args,"iO|iii:transformUV", &matindex, &pymat, &uvindex, &uvindex_from) || - !PyMatTo(pymat, transform)) - { - return NULL; - } - - if (uvindex < -1 || uvindex > 1) { - PyErr_Format(PyExc_ValueError, - "mesh.transformUV(...): invalid uv_index %d", uvindex); - return NULL; - } - if (uvindex_from < -1 || uvindex_from > 1) { - PyErr_Format(PyExc_ValueError, - "mesh.transformUV(...): invalid uv_index_from %d", uvindex); - return NULL; - } - if (uvindex_from == uvindex) { - uvindex_from = -1; - } - - /* transform mesh verts */ - unsigned int mit_index = 0; - for (list::iterator mit = m_meshobj->GetFirstMaterial(); - (mit != m_meshobj->GetLastMaterial()); - ++mit, ++mit_index) - { - if (matindex == -1) { - /* always transform */ - } - else if (matindex == mit_index) { - /* we found the right index! */ - } - else { - continue; - } - - RAS_MeshSlot *slot = mit->m_baseslot; - RAS_MeshSlot::iterator it; - ok = true; - - for (slot->begin(it); !slot->end(it); slot->next(it)) { - size_t i; - - for (i = it.startvertex; i < it.endvertex; i++) { - RAS_TexVert *vert = &it.vertex[i]; - if (uvindex_from != -1) { - if (uvindex_from == 0) vert->SetUV(1, vert->getUV(0)); - else vert->SetUV(0, vert->getUV(1)); - } - - switch (uvindex) { - case 0: - vert->TransformUV(0, transform); - break; - case 1: - vert->TransformUV(1, transform); - break; - case -1: - vert->TransformUV(0, transform); - vert->TransformUV(1, transform); - break; - } - } - } - - /* if we set a material index, quit when done */ - if (matindex == mit_index) { - break; - } - } - - if (ok == false) { - PyErr_Format(PyExc_ValueError, - "mesh.transformUV(...): invalid material index %d", matindex); - return NULL; - } - - m_meshobj->SetMeshModified(true); - - Py_RETURN_NONE; -} - -PyObject *KX_MeshProxy::pyattr_get_materials(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_MeshProxy* self = static_cast(self_v); - - int tot= self->m_meshobj->NumMaterials(); - int i; - - PyObject *materials = PyList_New( tot ); - - list::iterator mit= self->m_meshobj->GetFirstMaterial(); - - - for (i=0; im_bucket->GetPolyMaterial(); - KX_BlenderMaterial *mat = static_cast(polymat); - PyList_SET_ITEM(materials, i, mat->GetProxy()); - } - return materials; -} - -PyObject *KX_MeshProxy::pyattr_get_numMaterials(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_MeshProxy * self = static_cast (self_v); - return PyLong_FromLong(self->m_meshobj->NumMaterials()); -} - -PyObject *KX_MeshProxy::pyattr_get_numPolygons(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_MeshProxy * self = static_cast (self_v); - return PyLong_FromLong(self->m_meshobj->NumPolygons()); -} - -/* a close copy of ConvertPythonToGameObject but for meshes */ -bool ConvertPythonToMesh(SCA_LogicManager *logicmgr, PyObject *value, RAS_MeshObject **object, bool py_none_ok, const char *error_prefix) -{ - if (value==NULL) { - PyErr_Format(PyExc_TypeError, "%s, python pointer NULL, should never happen", error_prefix); - *object = NULL; - return false; - } - - if (value==Py_None) { - *object = NULL; - - if (py_none_ok) { - return true; - } else { - PyErr_Format(PyExc_TypeError, "%s, expected KX_MeshProxy or a KX_MeshProxy name, None is invalid", error_prefix); - return false; - } - } - - if (PyUnicode_Check(value)) { - *object = (RAS_MeshObject*)logicmgr->GetMeshByName(STR_String( _PyUnicode_AsString(value) )); - - if (*object) { - return true; - } else { - PyErr_Format(PyExc_ValueError, "%s, requested name \"%s\" did not match any KX_MeshProxy in this scene", error_prefix, _PyUnicode_AsString(value)); - return false; - } - } - - if (PyObject_TypeCheck(value, &KX_MeshProxy::Type)) { - KX_MeshProxy *kx_mesh = static_castBGE_PROXY_REF(value); - - /* sets the error */ - if (kx_mesh==NULL) { - PyErr_Format(PyExc_SystemError, "%s, " BGE_PROXY_ERROR_MSG, error_prefix); - return false; - } - - *object = kx_mesh->GetMesh(); - return true; - } - - *object = NULL; - - if (py_none_ok) { - PyErr_Format(PyExc_TypeError, "%s, expect a KX_MeshProxy, a string or None", error_prefix); - } else { - PyErr_Format(PyExc_TypeError, "%s, expect a KX_MeshProxy or a string", error_prefix); - } - - return false; -} - -#endif // WITH_PYTHON diff --git a/source/gameengine/Ketsji/KX_MeshProxy.h b/source/gameengine/Ketsji/KX_MeshProxy.h deleted file mode 100644 index dbd7987f785..00000000000 --- a/source/gameengine/Ketsji/KX_MeshProxy.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_MeshProxy.h - * \ingroup ketsji - */ - -#ifndef __KX_MESHPROXY_H__ -#define __KX_MESHPROXY_H__ - -#ifdef WITH_PYTHON - -#include "SCA_IObject.h" - -class SCA_LogicManager; -/* utility conversion function */ -bool ConvertPythonToMesh(SCA_LogicManager *logicmgr, PyObject *value, class RAS_MeshObject **object, bool py_none_ok, const char *error_prefix); - -class KX_MeshProxy : public CValue -{ - Py_Header - - class RAS_MeshObject* m_meshobj; -public: - KX_MeshProxy(class RAS_MeshObject* mesh); - virtual ~KX_MeshProxy(); - - void SetMeshModified(bool v); - - // stuff for cvalue related things - virtual CValue* Calc(VALUE_OPERATOR op, CValue *val); - virtual CValue* CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val); - virtual const STR_String & GetText(); - virtual double GetNumber(); - virtual RAS_MeshObject* GetMesh() { return m_meshobj; } - virtual STR_String& GetName(); - virtual void SetName(const char *name); // Set the name of the value - virtual CValue* GetReplica(); - -// stuff for python integration - - KX_PYMETHOD(KX_MeshProxy,GetNumMaterials); // Deprecated - KX_PYMETHOD(KX_MeshProxy,GetMaterialName); - KX_PYMETHOD(KX_MeshProxy,GetTextureName); - KX_PYMETHOD_NOARGS(KX_MeshProxy,GetNumPolygons); // Deprecated - - // both take materialid (int) - KX_PYMETHOD(KX_MeshProxy,GetVertexArrayLength); - KX_PYMETHOD(KX_MeshProxy,GetVertex); - KX_PYMETHOD(KX_MeshProxy,GetPolygon); - KX_PYMETHOD(KX_MeshProxy,Transform); - KX_PYMETHOD(KX_MeshProxy,TransformUV); - - static PyObject *pyattr_get_materials(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_numMaterials(void *self, const KX_PYATTRIBUTE_DEF * attrdef); - static PyObject *pyattr_get_numPolygons(void *self, const KX_PYATTRIBUTE_DEF * attrdef); -}; - -#endif /* WITH_PYTHON */ - -#endif /* __KX_MESHPROXY_H__ */ diff --git a/source/gameengine/Ketsji/KX_MotionState.cpp b/source/gameengine/Ketsji/KX_MotionState.cpp deleted file mode 100644 index 4728f71a6ea..00000000000 --- a/source/gameengine/Ketsji/KX_MotionState.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_MotionState.cpp - * \ingroup ketsji - */ - -#include "KX_MotionState.h" -#include "SG_Spatial.h" - -KX_MotionState::KX_MotionState(SG_Spatial* node) : m_node(node) -{ - -} - -KX_MotionState::~KX_MotionState() -{ -} - -void KX_MotionState::GetWorldPosition(float& posX,float& posY,float& posZ) -{ - const MT_Point3& pos = m_node->GetWorldPosition(); - posX = pos[0]; - posY = pos[1]; - posZ = pos[2]; -} - -void KX_MotionState::GetWorldScaling(float& scaleX,float& scaleY,float& scaleZ) -{ - const MT_Vector3& scale = m_node->GetWorldScaling(); - scaleX = scale[0]; - scaleY = scale[1]; - scaleZ = scale[2]; -} - -void KX_MotionState::GetWorldOrientation(float& quatIma0,float& quatIma1,float& quatIma2,float& quatReal) -{ - MT_Quaternion orn = m_node->GetWorldOrientation().getRotation(); - quatIma0 = orn[0]; - quatIma1 = orn[1]; - quatIma2 = orn[2]; - quatReal = orn[3]; -} - -void KX_MotionState::GetWorldOrientation(float* ori) -{ - const MT_Matrix3x3& mat = m_node->GetWorldOrientation(); - mat.getValue(ori); -} - -void KX_MotionState::SetWorldOrientation(const float* ori) -{ - m_node->SetLocalOrientation(ori); -} - -void KX_MotionState::SetWorldPosition(float posX,float posY,float posZ) -{ - m_node->SetLocalPosition(MT_Point3(posX,posY,posZ)); - //m_node->SetWorldPosition(MT_Point3(posX,posY,posZ)); -} - -void KX_MotionState::SetWorldOrientation(float quatIma0,float quatIma1,float quatIma2,float quatReal) -{ - MT_Quaternion orn; - orn[0] = quatIma0; - orn[1] = quatIma1; - orn[2] = quatIma2; - orn[3] = quatReal; - - m_node->SetLocalOrientation(orn); - //m_node->SetWorldOrientation(orn); - -} - -void KX_MotionState::CalculateWorldTransformations() -{ - //Not needed, will be done in KX_Scene::UpdateParents() after the physics simulation - //bool parentUpdated = false; - //m_node->ComputeWorldTransforms(NULL, parentUpdated); -} - - diff --git a/source/gameengine/Ketsji/KX_MotionState.h b/source/gameengine/Ketsji/KX_MotionState.h deleted file mode 100644 index 38046fe4ff9..00000000000 --- a/source/gameengine/Ketsji/KX_MotionState.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_MotionState.h - * \ingroup ketsji - */ - -#ifndef __KX_MOTIONSTATE_H__ -#define __KX_MOTIONSTATE_H__ - -#include "PHY_IMotionState.h" - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -class KX_MotionState : public PHY_IMotionState -{ - class SG_Spatial* m_node; - -public: - KX_MotionState(class SG_Spatial* spatial); - virtual ~KX_MotionState(); - - virtual void GetWorldPosition(float& posX,float& posY,float& posZ); - virtual void GetWorldScaling(float& scaleX,float& scaleY,float& scaleZ); - virtual void GetWorldOrientation(float& quatIma0,float& quatIma1,float& quatIma2,float& quatReal); - virtual void SetWorldPosition(float posX,float posY,float posZ); - virtual void SetWorldOrientation(float quatIma0,float quatIma1,float quatIma2,float quatReal); - virtual void GetWorldOrientation(float* ori); - virtual void SetWorldOrientation(const float* ori); - - virtual void CalculateWorldTransformations(); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_MotionState") -#endif -}; - -#endif /* __KX_MOTIONSTATE_H__ */ diff --git a/source/gameengine/Ketsji/KX_MouseActuator.cpp b/source/gameengine/Ketsji/KX_MouseActuator.cpp deleted file mode 100644 index 6aa0d588b50..00000000000 --- a/source/gameengine/Ketsji/KX_MouseActuator.cpp +++ /dev/null @@ -1,539 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * Contributor(s): Geoffrey Gollmer, Jorge Bernal - * - * ***** END GPL LICENSE BLOCK ***** - */ - -#include "KX_MouseActuator.h" -#include "KX_KetsjiEngine.h" -#include "SCA_MouseManager.h" -#include "SCA_IInputDevice.h" -#include "RAS_ICanvas.h" -#include "KX_GameObject.h" -#include "MT_Vector3.h" -#include "MT_Scalar.h" -#include "MT_assert.h" -#include "limits.h" - -#include "BLI_math.h" - -#ifdef HAVE_CONFIG_H -#include -#endif - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -KX_MouseActuator::KX_MouseActuator( - SCA_IObject* gameobj, - - KX_KetsjiEngine* ketsjiEngine, - SCA_MouseManager* eventmgr, - int acttype, - bool visible, - bool* use_axis, - float* threshold, - bool* reset, - int* object_axis, - bool* local, - float* sensitivity, - float* limit_x, - float* limit_y -): - SCA_IActuator(gameobj, KX_ACT_MOUSE), - m_ketsji(ketsjiEngine), - m_eventmgr(eventmgr), - m_type(acttype), - m_visible(visible), - m_use_axis_x(use_axis[0]), - m_use_axis_y(use_axis[1]), - m_reset_x(reset[0]), - m_reset_y(reset[1]), - m_local_x(local[0]), - m_local_y(local[1]) -{ - m_canvas = m_ketsji->GetCanvas(); - m_oldposition[0] = m_oldposition[1] = -1.f; - m_limit_x[0] = limit_x[0]; - m_limit_x[1] = limit_x[1]; - m_limit_y[0] = limit_y[0]; - m_limit_y[1] = limit_y[1]; - m_threshold[0] = threshold[0]; - m_threshold[1] = threshold[1]; - m_object_axis[0] = object_axis[0]; - m_object_axis[1] = object_axis[1]; - m_sensitivity[0] = sensitivity[0]; - m_sensitivity[1] = sensitivity[1]; - m_angle[0] = 0.f; - m_angle[1] = 0.f; -} - -KX_MouseActuator::~KX_MouseActuator() -{ -} - -bool KX_MouseActuator::Update() -{ - bool result = false; - - bool bNegativeEvent = IsNegativeEvent(); - RemoveAllEvents(); - - if (bNegativeEvent) - return false; // do nothing on negative events - - KX_GameObject *parent = static_cast(GetParent()); - - m_mouse = ((SCA_MouseManager *)m_eventmgr)->GetInputDevice(); - - switch (m_type) { - case KX_ACT_MOUSE_VISIBILITY: - { - if (m_visible) { - if (m_canvas) { - m_canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL); - } - } - else { - if (m_canvas) { - m_canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE); - } - } - break; - } - case KX_ACT_MOUSE_LOOK: - { - if (m_mouse) { - - float position[2]; - float movement[2]; - MT_Vector3 rotation; - float setposition[2] = {0.0f}; - float center_x = 0.5f, center_y = 0.5f; - - getMousePosition(position); - - movement[0] = position[0]; - movement[1] = position[1]; - - //preventing undesired drifting when resolution is odd - if ((m_canvas->GetWidth() % 2) != 0) { - center_x = ((m_canvas->GetWidth() - 1.0f) / 2.0f) / (m_canvas->GetWidth()); - } - if ((m_canvas->GetHeight() % 2) != 0) { - center_y = ((m_canvas->GetHeight() - 1.0f) / 2.0f) / (m_canvas->GetHeight()); - } - - //preventing initial skipping. - if ((m_oldposition[0] <= -0.9f) && (m_oldposition[1] <= -0.9f)) { - - if (m_reset_x) { - m_oldposition[0] = center_x; - } - else { - m_oldposition[0] = position[0]; - } - - if (m_reset_y) { - m_oldposition[1] = center_y; - } - else { - m_oldposition[1] = position[1]; - } - setMousePosition(m_oldposition[0], m_oldposition[1]); - break; - } - - //Calculating X axis. - if (m_use_axis_x) { - - if (m_reset_x) { - setposition[0] = center_x; - movement[0] -= center_x; - } - else { - setposition[0] = position[0]; - movement[0] -= m_oldposition[0]; - } - - movement[0] *= -1.0f; - - /* Don't apply the rotation when we are under a certain threshold for mouse - movement */ - - if (((movement[0] > (m_threshold[0] / 10.0f)) || - ((movement[0] * (-1.0f)) > (m_threshold[0] / 10.0f)))) { - - movement[0] *= m_sensitivity[0]; - - if ((m_limit_x[0] != 0.0f) && ((m_angle[0] + movement[0]) <= m_limit_x[0])) { - movement[0] = m_limit_x[0] - m_angle[0]; - } - - if ((m_limit_x[1] != 0.0f) && ((m_angle[0] + movement[0]) >= m_limit_x[1])) { - movement[0] = m_limit_x[1] - m_angle[0]; - } - - m_angle[0] += movement[0]; - - switch (m_object_axis[0]) { - case KX_ACT_MOUSE_OBJECT_AXIS_X: - { - rotation = MT_Vector3(movement[0], 0.0f, 0.0f); - break; - } - case KX_ACT_MOUSE_OBJECT_AXIS_Y: - { - rotation = MT_Vector3(0.0f, movement[0], 0.0f); - break; - } - case KX_ACT_MOUSE_OBJECT_AXIS_Z: - { - rotation = MT_Vector3(0.0f, 0.0f, movement[0]); - break; - } - default: - break; - } - parent->ApplyRotation(rotation, m_local_x); - } - } - else { - setposition[0] = center_x; - } - - //Calculating Y axis. - if (m_use_axis_y) { - - if (m_reset_y) { - setposition[1] = center_y; - movement[1] -= center_y; - } - else { - setposition[1] = position[1]; - movement[1] -= m_oldposition[1]; - } - - movement[1] *= -1.0f; - - /* Don't apply the rotation when we are under a certain threshold for mouse - movement */ - - if (((movement[1] > (m_threshold[1] / 10.0f)) || - ((movement[1] * (-1.0f)) > (m_threshold[1] / 10.0f)))) { - - movement[1] *= m_sensitivity[1]; - - if ((m_limit_y[0] != 0.0f) && ((m_angle[1] + movement[1]) <= m_limit_y[0])) { - movement[1] = m_limit_y[0] - m_angle[1]; - } - - if ((m_limit_y[1] != 0.0f) && ((m_angle[1] + movement[1]) >= m_limit_y[1])) { - movement[1] = m_limit_y[1] - m_angle[1]; - } - - m_angle[1] += movement[1]; - - switch (m_object_axis[1]) - { - case KX_ACT_MOUSE_OBJECT_AXIS_X: - { - rotation = MT_Vector3(movement[1], 0.0f, 0.0f); - break; - } - case KX_ACT_MOUSE_OBJECT_AXIS_Y: - { - rotation = MT_Vector3(0.0f, movement[1], 0.0f); - break; - } - case KX_ACT_MOUSE_OBJECT_AXIS_Z: - { - rotation = MT_Vector3(0.0f, 0.0f, movement[1]); - break; - } - default: - break; - } - parent->ApplyRotation(rotation, m_local_y); - } - } - else { - setposition[1] = center_y; - } - - // only trigger mouse event when it is necessary - if (m_oldposition[0] != position[0] || m_oldposition[1] != position[1]) { - setMousePosition(setposition[0], setposition[1]); - } - - m_oldposition[0] = position[0]; - m_oldposition[1] = position[1]; - - } - else { - //printf("\nNo input device detected for mouse actuator\n"); - } - break; - } - default: - break; - } - return result; -} - -bool KX_MouseActuator::isValid(KX_MouseActuator::KX_ACT_MOUSE_MODE mode) -{ - return ((mode > KX_ACT_MOUSE_NODEF) && (mode < KX_ACT_MOUSE_MAX)); -} - - -CValue* KX_MouseActuator::GetReplica() -{ - KX_MouseActuator* replica = new KX_MouseActuator(*this); - - replica->ProcessReplica(); - return replica; -} - -void KX_MouseActuator::ProcessReplica() -{ - SCA_IActuator::ProcessReplica(); -} - -void KX_MouseActuator::getMousePosition(float* pos) -{ - MT_assert(m_mouse); - const SCA_InputEvent & xevent = m_mouse->GetEventValue(SCA_IInputDevice::KX_MOUSEX); - const SCA_InputEvent & yevent = m_mouse->GetEventValue(SCA_IInputDevice::KX_MOUSEY); - - pos[0] = m_canvas->GetMouseNormalizedX(xevent.m_eventval); - pos[1] = m_canvas->GetMouseNormalizedY(yevent.m_eventval); -} - -void KX_MouseActuator::setMousePosition(float fx, float fy) -{ - int x, y; - - x = (int)(fx * m_canvas->GetWidth()); - y = (int)(fy * m_canvas->GetHeight()); - - m_canvas->SetMousePosition(x, y); -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject KX_MouseActuator::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_MouseActuator", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &SCA_IActuator::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_MouseActuator::Methods[] = { - {"reset", (PyCFunction) KX_MouseActuator::sPyReset, METH_NOARGS,"reset() : undo rotation caused by actuator\n"}, - {NULL,NULL} //Sentinel -}; - - - -PyAttributeDef KX_MouseActuator::Attributes[] = { - KX_PYATTRIBUTE_BOOL_RW("visible", KX_MouseActuator, m_visible), - KX_PYATTRIBUTE_BOOL_RW("use_axis_x", KX_MouseActuator, m_use_axis_x), - KX_PYATTRIBUTE_BOOL_RW("use_axis_y", KX_MouseActuator, m_use_axis_y), - KX_PYATTRIBUTE_FLOAT_ARRAY_RW("threshold", 0.0f, 0.5f, KX_MouseActuator, m_threshold, 2), - KX_PYATTRIBUTE_BOOL_RW("reset_x", KX_MouseActuator, m_reset_x), - KX_PYATTRIBUTE_BOOL_RW("reset_y", KX_MouseActuator, m_reset_y), - KX_PYATTRIBUTE_INT_ARRAY_RW("object_axis", 0, 2, 1, KX_MouseActuator, m_object_axis, 2), - KX_PYATTRIBUTE_BOOL_RW("local_x", KX_MouseActuator, m_local_x), - KX_PYATTRIBUTE_BOOL_RW("local_y", KX_MouseActuator, m_local_y), - KX_PYATTRIBUTE_FLOAT_ARRAY_RW("sensitivity", -FLT_MAX, FLT_MAX, KX_MouseActuator, m_sensitivity, 2), - KX_PYATTRIBUTE_RW_FUNCTION("limit_x", KX_MouseActuator, pyattr_get_limit_x, pyattr_set_limit_x), - KX_PYATTRIBUTE_RW_FUNCTION("limit_y", KX_MouseActuator, pyattr_get_limit_y, pyattr_set_limit_y), - KX_PYATTRIBUTE_RW_FUNCTION("angle", KX_MouseActuator, pyattr_get_angle, pyattr_set_angle), - { NULL } //Sentinel -}; - -PyObject* KX_MouseActuator::pyattr_get_limit_x(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_MouseActuator* self= static_cast(self_v); - return Py_BuildValue("[f,f]", (self->m_limit_x[0] / (float)M_PI * 180.0f), (self->m_limit_x[1] / (float)M_PI * 180.0f)); -} - -int KX_MouseActuator::pyattr_set_limit_x(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - PyObject *item1, *item2; - KX_MouseActuator* self= static_cast(self_v); - - if (!PyList_Check(value)) - return PY_SET_ATTR_FAIL; - - if (PyList_Size(value) != 2) - return PY_SET_ATTR_FAIL; - - item1 = PyList_GET_ITEM(value, 0); - item2 = PyList_GET_ITEM(value, 1); - - if (!(PyFloat_Check(item1)) || !(PyFloat_Check(item2))) { - return PY_SET_ATTR_FAIL; - } - else { - self->m_limit_x[0] = (float)((PyFloat_AsDouble(item1) * M_PI) / 180.0f); - self->m_limit_x[1] = (float)((PyFloat_AsDouble(item2) * M_PI) / 180.0f); - } - - return PY_SET_ATTR_SUCCESS; -} - -PyObject* KX_MouseActuator::pyattr_get_limit_y(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_MouseActuator* self= static_cast(self_v); - return Py_BuildValue("[f,f]", (self->m_limit_y[0] / (float)M_PI * 180.0f), (self->m_limit_y[1] / (float)M_PI * 180.0f)); -} - -int KX_MouseActuator::pyattr_set_limit_y(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - PyObject *item1, *item2; - KX_MouseActuator* self= static_cast(self_v); - - if (!PyList_Check(value)) - return PY_SET_ATTR_FAIL; - - if (PyList_Size(value) != 2) - return PY_SET_ATTR_FAIL; - - item1 = PyList_GET_ITEM(value, 0); - item2 = PyList_GET_ITEM(value, 1); - - if (!(PyFloat_Check(item1)) || !(PyFloat_Check(item2))) { - return PY_SET_ATTR_FAIL; - } - else { - self->m_limit_y[0] = (float)((PyFloat_AsDouble(item1) * M_PI) / 180.0f); - self->m_limit_y[1] = (float)((PyFloat_AsDouble(item2) * M_PI) / 180.0f); - } - - return PY_SET_ATTR_SUCCESS; -} - -PyObject* KX_MouseActuator::pyattr_get_angle(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_MouseActuator* self= static_cast(self_v); - return Py_BuildValue("[f,f]", (self->m_angle[0] / (float)M_PI * 180.0f), (self->m_angle[1] / (float)M_PI * 180.0f)); -} - -int KX_MouseActuator::pyattr_set_angle(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - PyObject *item1, *item2; - KX_MouseActuator* self= static_cast(self_v); - - if (!PyList_Check(value)) - return PY_SET_ATTR_FAIL; - - if (PyList_Size(value) != 2) - return PY_SET_ATTR_FAIL; - - item1 = PyList_GET_ITEM(value, 0); - item2 = PyList_GET_ITEM(value, 1); - - if (!(PyFloat_Check(item1)) || !(PyFloat_Check(item2))) { - return PY_SET_ATTR_FAIL; - } - else { - self->m_angle[0] = ((float)(PyFloat_AsDouble(item1) * M_PI) / 180.0f); - self->m_angle[1] = ((float)(PyFloat_AsDouble(item2) * M_PI) / 180.0f); - } - - return PY_SET_ATTR_SUCCESS; -} - -PyObject* KX_MouseActuator::PyReset() -{ - MT_Vector3 rotation; - KX_GameObject *parent = static_cast(GetParent()); - - switch (m_object_axis[0]) { - case KX_ACT_MOUSE_OBJECT_AXIS_X: - { - rotation = MT_Vector3(-1.0f * m_angle[0], 0.0f, 0.0f); - break; - } - case KX_ACT_MOUSE_OBJECT_AXIS_Y: - { - rotation = MT_Vector3(0.0f, -1.0f * m_angle[0], 0.0f); - break; - } - case KX_ACT_MOUSE_OBJECT_AXIS_Z: - { - rotation = MT_Vector3(0.0f, 0.0f, -1.0f * m_angle[0]); - break; - } - default: - break; - } - parent->ApplyRotation(rotation, m_local_x); - - switch (m_object_axis[1]) { - case KX_ACT_MOUSE_OBJECT_AXIS_X: - { - rotation = MT_Vector3(-1.0f * m_angle[1], 0.0f, 0.0f); - break; - } - case KX_ACT_MOUSE_OBJECT_AXIS_Y: - { - rotation = MT_Vector3(0.0f, -1.0f * m_angle[1], 0.0f); - break; - } - case KX_ACT_MOUSE_OBJECT_AXIS_Z: - { - rotation = MT_Vector3(0.0f, 0.0f, -1.0f * m_angle[1]); - break; - } - default: - break; - } - parent->ApplyRotation(rotation, m_local_y); - - m_angle[0] = 0.0f; - m_angle[1] = 0.0f; - - Py_RETURN_NONE; -} - -#endif /* WITH_PYTHON */ diff --git a/source/gameengine/Ketsji/KX_MouseActuator.h b/source/gameengine/Ketsji/KX_MouseActuator.h deleted file mode 100644 index e244e271428..00000000000 --- a/source/gameengine/Ketsji/KX_MouseActuator.h +++ /dev/null @@ -1,132 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * Contributor(s): Geoffrey Gollmer, Jorge Bernal - * - * ***** END GPL LICENSE BLOCK ***** - */ - -#ifndef __KX_MOUSEACTUATOR -#define __KX_MOUSEACTUATOR - -#include "SCA_IActuator.h" - -class KX_KetsjiEngine; -class SCA_MouseManager; -class SCA_IInputDevice; -class RAS_ICanvas; - -class KX_MouseActuator : public SCA_IActuator -{ - Py_Header - -private: - - KX_KetsjiEngine* m_ketsji; - SCA_MouseManager* m_eventmgr; - SCA_IInputDevice* m_mouse; - RAS_ICanvas* m_canvas; - int m_type; - - bool m_visible; - - bool m_use_axis_x; /* 0 for calculate axis, 1 for ignore axis */ - bool m_use_axis_y; - float m_threshold[2]; - bool m_reset_x; /* 0=reset, 1=free */ - bool m_reset_y; - int m_object_axis[2]; /* 0=x, 1=y, 2=z */ - bool m_local_x; /* 0=local, 1=global*/ - bool m_local_y; - float m_sensitivity[2]; - float m_limit_x[2]; - float m_limit_y[2]; - - float m_oldposition[2]; - float m_angle[2]; - -public: - - enum KX_ACT_MOUSE_OBJECT_AXIS { - KX_ACT_MOUSE_OBJECT_AXIS_X = 0, - KX_ACT_MOUSE_OBJECT_AXIS_Y, - KX_ACT_MOUSE_OBJECT_AXIS_Z - }; - - enum KX_ACT_MOUSE_MODE { - KX_ACT_MOUSE_NODEF = 0, - KX_ACT_MOUSE_VISIBILITY, - KX_ACT_MOUSE_LOOK, - KX_ACT_MOUSE_MAX - }; - - KX_MouseActuator( - SCA_IObject* gameobj, - KX_KetsjiEngine* ketsjiEngine, - SCA_MouseManager* eventmgr, - int acttype, - bool visible, - bool* use_axis, - float* threshold, - bool* reset, - int* object_axis, - bool* local, - float* sensitivity, - float* limit_x, - float* limit_y - ); - - - ~KX_MouseActuator(); - - CValue* GetReplica(); - virtual void ProcessReplica(); - - virtual bool Update(); - - /* check whether this value is valid */ - bool isValid(KX_ACT_MOUSE_MODE mode); - - virtual void getMousePosition(float*); - virtual void setMousePosition(float, float); - - -#ifdef WITH_PYTHON - - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - - /* Methods */ - - KX_PYMETHOD_DOC_NOARGS(KX_MouseActuator,Reset); - - /* Attributes */ - - static PyObject* pyattr_get_limit_x(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_limit_x(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - - static PyObject* pyattr_get_limit_y(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_limit_y(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - - static PyObject* pyattr_get_angle(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_angle(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); -#endif /* WITH_PYTHON */ - -}; - -#endif //__KX_MOUSEACTUATOR_DOC diff --git a/source/gameengine/Ketsji/KX_MouseFocusSensor.cpp b/source/gameengine/Ketsji/KX_MouseFocusSensor.cpp deleted file mode 100644 index 451078d4a36..00000000000 --- a/source/gameengine/Ketsji/KX_MouseFocusSensor.cpp +++ /dev/null @@ -1,520 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - * KX_MouseFocusSensor determines mouse in/out/over events. - */ - -/** \file gameengine/Ketsji/KX_MouseFocusSensor.cpp - * \ingroup ketsji - */ - -#ifdef _MSC_VER - /* This warning tells us about truncation of __long__ stl-generated names. - * It can occasionally cause DevStudio to have internal compiler warnings. */ -# pragma warning(disable:4786) -#endif - -#include - -#include "MT_Point3.h" -#include "RAS_FramingManager.h" -#include "RAS_ICanvas.h" -#include "RAS_IRasterizer.h" -#include "RAS_MeshObject.h" -#include "SCA_IScene.h" -#include "KX_Scene.h" -#include "KX_Camera.h" -#include "KX_MouseFocusSensor.h" -#include "KX_PyMath.h" - -#include "KX_RayCast.h" -#include "PHY_IPhysicsController.h" -#include "PHY_IPhysicsEnvironment.h" - - -#include "KX_ClientObjectInfo.h" - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -KX_MouseFocusSensor::KX_MouseFocusSensor(SCA_MouseManager* eventmgr, - int startx, - int starty, - short int mousemode, - int focusmode, - bool bTouchPulse, - const STR_String& propname, - bool bFindMaterial, - bool bXRay, - KX_Scene* kxscene, - KX_KetsjiEngine *kxengine, - SCA_IObject* gameobj) - : SCA_MouseSensor(eventmgr, startx, starty, mousemode, gameobj), - m_focusmode(focusmode), - m_bTouchPulse(bTouchPulse), - m_bXRay(bXRay), - m_bFindMaterial(bFindMaterial), - m_propertyname(propname), - m_kxscene(kxscene), - m_kxengine(kxengine) -{ - Init(); -} - -void KX_MouseFocusSensor::Init() -{ - m_mouse_over_in_previous_frame = (m_invert)?true:false; - m_positive_event = false; - m_hitObject = 0; - m_hitObject_Last = NULL; - m_reset = true; - - m_hitPosition.setValue(0,0,0); - m_prevTargetPoint.setValue(0,0,0); - m_prevSourcePoint.setValue(0,0,0); - m_hitNormal.setValue(0,0,1); -} - -bool KX_MouseFocusSensor::Evaluate() -{ - bool result = false; - bool obHasFocus = false; - bool reset = m_reset && m_level; - -// cout << "evaluate focus mouse sensor "<m_gameobject; - - /* Is this me? In the ray test, there are a lot of extra checks - * for aliasing artifacts from self-hits. That doesn't happen - * here, so a simple test suffices. Or does the camera also get - * self-hits? (No, and the raysensor shouldn't do it either, since - * self-hits are excluded by setting the correct ignore-object.) - * Hitspots now become valid. */ - KX_GameObject* thisObj = (KX_GameObject*) GetParent(); - - bool bFound = false; - - if ((m_focusmode == 2) || hitKXObj == thisObj) - { - if (m_propertyname.Length() == 0) - { - bFound = true; - } - else - { - if (m_bFindMaterial) { - for (unsigned int i = 0; i < hitKXObj->GetMeshCount(); ++i) { - RAS_MeshObject *meshObj = hitKXObj->GetMesh(i); - for (unsigned int j = 0; j < meshObj->NumMaterials(); ++j) { - bFound = strcmp(m_propertyname.ReadPtr(), meshObj->GetMaterialName(j).ReadPtr() + 2) == 0; - if (bFound) - break; - } - } - } - else { - bFound = hitKXObj->GetProperty(m_propertyname) != NULL; - } - } - - if (bFound) - { - m_hitObject = hitKXObj; - m_hitPosition = result->m_hitPoint; - m_hitNormal = result->m_hitNormal; - m_hitUV = result->m_hitUV; - return true; - } - } - - return true; // object must be visible to trigger - //return false; // occluded objects can trigger -} - -/* this function is used to pre-filter the object before casting the ray on them. - * This is useful for "X-Ray" option when we want to see "through" unwanted object. - */ -bool KX_MouseFocusSensor::NeedRayCast(KX_ClientObjectInfo *client, void *UNUSED(data)) -{ - KX_GameObject *hitKXObj = client->m_gameobject; - - if (client->m_type > KX_ClientObjectInfo::ACTOR) - { - // Unknown type of object, skip it. - // Should not occur as the sensor objects are filtered in RayTest() - printf("Invalid client type %d found ray casting\n", client->m_type); - return false; - } - if (m_bXRay && m_propertyname.Length() != 0) - { - if (m_bFindMaterial) - { - bool found = false; - for (unsigned int i = 0; i < hitKXObj->GetMeshCount(); ++i) { - RAS_MeshObject *meshObj = hitKXObj->GetMesh(i); - for (unsigned int j = 0; j < meshObj->NumMaterials(); ++j) { - found = strcmp(m_propertyname.ReadPtr(), meshObj->GetMaterialName(j).ReadPtr() + 2) == 0; - if (found) - break; - } - } - if (!found) - return false; - } - else - { - if (hitKXObj->GetProperty(m_propertyname) == NULL) - return false; - } - } - return true; -} - -bool KX_MouseFocusSensor::ParentObjectHasFocusCamera(KX_Camera *cam) -{ - /* All screen handling in the gameengine is done by GL, - * specifically the model/view and projection parts. The viewport - * part is in the creator. - * - * The theory is this: - * WCS - world coordinates - * -> wcs_camcs_trafo -> - * camCS - camera coordinates - * -> camcs_clip_trafo -> - * clipCS - normalized device coordinates? - * -> normview_win_trafo - * winCS - window coordinates - * - * The first two transforms are respectively the model/view and - * the projection matrix. These are passed to the rasterizer, and - * we store them in the camera for easy access. - * - * For normalized device coords (xn = x/w, yn = y/w/zw) the - * windows coords become (lb = left bottom) - * - * xwin = [(xn + 1.0) * width]/2 + x_lb - * ywin = [(yn + 1.0) * height]/2 + y_lb - * - * Inverting (blender y is flipped!): - * - * xn = 2(xwin - x_lb)/width - 1.0 - * yn = 2(ywin - y_lb)/height - 1.0 - * = 2(height - y_blender - y_lb)/height - 1.0 - * = 1.0 - 2(y_blender - y_lb)/height - * - * */ - - - /* Because we don't want to worry about resize events, camera - * changes and all that crap, we just determine this over and - * over. Stop whining. We have lots of other calculations to do - * here as well. These reads are not the main cost. If there is no - * canvas, the test is irrelevant. The 1.0 makes sure the - * calculations don't bomb. Maybe we should explicitly guard for - * division by 0.0...*/ - - RAS_Rect area, viewport; - short m_y_inv = m_kxengine->GetCanvas()->GetHeight()-m_y; - - m_kxengine->GetSceneViewport(m_kxscene, cam, area, viewport); - - /* Check if the mouse is in the viewport */ - if (( m_x < viewport.m_x2 && // less than right - m_x > viewport.m_x1 && // more than then left - m_y_inv < viewport.m_y2 && // below top - m_y_inv > viewport.m_y1) == 0) // above bottom - { - return false; - } - - float height = float(viewport.m_y2 - viewport.m_y1 + 1); - float width = float(viewport.m_x2 - viewport.m_x1 + 1); - - float x_lb = float(viewport.m_x1); - float y_lb = float(viewport.m_y1); - - MT_Vector4 frompoint; - MT_Vector4 topoint; - - /* m_y_inv - inverting for a bounds check is only part of it, now make relative to view bounds */ - m_y_inv = (viewport.m_y2 - m_y_inv) + viewport.m_y1; - - - /* There's some strangeness I don't fully get here... These values - * _should_ be wrong! - see from point Z values */ - - - /* build the from and to point in normalized device coordinates - * Normalized device coordinates are [-1,1] in x, y, z - * - * The actual z coordinates used don't have to be exact just infront and - * behind of the near and far clip planes. - */ - frompoint.setValue( (2 * (m_x-x_lb) / width) - 1.0f, - 1.0f - (2 * (m_y_inv - y_lb) / height), - -1.0f, - 1.0f ); - - topoint.setValue( (2 * (m_x-x_lb) / width) - 1.0f, - 1.0f - (2 * (m_y_inv-y_lb) / height), - 1.0f, - 1.0f ); - - /* camera to world */ - MT_Matrix4x4 camcs_wcs_matrix = MT_Matrix4x4(cam->GetCameraToWorld()); - - /* badly defined, the first time round.... I wonder why... I might - * want to guard against floating point errors here.*/ - MT_Matrix4x4 clip_camcs_matrix = MT_Matrix4x4(cam->GetProjectionMatrix()); - clip_camcs_matrix.invert(); - - /* shoot-points: clip to cam to wcs . win to clip was already done.*/ - frompoint = clip_camcs_matrix * frompoint; - topoint = clip_camcs_matrix * topoint; - /* clipstart = - (frompoint[2] / frompoint[3]) - * clipend = - (topoint[2] / topoint[3]) */ - frompoint = camcs_wcs_matrix * frompoint; - topoint = camcs_wcs_matrix * topoint; - - /* from hom wcs to 3d wcs: */ - m_prevSourcePoint.setValue( frompoint[0]/frompoint[3], - frompoint[1]/frompoint[3], - frompoint[2]/frompoint[3]); - - m_prevTargetPoint.setValue( topoint[0]/topoint[3], - topoint[1]/topoint[3], - topoint[2]/topoint[3]); - - /* 2. Get the object from PhysicsEnvironment */ - /* Shoot! Beware that the first argument here is an - * ignore-object. We don't ignore anything... */ - PHY_IPhysicsController* physics_controller = cam->GetPhysicsController(); - PHY_IPhysicsEnvironment* physics_environment = m_kxscene->GetPhysicsEnvironment(); - - // get UV mapping - KX_RayCast::Callback callback(this,physics_controller,NULL,false,true); - - KX_RayCast::RayTest(physics_environment, m_prevSourcePoint, m_prevTargetPoint, callback); - - if (m_hitObject) - return true; - - return false; -} - -bool KX_MouseFocusSensor::ParentObjectHasFocus() -{ - m_hitObject = 0; - m_hitPosition.setValue(0,0,0); - m_hitNormal.setValue(1,0,0); - - KX_Camera *cam= m_kxscene->GetActiveCamera(); - - if (ParentObjectHasFocusCamera(cam)) - return true; - - list* cameras = m_kxscene->GetCameras(); - list::iterator it = cameras->begin(); - - while (it != cameras->end()) { - if (((*it) != cam) && (*it)->GetViewport()) - if (ParentObjectHasFocusCamera(*it)) - return true; - - it++; - } - - return false; -} - -const MT_Point3& KX_MouseFocusSensor::RaySource() const -{ - return m_prevSourcePoint; -} - -const MT_Point3& KX_MouseFocusSensor::RayTarget() const -{ - return m_prevTargetPoint; -} - -const MT_Point3& KX_MouseFocusSensor::HitPosition() const -{ - return m_hitPosition; -} - -const MT_Vector3& KX_MouseFocusSensor::HitNormal() const -{ - return m_hitNormal; -} - -const MT_Vector2& KX_MouseFocusSensor::HitUV() const -{ - return m_hitUV; -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject KX_MouseFocusSensor::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_MouseFocusSensor", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &SCA_MouseSensor::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_MouseFocusSensor::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_MouseFocusSensor::Attributes[] = { - KX_PYATTRIBUTE_RO_FUNCTION("raySource", KX_MouseFocusSensor, pyattr_get_ray_source), - KX_PYATTRIBUTE_RO_FUNCTION("rayTarget", KX_MouseFocusSensor, pyattr_get_ray_target), - KX_PYATTRIBUTE_RO_FUNCTION("rayDirection", KX_MouseFocusSensor, pyattr_get_ray_direction), - KX_PYATTRIBUTE_RO_FUNCTION("hitObject", KX_MouseFocusSensor, pyattr_get_hit_object), - KX_PYATTRIBUTE_RO_FUNCTION("hitPosition", KX_MouseFocusSensor, pyattr_get_hit_position), - KX_PYATTRIBUTE_RO_FUNCTION("hitNormal", KX_MouseFocusSensor, pyattr_get_hit_normal), - KX_PYATTRIBUTE_RO_FUNCTION("hitUV", KX_MouseFocusSensor, pyattr_get_hit_uv), - KX_PYATTRIBUTE_BOOL_RW("usePulseFocus", KX_MouseFocusSensor, m_bTouchPulse), - KX_PYATTRIBUTE_BOOL_RW("useXRay", KX_MouseFocusSensor, m_bXRay), - KX_PYATTRIBUTE_BOOL_RW("useMaterial", KX_MouseFocusSensor, m_bFindMaterial), - KX_PYATTRIBUTE_STRING_RW("propName", 0, MAX_PROP_NAME, false, KX_MouseFocusSensor, m_propertyname), - { NULL } //Sentinel -}; - -/* Attributes */ -PyObject *KX_MouseFocusSensor::pyattr_get_ray_source(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_MouseFocusSensor* self = static_cast(self_v); - return PyObjectFrom(self->RaySource()); -} - -PyObject *KX_MouseFocusSensor::pyattr_get_ray_target(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_MouseFocusSensor* self = static_cast(self_v); - return PyObjectFrom(self->RayTarget()); -} - -PyObject *KX_MouseFocusSensor::pyattr_get_ray_direction(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_MouseFocusSensor* self = static_cast(self_v); - MT_Vector3 dir = self->RayTarget() - self->RaySource(); - if (MT_fuzzyZero(dir)) dir.setValue(0,0,0); - else dir.normalize(); - return PyObjectFrom(dir); -} - -PyObject *KX_MouseFocusSensor::pyattr_get_hit_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_MouseFocusSensor* self = static_cast(self_v); - - if (self->m_hitObject) - return self->m_hitObject->GetProxy(); - - Py_RETURN_NONE; -} - -PyObject *KX_MouseFocusSensor::pyattr_get_hit_position(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_MouseFocusSensor* self = static_cast(self_v); - return PyObjectFrom(self->HitPosition()); -} - -PyObject *KX_MouseFocusSensor::pyattr_get_hit_normal(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_MouseFocusSensor* self = static_cast(self_v); - return PyObjectFrom(self->HitNormal()); -} - -PyObject *KX_MouseFocusSensor::pyattr_get_hit_uv(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_MouseFocusSensor* self = static_cast(self_v); - return PyObjectFrom(self->HitUV()); -} - -#endif // WITH_PYTHON - -/* eof */ - diff --git a/source/gameengine/Ketsji/KX_MouseFocusSensor.h b/source/gameengine/Ketsji/KX_MouseFocusSensor.h deleted file mode 100644 index dd9295b2ff4..00000000000 --- a/source/gameengine/Ketsji/KX_MouseFocusSensor.h +++ /dev/null @@ -1,208 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_MouseFocusSensor.h - * \ingroup ketsji - * \brief KX_MouseFocusSensor determines mouse in/out/over events. - */ - -#ifndef __KX_MOUSEFOCUSSENSOR_H__ -#define __KX_MOUSEFOCUSSENSOR_H__ - -#include "SCA_MouseSensor.h" - -#include "BLI_utildefines.h" - -class KX_RayCast; - -/** - * The mouse focus sensor extends the basic SCA_MouseSensor. It has - * been placed in KX because it needs access to the rasterizer and - * SuMO. - * - * - extend the valid modes? - * - */ -class KX_MouseFocusSensor : public SCA_MouseSensor -{ - - Py_Header - - public: - - KX_MouseFocusSensor(class SCA_MouseManager* eventmgr, - int startx, - int starty, - short int mousemode, - int focusmode, - bool bTouchPulse, - const STR_String& propname, - bool bFindMaterial, - bool bXRay, - KX_Scene* kxscene, - KX_KetsjiEngine* kxengine, - SCA_IObject* gameobj); - - virtual ~KX_MouseFocusSensor() { } - virtual CValue* GetReplica() { - CValue* replica = new KX_MouseFocusSensor(*this); - // this will copy properties and so on... - replica->ProcessReplica(); - return replica; - }; - - virtual void Replace_IScene(SCA_IScene *val) - { - m_kxscene= static_cast(val); - }; - - - /** - * \attention Overrides default evaluate. - */ - virtual bool Evaluate(); - virtual void Init(); - - virtual bool IsPositiveTrigger() { - bool result = m_positive_event; - if (m_invert) result = !result; - return result; - }; - - /// \see KX_RayCast - bool RayHit(KX_ClientObjectInfo *client, KX_RayCast *result, void *UNUSED(data)); - /// \see KX_RayCast - bool NeedRayCast(KX_ClientObjectInfo *client, void *UNUSED(data)); - - const MT_Point3& RaySource() const; - const MT_Point3& RayTarget() const; - const MT_Point3& HitPosition() const; - const MT_Vector3& HitNormal() const; - const MT_Vector2& HitUV() const; - -#ifdef WITH_PYTHON - - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - - /* attributes */ - static PyObject* pyattr_get_ray_source(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_ray_target(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_ray_direction(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_hit_object(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_hit_position(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_hit_normal(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_hit_uv(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - -#endif /* WITH_PYTHON */ - - /* --------------------------------------------------------------------- */ - SCA_IObject* m_hitObject; - void* m_hitObject_Last; /* only use for comparison, never access */ - - private: - /** - * The focus mode. 1 for handling focus, 0 for not handling, 2 for focus on any object - */ - int m_focusmode; - - /** - * Flags whether the previous test showed a mouse-over. - */ - bool m_mouse_over_in_previous_frame; - - /** - * Flags whether changes in hit object should trigger a pulse - */ - bool m_bTouchPulse; - - /** - * Flags get through other objects - */ - bool m_bXRay; - - /** - * Flags material - */ - bool m_bFindMaterial; - - /** - * Property or material name - */ - STR_String m_propertyname; - - /** - * Flags whether the previous test evaluated positive. - */ - bool m_positive_event; - - /** - * Tests whether the object is in mouse focus for this camera - */ - bool ParentObjectHasFocusCamera(KX_Camera *cam); - - /** - * Tests whether the object is in mouse focus in this scene. - */ - bool ParentObjectHasFocus(void); - - /** - * (in game world coordinates) the place where the object was hit. - */ - MT_Point3 m_hitPosition; - - /** - * (in game world coordinates) the position to which to shoot the ray. - */ - MT_Point3 m_prevTargetPoint; - - /** - * (in game world coordinates) the position from which to shoot the ray. - */ - MT_Point3 m_prevSourcePoint; - - /** - * (in game world coordinates) the face normal of the vertex where - * the object was hit. */ - MT_Vector3 m_hitNormal; - - /** - * UV texture coordinate of the hit point if any, (0,0) otherwise - */ - MT_Vector2 m_hitUV; - - /** - * The KX scene that holds the camera. The camera position - * determines a part of the start location of the picking ray. */ - KX_Scene* m_kxscene; - - /** - * The KX engine is needed for computing the viewport */ - KX_KetsjiEngine* m_kxengine; -}; - -#endif /* __KX_MOUSESENSOR */ diff --git a/source/gameengine/Ketsji/KX_NavMeshObject.cpp b/source/gameengine/Ketsji/KX_NavMeshObject.cpp deleted file mode 100644 index 83accb1d7a5..00000000000 --- a/source/gameengine/Ketsji/KX_NavMeshObject.cpp +++ /dev/null @@ -1,747 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -#include "MEM_guardedalloc.h" - -#include "BLI_math_vector.h" -#include "KX_NavMeshObject.h" -#include "RAS_MeshObject.h" -#include "RAS_Polygon.h" - -#include "DNA_mesh_types.h" -#include "DNA_meshdata_types.h" - -extern "C" { -#include "BKE_scene.h" -#include "BKE_customdata.h" -#include "BKE_cdderivedmesh.h" -#include "BKE_DerivedMesh.h" -#include "BKE_navmesh_conversion.h" -} - -#include "KX_PythonInit.h" -#include "KX_PyMath.h" -#include "EXP_Value.h" -#include "Recast.h" -#include "DetourStatNavMeshBuilder.h" -#include "KX_ObstacleSimulation.h" - -#define MAX_PATH_LEN 256 -static const float polyPickExt[3] = {2, 4, 2}; - -static void calcMeshBounds(const float* vert, int nverts, float* bmin, float* bmax) -{ - bmin[0] = bmax[0] = vert[0]; - bmin[1] = bmax[1] = vert[1]; - bmin[2] = bmax[2] = vert[2]; - for (int i=1; ivert[3*i+0]) bmin[0] = vert[3*i+0]; - if (bmin[1]>vert[3*i+1]) bmin[1] = vert[3*i+1]; - if (bmin[2]>vert[3*i+2]) bmin[2] = vert[3*i+2]; - - if (bmax[0]ProcessReplica(); - return replica; -} - -void KX_NavMeshObject::ProcessReplica() -{ - KX_GameObject::ProcessReplica(); - m_navMesh = NULL; /* without this, building frees the navmesh we copied from */ - if (!BuildNavMesh()) { - std::cout << "Error in " << __func__ << ": unable to build navigation mesh" << std::endl; - return; - } - KX_Scene* scene = KX_GetActiveScene(); - KX_ObstacleSimulation* obssimulation = scene->GetObstacleSimulation(); - if (obssimulation) - obssimulation->AddObstaclesForNavMesh(this); -} - -bool KX_NavMeshObject::BuildVertIndArrays(float *&vertices, int& nverts, - unsigned short* &polys, int& npolys, unsigned short *&dmeshes, - float *&dvertices, int &ndvertsuniq, unsigned short *&dtris, - int& ndtris, int &vertsPerPoly) -{ - /* TODO: This doesn't work currently because of eval_ctx. */ -#if 0 - DerivedMesh* dm = mesh_create_derived_no_virtual(GetScene()->GetBlenderScene(), GetBlenderObject(), - NULL, CD_MASK_MESH); - CustomData *pdata = dm->getPolyDataLayout(dm); - int* recastData = (int*) CustomData_get_layer(pdata, CD_RECAST); - if (recastData) - { - int *dtrisToPolysMap=NULL, *dtrisToTrisMap=NULL, *trisToFacesMap=NULL; - int nAllVerts = 0; - float *allVerts = NULL; - buildNavMeshDataByDerivedMesh(dm, &vertsPerPoly, &nAllVerts, &allVerts, &ndtris, &dtris, - &npolys, &dmeshes, &polys, &dtrisToPolysMap, &dtrisToTrisMap, &trisToFacesMap); - - MEM_SAFE_FREE(dtrisToPolysMap); - MEM_SAFE_FREE(dtrisToTrisMap); - MEM_SAFE_FREE(trisToFacesMap); - - unsigned short *verticesMap = (unsigned short *)MEM_mallocN(sizeof(*verticesMap) * nAllVerts, __func__); - memset(verticesMap, 0xff, sizeof(*verticesMap) * nAllVerts); - int curIdx = 0; - //vertices - mesh verts - //iterate over all polys and create map for their vertices first... - for (int polyidx=0; polyidx0) - { - dvertices = new float[ndvertsuniq*3]; - } - for (int vi=0; vim_sharedvertex_map.size(); - if (nverts >= 0xffff) - return false; - //calculate count of tris - int nmeshpolys = meshobj->NumPolygons(); - npolys = nmeshpolys; - for (int p=0; pGetPolygon(p)->VertexCount(); - npolys+=vertcount-3; - } - - //create verts - vertices = new float[nverts*3]; - float* vert = vertices; - for (int vi=0; vim_sharedvertex_map[vi].empty() ? meshobj->GetVertexLocation(vi) : NULL; - if (pos) - copy_v3_v3(vert, pos); - else - { - memset(vert, 0, 3*sizeof(float)); //vertex isn't in any poly, set dummy zero coordinates - } - vert+=3; - } - - //create tris - polys = (unsigned short *)MEM_callocN(sizeof(unsigned short)*3*2*npolys, "BuildVertIndArrays polys"); - memset(polys, 0xff, sizeof(unsigned short)*3*2*npolys); - unsigned short *poly = polys; - RAS_Polygon* raspoly; - for (int p=0; pGetPolygon(p); - for (int v=0; vVertexCount()-2; v++) - { - poly[0] = raspoly->GetVertex(0)->getOrigIndex(); - for (size_t i=1; i<3; i++) - { - poly[i] = raspoly->GetVertex(v+i)->getOrigIndex(); - } - poly += 6; - } - } - dmeshes = NULL; - dvertices = NULL; - ndvertsuniq = 0; - dtris = NULL; - ndtris = npolys; - } - dm->release(dm); - - return true; -#endif - return false; -} - - -bool KX_NavMeshObject::BuildNavMesh() -{ - if (m_navMesh) - { - delete m_navMesh; - m_navMesh = NULL; - } - - if (GetMeshCount()==0) - { - printf("Can't find mesh for navmesh object: %s\n", m_name.ReadPtr()); - return false; - } - - float *vertices = NULL, *dvertices = NULL; - unsigned short *polys = NULL, *dtris = NULL, *dmeshes = NULL; - int nverts = 0, npolys = 0, ndvertsuniq = 0, ndtris = 0; - int vertsPerPoly = 0; - if (!BuildVertIndArrays(vertices, nverts, polys, npolys, - dmeshes, dvertices, ndvertsuniq, dtris, ndtris, vertsPerPoly ) - || vertsPerPoly<3) - { - printf("Can't build navigation mesh data for object:%s\n", m_name.ReadPtr()); - if (vertices) { - delete[] vertices; - } - if (dvertices) { - delete[] dvertices; - } - return false; - } - - MT_Point3 pos; - if (dmeshes==NULL) - { - for (int i=0; i((vertices[3*i+0]-bmin[0])*ics); - vertsi[3*i+1] = static_cast((vertices[3*i+1]-bmin[1])*ics); - vertsi[3*i+2] = static_cast((vertices[3*i+2]-bmin[2])*ics); - } - - // Calculate data size - const int headerSize = sizeof(dtStatNavMeshHeader); - const int vertsSize = sizeof(float)*3*nverts; - const int polysSize = sizeof(dtStatPoly)*npolys; - const int nodesSize = sizeof(dtStatBVNode)*npolys*2; - const int detailMeshesSize = sizeof(dtStatPolyDetail)*npolys; - const int detailVertsSize = sizeof(float)*3*ndvertsuniq; - const int detailTrisSize = sizeof(unsigned char)*4*ndtris; - - const int dataSize = headerSize + vertsSize + polysSize + nodesSize + - detailMeshesSize + detailVertsSize + detailTrisSize; - unsigned char* data = new unsigned char[dataSize]; - if (!data) - return false; - memset(data, 0, dataSize); - - unsigned char* d = data; - dtStatNavMeshHeader* header = (dtStatNavMeshHeader*)d; d += headerSize; - float* navVerts = (float*)d; d += vertsSize; - dtStatPoly* navPolys = (dtStatPoly*)d; d += polysSize; - dtStatBVNode* navNodes = (dtStatBVNode*)d; d += nodesSize; - dtStatPolyDetail* navDMeshes = (dtStatPolyDetail*)d; d += detailMeshesSize; - float* navDVerts = (float*)d; d += detailVertsSize; - unsigned char* navDTris = (unsigned char*)d; d += detailTrisSize; - - // Store header - header->magic = DT_STAT_NAVMESH_MAGIC; - header->version = DT_STAT_NAVMESH_VERSION; - header->npolys = npolys; - header->nverts = nverts; - header->cs = cs; - header->bmin[0] = bmin[0]; - header->bmin[1] = bmin[1]; - header->bmin[2] = bmin[2]; - header->bmax[0] = bmax[0]; - header->bmax[1] = bmax[1]; - header->bmax[2] = bmax[2]; - header->ndmeshes = npolys; - header->ndverts = ndvertsuniq; - header->ndtris = ndtris; - - // Store vertices - for (int i = 0; i < nverts; ++i) - { - const unsigned short* iv = &vertsi[i*3]; - float* v = &navVerts[i*3]; - v[0] = bmin[0] + iv[0] * cs; - v[1] = bmin[1] + iv[1] * cs; - v[2] = bmin[2] + iv[2] * cs; - } - //memcpy(navVerts, vertices, nverts*3*sizeof(float)); - - // Store polygons - const unsigned short* src = polys; - for (int i = 0; i < npolys; ++i) - { - dtStatPoly* p = &navPolys[i]; - p->nv = 0; - for (int j = 0; j < vertsPerPoly; ++j) - { - if (src[j] == 0xffff) break; - p->v[j] = src[j]; - p->n[j] = src[vertsPerPoly+j]+1; - p->nv++; - } - src += vertsPerPoly*2; - } - - header->nnodes = createBVTree(vertsi, nverts, polys, npolys, vertsPerPoly, - cs, cs, npolys*2, navNodes); - - - if (dmeshes==NULL) - { - //create fake detail meshes - for (int i = 0; i < npolys; ++i) - { - dtStatPolyDetail& dtl = navDMeshes[i]; - dtl.vbase = 0; - dtl.nverts = 0; - dtl.tbase = i; - dtl.ntris = 1; - } - // setup triangles. - unsigned char* tri = navDTris; - for (size_t i=0; iinit(data, dataSize, true); - - delete [] vertices; - - /* navmesh conversion is using C guarded alloc for memory allocaitons */ - MEM_freeN(polys); - if (dmeshes) MEM_freeN(dmeshes); - if (dtris) MEM_freeN(dtris); - - if (dvertices) - delete [] dvertices; - - if (vertsi) - delete [] vertsi; - - return true; -} - -dtStatNavMesh* KX_NavMeshObject::GetNavMesh() -{ - return m_navMesh; -} - -void KX_NavMeshObject::DrawNavMesh(NavMeshRenderMode renderMode) -{ - if (!m_navMesh) - return; - MT_Vector3 color(0.f, 0.f, 0.f); - - switch (renderMode) - { - case RM_POLYS : - case RM_WALLS : - for (int pi=0; pigetPolyCount(); pi++) - { - const dtStatPoly* poly = m_navMesh->getPoly(pi); - - for (int i = 0, j = (int)poly->nv-1; i < (int)poly->nv; j = i++) - { - if (poly->n[j] && renderMode==RM_WALLS) - continue; - const float* vif = m_navMesh->getVertex(poly->v[i]); - const float* vjf = m_navMesh->getVertex(poly->v[j]); - MT_Point3 vi(vif[0], vif[2], vif[1]); - MT_Point3 vj(vjf[0], vjf[2], vjf[1]); - vi = TransformToWorldCoords(vi); - vj = TransformToWorldCoords(vj); - KX_RasterizerDrawDebugLine(vi, vj, color); - } - } - break; - case RM_TRIS : - for (int i = 0; i < m_navMesh->getPolyDetailCount(); ++i) - { - const dtStatPoly* p = m_navMesh->getPoly(i); - const dtStatPolyDetail* pd = m_navMesh->getPolyDetail(i); - - for (int j = 0; j < pd->ntris; ++j) - { - const unsigned char* t = m_navMesh->getDetailTri(pd->tbase+j); - MT_Point3 tri[3]; - for (int k = 0; k < 3; ++k) - { - const float* v; - if (t[k] < p->nv) - v = m_navMesh->getVertex(p->v[t[k]]); - else - v = m_navMesh->getDetailVertex(pd->vbase+(t[k]-p->nv)); - float pos[3]; - rcVcopy(pos, v); - flipAxes(pos); - tri[k].setValue(pos); - } - - for (int k=0; k<3; k++) - tri[k] = TransformToWorldCoords(tri[k]); - - for (int k=0; k<3; k++) - KX_RasterizerDrawDebugLine(tri[k], tri[(k+1)%3], color); - } - } - break; - default: - /* pass */ - break; - } -} - -MT_Point3 KX_NavMeshObject::TransformToLocalCoords(const MT_Point3& wpos) -{ - MT_Matrix3x3 orientation = NodeGetWorldOrientation(); - const MT_Vector3& scaling = NodeGetWorldScaling(); - orientation.scale(scaling[0], scaling[1], scaling[2]); - MT_Transform worldtr(NodeGetWorldPosition(), orientation); - MT_Transform invworldtr; - invworldtr.invert(worldtr); - MT_Point3 lpos = invworldtr(wpos); - return lpos; -} - -MT_Point3 KX_NavMeshObject::TransformToWorldCoords(const MT_Point3& lpos) -{ - MT_Matrix3x3 orientation = NodeGetWorldOrientation(); - const MT_Vector3& scaling = NodeGetWorldScaling(); - orientation.scale(scaling[0], scaling[1], scaling[2]); - MT_Transform worldtr(NodeGetWorldPosition(), orientation); - MT_Point3 wpos = worldtr(lpos); - return wpos; -} - -int KX_NavMeshObject::FindPath(const MT_Point3& from, const MT_Point3& to, float* path, int maxPathLen) -{ - if (!m_navMesh) - return 0; - MT_Point3 localfrom = TransformToLocalCoords(from); - MT_Point3 localto = TransformToLocalCoords(to); - float spos[3], epos[3]; - localfrom.getValue(spos); flipAxes(spos); - localto.getValue(epos); flipAxes(epos); - dtStatPolyRef sPolyRef = m_navMesh->findNearestPoly(spos, polyPickExt); - dtStatPolyRef ePolyRef = m_navMesh->findNearestPoly(epos, polyPickExt); - - int pathLen = 0; - if (sPolyRef && ePolyRef) - { - dtStatPolyRef* polys = new dtStatPolyRef[maxPathLen]; - int npolys; - npolys = m_navMesh->findPath(sPolyRef, ePolyRef, spos, epos, polys, maxPathLen); - if (npolys) - { - pathLen = m_navMesh->findStraightPath(spos, epos, polys, npolys, path, maxPathLen); - for (int i=0; ifindNearestPoly(spos, polyPickExt); - float t=0; - static dtStatPolyRef polys[MAX_PATH_LEN]; - m_navMesh->raycast(sPolyRef, spos, epos, t, polys, MAX_PATH_LEN); - return t; -} - -void KX_NavMeshObject::DrawPath(const float *path, int pathLen, const MT_Vector3& color) -{ - MT_Vector3 a,b; - for (int i=0; i=0 && arg - -class RAS_MeshObject; -class MT_Transform; - -class KX_NavMeshObject: public KX_GameObject -{ - Py_Header - -protected: - dtStatNavMesh* m_navMesh; - - bool BuildVertIndArrays(float *&vertices, int& nverts, - unsigned short* &polys, int& npolys, unsigned short *&dmeshes, - float *&dvertices, int &ndvertsuniq, unsigned short* &dtris, - int& ndtris, int &vertsPerPoly); - -public: - KX_NavMeshObject(void* sgReplicationInfo, SG_Callbacks callbacks); - ~KX_NavMeshObject(); - - virtual CValue* GetReplica(); - virtual void ProcessReplica(); - - - bool BuildNavMesh(); - dtStatNavMesh* GetNavMesh(); - int FindPath(const MT_Point3& from, const MT_Point3& to, float* path, int maxPathLen); - float Raycast(const MT_Point3& from, const MT_Point3& to); - - enum NavMeshRenderMode {RM_WALLS, RM_POLYS, RM_TRIS, RM_MAX}; - void DrawNavMesh(NavMeshRenderMode mode); - void DrawPath(const float *path, int pathLen, const MT_Vector3& color); - - MT_Point3 TransformToLocalCoords(const MT_Point3& wpos); - MT_Point3 TransformToWorldCoords(const MT_Point3& lpos); -#ifdef WITH_PYTHON - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - - KX_PYMETHOD_DOC(KX_NavMeshObject, findPath); - KX_PYMETHOD_DOC(KX_NavMeshObject, raycast); - KX_PYMETHOD_DOC(KX_NavMeshObject, draw); - KX_PYMETHOD_DOC_NOARGS(KX_NavMeshObject, rebuild); -#endif /* WITH_PYTHON */ -}; - -#endif /* __KX_NAVMESHOBJECT_H__ */ diff --git a/source/gameengine/Ketsji/KX_NearSensor.cpp b/source/gameengine/Ketsji/KX_NearSensor.cpp deleted file mode 100644 index 92ab8f412d9..00000000000 --- a/source/gameengine/Ketsji/KX_NearSensor.cpp +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Sense if other objects are near - * - * - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_NearSensor.cpp - * \ingroup ketsji - */ - - -#include "KX_NearSensor.h" -#include "SCA_LogicManager.h" -#include "KX_GameObject.h" -#include "KX_TouchEventManager.h" -#include "KX_Scene.h" // needed to create a replica -#include "PHY_IPhysicsEnvironment.h" -#include "PHY_IPhysicsController.h" -#include "PHY_IMotionState.h" - -KX_NearSensor::KX_NearSensor(SCA_EventManager* eventmgr, - KX_GameObject* gameobj, - float margin, - float resetmargin, - bool bFindMaterial, - const STR_String& touchedpropname, - PHY_IPhysicsController* ctrl) - :KX_TouchSensor(eventmgr, - gameobj, - bFindMaterial, - false, - touchedpropname), - m_Margin(margin), - m_ResetMargin(resetmargin) - -{ - - gameobj->getClientInfo()->m_sensors.remove(this); - m_client_info = new KX_ClientObjectInfo(gameobj, KX_ClientObjectInfo::SENSOR); - m_client_info->m_sensors.push_back(this); - - //DT_ShapeHandle shape = (DT_ShapeHandle) vshape; - m_physCtrl = ctrl; - if (m_physCtrl) - { - m_physCtrl->SetMargin(m_Margin); - m_physCtrl->SetNewClientInfo(m_client_info); - } - SynchronizeTransform(); -} - -void KX_NearSensor::SynchronizeTransform() -{ - // The near and radar sensors are using a different physical object which is - // not linked to the parent object, must synchronize it. - if (m_physCtrl) - { - PHY_IMotionState* motionState = m_physCtrl->GetMotionState(); - KX_GameObject* parent = ((KX_GameObject*)GetParent()); - const MT_Point3& pos = parent->NodeGetWorldPosition(); - float ori[12]; - parent->NodeGetWorldOrientation().getValue(ori); - motionState->SetWorldPosition(pos[0], pos[1], pos[2]); - motionState->SetWorldOrientation(ori); - m_physCtrl->WriteMotionStateToDynamics(true); - } -} - -CValue* KX_NearSensor::GetReplica() -{ - KX_NearSensor* replica = new KX_NearSensor(*this); - replica->ProcessReplica(); - return replica; -} - -void KX_NearSensor::ProcessReplica() -{ - KX_TouchSensor::ProcessReplica(); - - m_client_info = new KX_ClientObjectInfo(m_client_info->m_gameobject, KX_ClientObjectInfo::SENSOR); - - if (m_physCtrl) - { - m_physCtrl = m_physCtrl->GetReplicaForSensors(); - if (m_physCtrl) - { - //static_cast(m_eventmgr)->GetPhysicsEnvironment()->addSensor(replica->m_physCtrl); - m_physCtrl->SetMargin(m_Margin); - m_physCtrl->SetNewClientInfo(m_client_info); - } - - } -} - -void KX_NearSensor::ReParent(SCA_IObject* parent) -{ - SCA_ISensor::ReParent(parent); - m_client_info->m_gameobject = static_cast(parent); - m_client_info->m_sensors.push_back(this); - //Synchronize here with the actual parent. - SynchronizeTransform(); -} - - - -KX_NearSensor::~KX_NearSensor() -{ - // for nearsensor, the sensor is the 'owner' of sumoobj - // for touchsensor, it's the parent - if (m_physCtrl) - { - //static_cast(m_eventmgr)->GetPhysicsEnvironment()->removeSensor(m_physCtrl); - delete m_physCtrl; - m_physCtrl = NULL; - } - - - if (m_client_info) - delete m_client_info; -} - -void KX_NearSensor::SetPhysCtrlRadius() -{ - if (m_bTriggered) - { - if (m_physCtrl) - { - m_physCtrl->SetRadius(m_ResetMargin); - } - } else - { - if (m_physCtrl) - { - m_physCtrl->SetRadius(m_Margin); - } - } -} - -bool KX_NearSensor::Evaluate() -{ - bool result = false; -// KX_GameObject* parent = static_cast(GetParent()); - - if (m_bTriggered != m_bLastTriggered) - { - m_bLastTriggered = m_bTriggered; - - SetPhysCtrlRadius(); - - result = true; - } - - return result; -} - -// this function is called at broad phase stage to check if the two controller -// need to interact at all. It is used for Near/Radar sensor that don't need to -// check collision with object not included in filter -bool KX_NearSensor::BroadPhaseFilterCollision(void*obj1,void*obj2) -{ - KX_GameObject* parent = static_cast(GetParent()); - - // need the mapping from PHY_IPhysicsController to gameobjects now - assert(obj1==m_physCtrl && obj2); - KX_ClientObjectInfo *client_info = static_cast((static_cast(obj2))->GetNewClientInfo()); - - KX_GameObject* gameobj = ( client_info ? - client_info->m_gameobject : - NULL); - - if (gameobj && (gameobj != parent)) - { - // only take valid colliders - if (client_info->m_type == KX_ClientObjectInfo::ACTOR) - { - if ((m_touchedpropname.Length() == 0) || - (gameobj->GetProperty(m_touchedpropname))) - { - return true; - } - } - } - - return false; -} - -bool KX_NearSensor::NewHandleCollision(void *obj1, void *obj2, const PHY_CollData *coll_data) -{ -// KX_TouchEventManager* toucheventmgr = static_cast(m_eventmgr); -// KX_GameObject* parent = static_cast(GetParent()); - - // need the mapping from PHY_IPhysicsController to gameobjects now - - KX_ClientObjectInfo *client_info = static_cast (obj1 == m_physCtrl? - ((PHY_IPhysicsController*)obj2)->GetNewClientInfo() : - ((PHY_IPhysicsController*)obj1)->GetNewClientInfo()); - - KX_GameObject* gameobj = ( client_info ? - client_info->m_gameobject : - NULL); - - // Add the same check as in SCA_ISensor::Activate(), - // we don't want to record collision when the sensor is not active. - if (m_links && !m_suspended && - gameobj /* done in BroadPhaseFilterCollision() && (gameobj != parent)*/) - { - if (!m_colliders->SearchValue(gameobj)) - m_colliders->Add(gameobj->AddRef()); - // only take valid colliders - // These checks are done already in BroadPhaseFilterCollision() - //if (client_info->m_type == KX_ClientObjectInfo::ACTOR) - //{ - // if ((m_touchedpropname.Length() == 0) || - // (gameobj->GetProperty(m_touchedpropname))) - // { - m_bTriggered = true; - m_hitObject = gameobj; - // } - //} - } - - return false; // was DT_CONTINUE; but this was defined in Sumo as false -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python Functions */ -/* ------------------------------------------------------------------------- */ - -/* ------------------------------------------------------------------------- */ -/* Python Integration Hooks */ -/* ------------------------------------------------------------------------- */ - -PyTypeObject KX_NearSensor::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_NearSensor", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &KX_TouchSensor::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_NearSensor::Methods[] = { - //No methods - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_NearSensor::Attributes[] = { - KX_PYATTRIBUTE_FLOAT_RW_CHECK("distance", 0, 10000, KX_NearSensor, m_Margin, CheckResetDistance), - KX_PYATTRIBUTE_FLOAT_RW_CHECK("resetDistance", 0, 10000, KX_NearSensor, m_ResetMargin, CheckResetDistance), - {NULL} //Sentinel -}; - -#endif // WITH_PYTHON diff --git a/source/gameengine/Ketsji/KX_NearSensor.h b/source/gameengine/Ketsji/KX_NearSensor.h deleted file mode 100644 index ef6e15f602f..00000000000 --- a/source/gameengine/Ketsji/KX_NearSensor.h +++ /dev/null @@ -1,107 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_NearSensor.h - * \ingroup ketsji - * \brief Sense if other objects are near - */ - -#ifndef __KX_NEARSENSOR_H__ -#define __KX_NEARSENSOR_H__ - -#include "KX_TouchSensor.h" -#include "KX_ClientObjectInfo.h" - -class KX_Scene; -struct PHY_CollData; - -class KX_NearSensor : public KX_TouchSensor -{ - Py_Header -protected: - float m_Margin; - float m_ResetMargin; - - KX_ClientObjectInfo* m_client_info; -public: - KX_NearSensor(class SCA_EventManager* eventmgr, - class KX_GameObject* gameobj, - float margin, - float resetmargin, - bool bFindMaterial, - const STR_String& touchedpropname, - PHY_IPhysicsController* ctrl); -#if 0 -public: - KX_NearSensor(class SCA_EventManager* eventmgr, - class KX_GameObject* gameobj, - double margin, - double resetmargin, - bool bFindMaterial, - const STR_String& touchedpropname, - class KX_Scene* scene); -#endif - virtual ~KX_NearSensor(); - virtual void SynchronizeTransform(); - virtual CValue* GetReplica(); - virtual void ProcessReplica(); - virtual void SetPhysCtrlRadius(); - virtual bool Evaluate(); - - virtual void ReParent(SCA_IObject* parent); - virtual bool NewHandleCollision(void* obj1,void* obj2, - const PHY_CollData * coll_data); - virtual bool BroadPhaseFilterCollision(void*obj1,void*obj2); - virtual bool BroadPhaseSensorFilterCollision(void* obj1,void* obj2) { return false; } - virtual sensortype GetSensorType() { return ST_NEAR; } - -#ifdef WITH_PYTHON - - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - - //No methods - - //This method is used to make sure the distance does not exceed the reset distance - static int CheckResetDistance(void *self, const PyAttributeDef*) - { - KX_NearSensor* sensor = reinterpret_cast(self); - - if (sensor->m_Margin > sensor->m_ResetMargin) - sensor->m_ResetMargin = sensor->m_Margin; - - sensor->SetPhysCtrlRadius(); - - return 0; - } - -#endif /* WITH_PYTHON */ - -}; - -#endif /* __KX_NEARSENSOR_H__ */ diff --git a/source/gameengine/Ketsji/KX_ObColorIpoSGController.cpp b/source/gameengine/Ketsji/KX_ObColorIpoSGController.cpp deleted file mode 100644 index 7f81f221c07..00000000000 --- a/source/gameengine/Ketsji/KX_ObColorIpoSGController.cpp +++ /dev/null @@ -1,110 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_ObColorIpoSGController.cpp - * \ingroup ketsji - */ - - -#include "KX_ObColorIpoSGController.h" -#include "KX_ScalarInterpolator.h" -#include "KX_GameObject.h" - -#if defined(_WIN64) -typedef unsigned __int64 uint_ptr; -#else -typedef unsigned long uint_ptr; -#endif - - -bool KX_ObColorIpoSGController::Update(double currentTime) -{ - if (m_modified) - { - SG_Spatial* ob = (SG_Spatial*)m_pObject; - KX_GameObject* kxgameobj= (KX_GameObject*) ob->GetSGClientObject(); - - m_rgba = kxgameobj->GetObjectColor(); - - T_InterpolatorList::iterator i; - for (i = m_interpolators.begin(); !(i == m_interpolators.end()); ++i) { - (*i)->Execute(m_ipotime); - } - - - kxgameobj->SetObjectColor(m_rgba); - - - m_modified=false; - } - return false; -} - - -void KX_ObColorIpoSGController::AddInterpolator(KX_IInterpolator* interp) -{ - this->m_interpolators.push_back(interp); -} - -SG_Controller* KX_ObColorIpoSGController::GetReplica(class SG_Node* destnode) -{ - KX_ObColorIpoSGController* iporeplica = new KX_ObColorIpoSGController(*this); - // clear object that ipo acts on - iporeplica->ClearObject(); - - // dirty hack, ask Gino for a better solution in the ipo implementation - // hacken en zagen, in what we call datahiding, not written for replication :( - - T_InterpolatorList oldlist = m_interpolators; - iporeplica->m_interpolators.clear(); - - T_InterpolatorList::iterator i; - for (i = oldlist.begin(); !(i == oldlist.end()); ++i) { - KX_ScalarInterpolator* copyipo = new KX_ScalarInterpolator(*((KX_ScalarInterpolator*)*i)); - iporeplica->AddInterpolator(copyipo); - - MT_Scalar* scaal = ((KX_ScalarInterpolator*)*i)->GetTarget(); - uint_ptr orgbase = (uint_ptr)this; - uint_ptr orgloc = (uint_ptr)scaal; - uint_ptr offset = orgloc-orgbase; - uint_ptr newaddrbase = (uint_ptr)iporeplica + offset; - MT_Scalar* blaptr = (MT_Scalar*) newaddrbase; - copyipo->SetNewTarget((MT_Scalar*)blaptr); - } - - return iporeplica; -} - -KX_ObColorIpoSGController::~KX_ObColorIpoSGController() -{ - - T_InterpolatorList::iterator i; - for (i = m_interpolators.begin(); !(i == m_interpolators.end()); ++i) { - delete (*i); - } - -} diff --git a/source/gameengine/Ketsji/KX_ObColorIpoSGController.h b/source/gameengine/Ketsji/KX_ObColorIpoSGController.h deleted file mode 100644 index a7b0b2c4ffc..00000000000 --- a/source/gameengine/Ketsji/KX_ObColorIpoSGController.h +++ /dev/null @@ -1,80 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_ObColorIpoSGController.h - * \ingroup ketsji - */ - -#ifndef __KX_OBCOLORIPOSGCONTROLLER_H__ -#define __KX_OBCOLORIPOSGCONTROLLER_H__ - -#include "SG_Controller.h" -#include "SG_Spatial.h" -#include "KX_IInterpolator.h" - -class KX_ObColorIpoSGController : public SG_Controller -{ -public: - MT_Vector4 m_rgba; - - -private: - T_InterpolatorList m_interpolators; - bool m_modified; - - double m_ipotime; -public: - KX_ObColorIpoSGController() : - m_modified(true), - m_ipotime(0.0) - {} - virtual ~KX_ObColorIpoSGController(); - virtual SG_Controller* GetReplica(class SG_Node* destnode); - virtual bool Update(double time); - virtual void SetSimulatedTime(double time) { - m_ipotime = time; - m_modified = true; - } - - void - SetOption( - int option, - int value - ) { - // intentionally empty - }; - - - void AddInterpolator(KX_IInterpolator* interp); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_ObColorIpoSGController") -#endif -}; - -#endif /* __KX_OBCOLORIPOSGCONTROLLER_H__ */ diff --git a/source/gameengine/Ketsji/KX_ObjectActuator.cpp b/source/gameengine/Ketsji/KX_ObjectActuator.cpp deleted file mode 100644 index 8c1dee7940f..00000000000 --- a/source/gameengine/Ketsji/KX_ObjectActuator.cpp +++ /dev/null @@ -1,709 +0,0 @@ -/* - * Do translation/rotation actions - * - * - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_ObjectActuator.cpp - * \ingroup ketsji - */ - -#include - -#include "KX_ObjectActuator.h" -#include "KX_GameObject.h" -#include "KX_PyMath.h" // For PyVecTo - should this include be put in PyObjectPlus? -#include "PHY_IPhysicsController.h" -#include "PHY_ICharacter.h" -#include "PHY_IPhysicsEnvironment.h" - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -KX_ObjectActuator:: -KX_ObjectActuator( - SCA_IObject* gameobj, - KX_GameObject* refobj, - const MT_Vector3& force, - const MT_Vector3& torque, - const MT_Vector3& dloc, - const MT_Vector3& drot, - const MT_Vector3& linV, - const MT_Vector3& angV, - const short damping, - const KX_LocalFlags& flag -) : - SCA_IActuator(gameobj, KX_ACT_OBJECT), - m_force(force), - m_torque(torque), - m_dloc(dloc), - m_drot(drot), - m_linear_velocity(linV), - m_angular_velocity(angV), - m_linear_length2(0.0f), - m_current_linear_factor(0.0f), - m_current_angular_factor(0.0f), - m_damping(damping), - m_previous_error(0.0f,0.0f,0.0f), - m_error_accumulator(0.0f,0.0f,0.0f), - m_bitLocalFlag (flag), - m_reference(refobj), - m_active_combined_velocity (false), - m_linear_damping_active(false), - m_angular_damping_active(false), - m_jumping(false) -{ - if (m_bitLocalFlag.ServoControl) - { - // in servo motion, the force is local if the target velocity is local - m_bitLocalFlag.Force = m_bitLocalFlag.LinearVelocity; - - m_pid = m_torque; - } - if (m_bitLocalFlag.CharacterMotion) - { - KX_GameObject *parent = static_cast(GetParent()); - PHY_ICharacter *character = parent->GetScene()->GetPhysicsEnvironment()->GetCharacterController(parent); - - if (!character) - { - printf("Character motion enabled on non-character object (%s), falling back to simple motion.\n", parent->GetName().Ptr()); - m_bitLocalFlag.CharacterMotion = false; - } - } - if (m_reference) - m_reference->RegisterActuator(this); - UpdateFuzzyFlags(); -} - -KX_ObjectActuator::~KX_ObjectActuator() -{ - if (m_reference) - m_reference->UnregisterActuator(this); -} - -bool KX_ObjectActuator::Update() -{ - - bool bNegativeEvent = IsNegativeEvent(); - RemoveAllEvents(); - - KX_GameObject *parent = static_cast(GetParent()); - PHY_ICharacter *character = parent->GetScene()->GetPhysicsEnvironment()->GetCharacterController(parent); - - if (bNegativeEvent) { - // If we previously set the linear velocity we now have to inform - // the physics controller that we no longer wish to apply it and that - // it should reconcile the externally set velocity with it's - // own velocity. - if (m_active_combined_velocity) { - if (parent) - parent->ResolveCombinedVelocities( - m_linear_velocity, - m_angular_velocity, - (m_bitLocalFlag.LinearVelocity) != 0, - (m_bitLocalFlag.AngularVelocity) != 0 - ); - m_active_combined_velocity = false; - } - - // Explicitly stop the movement if we're using character motion - if (m_bitLocalFlag.CharacterMotion) { - character->SetWalkDirection(MT_Vector3 (0.0f, 0.0f, 0.0f)); - } - - m_linear_damping_active = false; - m_angular_damping_active = false; - m_error_accumulator.setValue(0.0f,0.0f,0.0f); - m_previous_error.setValue(0.0f,0.0f,0.0f); - m_jumping = false; - return false; - - } else if (parent) - { - if (m_bitLocalFlag.ServoControl) - { - // In this mode, we try to reach a target speed using force - // As we don't know the friction, we must implement a generic - // servo control to achieve the speed in a configurable - // v = current velocity - // V = target velocity - // e = V-v = speed error - // dt = time interval since previous update - // I = sum(e(t)*dt) - // dv = e(t) - e(t-1) - // KP, KD, KI : coefficient - // F = KP*e+KI*I+KD*dv - MT_Scalar mass = parent->GetMass(); - if (mass < MT_EPSILON) - return false; - MT_Vector3 v = parent->GetLinearVelocity(m_bitLocalFlag.LinearVelocity); - if (m_reference) - { - const MT_Point3& mypos = parent->NodeGetWorldPosition(); - const MT_Point3& refpos = m_reference->NodeGetWorldPosition(); - MT_Point3 relpos; - relpos = (mypos-refpos); - MT_Vector3 vel= m_reference->GetVelocity(relpos); - if (m_bitLocalFlag.LinearVelocity) - // must convert in local space - vel = parent->NodeGetWorldOrientation().transposed()*vel; - v -= vel; - } - MT_Vector3 e = m_linear_velocity - v; - MT_Vector3 dv = e - m_previous_error; - MT_Vector3 I = m_error_accumulator + e; - - m_force = m_pid.x()*e+m_pid.y()*I+m_pid.z()*dv; - // to automatically adapt the PID coefficient to mass; - m_force *= mass; - if (m_bitLocalFlag.Torque) - { - if (m_force[0] > m_dloc[0]) - { - m_force[0] = m_dloc[0]; - I[0] = m_error_accumulator[0]; - } else if (m_force[0] < m_drot[0]) - { - m_force[0] = m_drot[0]; - I[0] = m_error_accumulator[0]; - } - } - if (m_bitLocalFlag.DLoc) - { - if (m_force[1] > m_dloc[1]) - { - m_force[1] = m_dloc[1]; - I[1] = m_error_accumulator[1]; - } else if (m_force[1] < m_drot[1]) - { - m_force[1] = m_drot[1]; - I[1] = m_error_accumulator[1]; - } - } - if (m_bitLocalFlag.DRot) - { - if (m_force[2] > m_dloc[2]) - { - m_force[2] = m_dloc[2]; - I[2] = m_error_accumulator[2]; - } else if (m_force[2] < m_drot[2]) - { - m_force[2] = m_drot[2]; - I[2] = m_error_accumulator[2]; - } - } - m_previous_error = e; - m_error_accumulator = I; - parent->ApplyForce(m_force,(m_bitLocalFlag.LinearVelocity) != 0); - } - else if (m_bitLocalFlag.CharacterMotion) { - MT_Vector3 dir = m_dloc; - - if (m_bitLocalFlag.DLoc) { - MT_Matrix3x3 basis = parent->GetPhysicsController()->GetOrientation(); - dir = basis * dir; - } - - if (m_bitLocalFlag.AddOrSetCharLoc) { - MT_Vector3 old_dir = character->GetWalkDirection(); - - if (!old_dir.fuzzyZero()) { - MT_Scalar mag = old_dir.length(); - - dir = dir + old_dir; - if (!dir.fuzzyZero()) - dir = dir.normalized() * mag; - } - } - - // We always want to set the walk direction since a walk direction of (0, 0, 0) should stop the character - character->SetWalkDirection(dir/parent->GetScene()->GetPhysicsEnvironment()->GetNumTimeSubSteps()); - - if (!m_bitLocalFlag.ZeroDRot) - { - parent->ApplyRotation(m_drot,(m_bitLocalFlag.DRot) != 0); - } - - if (m_bitLocalFlag.CharacterJump) { - if (!m_jumping) { - character->Jump(); - m_jumping = true; - } - else if (character->OnGround()) - m_jumping = false; - } - } - else { - if (!m_bitLocalFlag.ZeroForce) - { - parent->ApplyForce(m_force,(m_bitLocalFlag.Force) != 0); - } - if (!m_bitLocalFlag.ZeroTorque) - { - parent->ApplyTorque(m_torque,(m_bitLocalFlag.Torque) != 0); - } - if (!m_bitLocalFlag.ZeroDLoc) - { - parent->ApplyMovement(m_dloc,(m_bitLocalFlag.DLoc) != 0); - } - if (!m_bitLocalFlag.ZeroDRot) - { - parent->ApplyRotation(m_drot,(m_bitLocalFlag.DRot) != 0); - } - if (!m_bitLocalFlag.ZeroLinearVelocity) - { - if (m_bitLocalFlag.AddOrSetLinV) { - parent->addLinearVelocity(m_linear_velocity,(m_bitLocalFlag.LinearVelocity) != 0); - } else { - m_active_combined_velocity = true; - if (m_damping > 0) { - MT_Vector3 linV; - if (!m_linear_damping_active) { - // delta and the start speed (depends on the existing speed in that direction) - linV = parent->GetLinearVelocity(m_bitLocalFlag.LinearVelocity); - // keep only the projection along the desired direction - m_current_linear_factor = linV.dot(m_linear_velocity)/m_linear_length2; - m_linear_damping_active = true; - } - if (m_current_linear_factor < 1.0f) - m_current_linear_factor += 1.0f/m_damping; - if (m_current_linear_factor > 1.0f) - m_current_linear_factor = 1.0f; - linV = m_current_linear_factor * m_linear_velocity; - parent->setLinearVelocity(linV,(m_bitLocalFlag.LinearVelocity) != 0); - } else { - parent->setLinearVelocity(m_linear_velocity,(m_bitLocalFlag.LinearVelocity) != 0); - } - } - } - if (!m_bitLocalFlag.ZeroAngularVelocity) - { - m_active_combined_velocity = true; - if (m_damping > 0) { - MT_Vector3 angV; - if (!m_angular_damping_active) { - // delta and the start speed (depends on the existing speed in that direction) - angV = parent->GetAngularVelocity(m_bitLocalFlag.AngularVelocity); - // keep only the projection along the desired direction - m_current_angular_factor = angV.dot(m_angular_velocity)/m_angular_length2; - m_angular_damping_active = true; - } - if (m_current_angular_factor < 1.0f) - m_current_angular_factor += 1.0f/m_damping; - if (m_current_angular_factor > 1.0f) - m_current_angular_factor = 1.0f; - angV = m_current_angular_factor * m_angular_velocity; - parent->setAngularVelocity(angV,(m_bitLocalFlag.AngularVelocity) != 0); - } else { - parent->setAngularVelocity(m_angular_velocity,(m_bitLocalFlag.AngularVelocity) != 0); - } - } - } - - } - return true; -} - - - -CValue* KX_ObjectActuator::GetReplica() -{ - KX_ObjectActuator* replica = new KX_ObjectActuator(*this);//m_float,GetName()); - replica->ProcessReplica(); - - return replica; -} - -void KX_ObjectActuator::ProcessReplica() -{ - SCA_IActuator::ProcessReplica(); - if (m_reference) - m_reference->RegisterActuator(this); -} - -bool KX_ObjectActuator::UnlinkObject(SCA_IObject* clientobj) -{ - if (clientobj == (SCA_IObject*)m_reference) - { - // this object is being deleted, we cannot continue to use it as reference. - m_reference = NULL; - return true; - } - return false; -} - -void KX_ObjectActuator::Relink(CTR_Map *obj_map) -{ - void **h_obj = (*obj_map)[m_reference]; - if (h_obj) { - if (m_reference) - m_reference->UnregisterActuator(this); - m_reference = (KX_GameObject*)(*h_obj); - m_reference->RegisterActuator(this); - } -} - -/* some 'standard' utilities... */ -bool KX_ObjectActuator::isValid(KX_ObjectActuator::KX_OBJECT_ACT_VEC_TYPE type) -{ - bool res = false; - res = (type > KX_OBJECT_ACT_NODEF) && (type < KX_OBJECT_ACT_MAX); - return res; -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject KX_ObjectActuator::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_ObjectActuator", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &SCA_IActuator::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_ObjectActuator::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_ObjectActuator::Attributes[] = { - KX_PYATTRIBUTE_VECTOR_RW_CHECK("force", -1000, 1000, false, KX_ObjectActuator, m_force, PyUpdateFuzzyFlags), - KX_PYATTRIBUTE_BOOL_RW("useLocalForce", KX_ObjectActuator, m_bitLocalFlag.Force), - KX_PYATTRIBUTE_VECTOR_RW_CHECK("torque", -1000, 1000, false, KX_ObjectActuator, m_torque, PyUpdateFuzzyFlags), - KX_PYATTRIBUTE_BOOL_RW("useLocalTorque", KX_ObjectActuator, m_bitLocalFlag.Torque), - KX_PYATTRIBUTE_VECTOR_RW_CHECK("dLoc", -1000, 1000, false, KX_ObjectActuator, m_dloc, PyUpdateFuzzyFlags), - KX_PYATTRIBUTE_BOOL_RW("useLocalDLoc", KX_ObjectActuator, m_bitLocalFlag.DLoc), - KX_PYATTRIBUTE_VECTOR_RW_CHECK("dRot", -1000, 1000, false, KX_ObjectActuator, m_drot, PyUpdateFuzzyFlags), - KX_PYATTRIBUTE_BOOL_RW("useLocalDRot", KX_ObjectActuator, m_bitLocalFlag.DRot), -#ifdef USE_MATHUTILS - KX_PYATTRIBUTE_RW_FUNCTION("linV", KX_ObjectActuator, pyattr_get_linV, pyattr_set_linV), - KX_PYATTRIBUTE_RW_FUNCTION("angV", KX_ObjectActuator, pyattr_get_angV, pyattr_set_angV), -#else - KX_PYATTRIBUTE_VECTOR_RW_CHECK("linV", -1000, 1000, false, KX_ObjectActuator, m_linear_velocity, PyUpdateFuzzyFlags), - KX_PYATTRIBUTE_VECTOR_RW_CHECK("angV", -1000, 1000, false, KX_ObjectActuator, m_angular_velocity, PyUpdateFuzzyFlags), -#endif - KX_PYATTRIBUTE_BOOL_RW("useLocalLinV", KX_ObjectActuator, m_bitLocalFlag.LinearVelocity), - KX_PYATTRIBUTE_BOOL_RW("useLocalAngV", KX_ObjectActuator, m_bitLocalFlag.AngularVelocity), - KX_PYATTRIBUTE_SHORT_RW("damping", 0, 1000, false, KX_ObjectActuator, m_damping), - KX_PYATTRIBUTE_RW_FUNCTION("forceLimitX", KX_ObjectActuator, pyattr_get_forceLimitX, pyattr_set_forceLimitX), - KX_PYATTRIBUTE_RW_FUNCTION("forceLimitY", KX_ObjectActuator, pyattr_get_forceLimitY, pyattr_set_forceLimitY), - KX_PYATTRIBUTE_RW_FUNCTION("forceLimitZ", KX_ObjectActuator, pyattr_get_forceLimitZ, pyattr_set_forceLimitZ), - KX_PYATTRIBUTE_VECTOR_RW_CHECK("pid", -100, 200, true, KX_ObjectActuator, m_pid, PyCheckPid), - KX_PYATTRIBUTE_RW_FUNCTION("reference", KX_ObjectActuator,pyattr_get_reference,pyattr_set_reference), - { NULL } //Sentinel -}; - -/* Attribute get/set functions */ - -#ifdef USE_MATHUTILS - -/* These require an SGNode */ -#define MATHUTILS_VEC_CB_LINV 1 -#define MATHUTILS_VEC_CB_ANGV 2 - -static unsigned char mathutils_kxobactu_vector_cb_index = -1; /* index for our callbacks */ - -static int mathutils_obactu_generic_check(BaseMathObject *bmo) -{ - KX_ObjectActuator* self = static_castBGE_PROXY_REF(bmo->cb_user); - if (self == NULL) - return -1; - - return 0; -} - -static int mathutils_obactu_vector_get(BaseMathObject *bmo, int subtype) -{ - KX_ObjectActuator* self = static_castBGE_PROXY_REF(bmo->cb_user); - if (self == NULL) - return -1; - - switch (subtype) { - case MATHUTILS_VEC_CB_LINV: - self->m_linear_velocity.getValue(bmo->data); - break; - case MATHUTILS_VEC_CB_ANGV: - self->m_angular_velocity.getValue(bmo->data); - break; - } - - return 0; -} - -static int mathutils_obactu_vector_set(BaseMathObject *bmo, int subtype) -{ - KX_ObjectActuator* self = static_castBGE_PROXY_REF(bmo->cb_user); - if (self == NULL) - return -1; - - switch (subtype) { - case MATHUTILS_VEC_CB_LINV: - self->m_linear_velocity.setValue(bmo->data); - break; - case MATHUTILS_VEC_CB_ANGV: - self->m_angular_velocity.setValue(bmo->data); - break; - } - - return 0; -} - -static int mathutils_obactu_vector_get_index(BaseMathObject *bmo, int subtype, int index) -{ - /* lazy, avoid repeteing the case statement */ - if (mathutils_obactu_vector_get(bmo, subtype) == -1) - return -1; - return 0; -} - -static int mathutils_obactu_vector_set_index(BaseMathObject *bmo, int subtype, int index) -{ - float f = bmo->data[index]; - - /* lazy, avoid repeteing the case statement */ - if (mathutils_obactu_vector_get(bmo, subtype) == -1) - return -1; - - bmo->data[index] = f; - return mathutils_obactu_vector_set(bmo, subtype); -} - -static Mathutils_Callback mathutils_obactu_vector_cb = { - mathutils_obactu_generic_check, - mathutils_obactu_vector_get, - mathutils_obactu_vector_set, - mathutils_obactu_vector_get_index, - mathutils_obactu_vector_set_index -}; - -PyObject *KX_ObjectActuator::pyattr_get_linV(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - return Vector_CreatePyObject_cb( - BGE_PROXY_FROM_REF_BORROW(self_v), 3, - mathutils_kxobactu_vector_cb_index, MATHUTILS_VEC_CB_LINV); -} - -int KX_ObjectActuator::pyattr_set_linV(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_ObjectActuator* self = static_cast(self_v); - if (!PyVecTo(value, self->m_linear_velocity)) - return PY_SET_ATTR_FAIL; - - self->UpdateFuzzyFlags(); - - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_ObjectActuator::pyattr_get_angV(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - return Vector_CreatePyObject_cb( - BGE_PROXY_FROM_REF_BORROW(self_v), 3, - mathutils_kxobactu_vector_cb_index, MATHUTILS_VEC_CB_ANGV); -} - -int KX_ObjectActuator::pyattr_set_angV(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_ObjectActuator* self = static_cast(self_v); - if (!PyVecTo(value, self->m_angular_velocity)) - return PY_SET_ATTR_FAIL; - - self->UpdateFuzzyFlags(); - - return PY_SET_ATTR_SUCCESS; -} - - -void KX_ObjectActuator_Mathutils_Callback_Init(void) -{ - // register mathutils callbacks, ok to run more than once. - mathutils_kxobactu_vector_cb_index = Mathutils_RegisterCallback(&mathutils_obactu_vector_cb); -} - -#endif // USE_MATHUTILS - -PyObject *KX_ObjectActuator::pyattr_get_forceLimitX(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_ObjectActuator* self = reinterpret_cast(self_v); - PyObject *retVal = PyList_New(3); - - PyList_SET_ITEM(retVal, 0, PyFloat_FromDouble(self->m_drot[0])); - PyList_SET_ITEM(retVal, 1, PyFloat_FromDouble(self->m_dloc[0])); - PyList_SET_ITEM(retVal, 2, PyBool_FromLong(self->m_bitLocalFlag.Torque)); - - return retVal; -} - -int KX_ObjectActuator::pyattr_set_forceLimitX(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_ObjectActuator* self = reinterpret_cast(self_v); - - PyObject *seq = PySequence_Fast(value, ""); - if (seq && PySequence_Fast_GET_SIZE(seq) == 3) - { - self->m_drot[0] = PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, 0)); - self->m_dloc[0] = PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, 1)); - self->m_bitLocalFlag.Torque = (PyLong_AsLong(PySequence_Fast_GET_ITEM(value, 2)) != 0); - - if (!PyErr_Occurred()) - { - Py_DECREF(seq); - return PY_SET_ATTR_SUCCESS; - } - } - - Py_XDECREF(seq); - - PyErr_SetString(PyExc_ValueError, "expected a sequence of 2 floats and a bool"); - return PY_SET_ATTR_FAIL; -} - -PyObject *KX_ObjectActuator::pyattr_get_forceLimitY(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_ObjectActuator* self = reinterpret_cast(self_v); - PyObject *retVal = PyList_New(3); - - PyList_SET_ITEM(retVal, 0, PyFloat_FromDouble(self->m_drot[1])); - PyList_SET_ITEM(retVal, 1, PyFloat_FromDouble(self->m_dloc[1])); - PyList_SET_ITEM(retVal, 2, PyBool_FromLong(self->m_bitLocalFlag.DLoc)); - - return retVal; -} - -int KX_ObjectActuator::pyattr_set_forceLimitY(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_ObjectActuator* self = reinterpret_cast(self_v); - - PyObject *seq = PySequence_Fast(value, ""); - if (seq && PySequence_Fast_GET_SIZE(seq) == 3) - { - self->m_drot[1] = PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, 0)); - self->m_dloc[1] = PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, 1)); - self->m_bitLocalFlag.DLoc = (PyLong_AsLong(PySequence_Fast_GET_ITEM(value, 2)) != 0); - - if (!PyErr_Occurred()) - { - Py_DECREF(seq); - return PY_SET_ATTR_SUCCESS; - } - } - - Py_XDECREF(seq); - - PyErr_SetString(PyExc_ValueError, "expected a sequence of 2 floats and a bool"); - return PY_SET_ATTR_FAIL; -} - -PyObject *KX_ObjectActuator::pyattr_get_forceLimitZ(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_ObjectActuator* self = reinterpret_cast(self_v); - PyObject *retVal = PyList_New(3); - - PyList_SET_ITEM(retVal, 0, PyFloat_FromDouble(self->m_drot[2])); - PyList_SET_ITEM(retVal, 1, PyFloat_FromDouble(self->m_dloc[2])); - PyList_SET_ITEM(retVal, 2, PyBool_FromLong(self->m_bitLocalFlag.DRot)); - - return retVal; -} - -int KX_ObjectActuator::pyattr_set_forceLimitZ(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_ObjectActuator* self = reinterpret_cast(self_v); - - PyObject *seq = PySequence_Fast(value, ""); - if (seq && PySequence_Fast_GET_SIZE(seq) == 3) - { - self->m_drot[2] = PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, 0)); - self->m_dloc[2] = PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, 1)); - self->m_bitLocalFlag.DRot = (PyLong_AsLong(PySequence_Fast_GET_ITEM(value, 2)) != 0); - - if (!PyErr_Occurred()) - { - Py_DECREF(seq); - return PY_SET_ATTR_SUCCESS; - } - } - - Py_XDECREF(seq); - - PyErr_SetString(PyExc_ValueError, "expected a sequence of 2 floats and a bool"); - return PY_SET_ATTR_FAIL; -} - -PyObject *KX_ObjectActuator::pyattr_get_reference(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_ObjectActuator* actuator = static_cast(self); - if (!actuator->m_reference) - Py_RETURN_NONE; - - return actuator->m_reference->GetProxy(); -} - -int KX_ObjectActuator::pyattr_set_reference(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_ObjectActuator* actuator = static_cast(self); - KX_GameObject *refOb; - - if (!ConvertPythonToGameObject(actuator->GetLogicManager(), value, &refOb, true, "actu.reference = value: KX_ObjectActuator")) - return PY_SET_ATTR_FAIL; - - if (actuator->m_reference) - actuator->m_reference->UnregisterActuator(actuator); - - if (refOb==NULL) { - actuator->m_reference= NULL; - } - else { - actuator->m_reference = refOb; - actuator->m_reference->RegisterActuator(actuator); - } - - return PY_SET_ATTR_SUCCESS; -} - -#endif // WITH_PYTHON - -/* eof */ diff --git a/source/gameengine/Ketsji/KX_ObjectActuator.h b/source/gameengine/Ketsji/KX_ObjectActuator.h deleted file mode 100644 index 919c6acf03b..00000000000 --- a/source/gameengine/Ketsji/KX_ObjectActuator.h +++ /dev/null @@ -1,234 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_ObjectActuator.h - * \ingroup ketsji - * \brief Do translation/rotation actions - */ - -#ifndef __KX_OBJECTACTUATOR_H__ -#define __KX_OBJECTACTUATOR_H__ - -#include "SCA_IActuator.h" -#include "MT_Vector3.h" - -#ifdef USE_MATHUTILS -void KX_ObjectActuator_Mathutils_Callback_Init(void); -#endif - -class KX_GameObject; - -// -// Stores the flags for each CValue derived class -// -struct KX_LocalFlags { - KX_LocalFlags() : - Force(false), - Torque(false), - DRot(false), - DLoc(false), - LinearVelocity(false), - AngularVelocity(false), - AddOrSetLinV(false), - AddOrSetCharLoc(false), - ServoControl(false), - CharacterMotion(false), - CharacterJump(false), - ZeroForce(false), - ZeroTorque(false), - ZeroDRot(false), - ZeroDLoc(false), - ZeroLinearVelocity(false), - ZeroAngularVelocity(false) - { - } - - bool Force; - bool Torque; - bool DRot; - bool DLoc; - bool LinearVelocity; - bool AngularVelocity; - bool AddOrSetLinV; - bool AddOrSetCharLoc; - bool ServoControl; - bool CharacterMotion; - bool CharacterJump; - bool ZeroForce; - bool ZeroTorque; - bool ZeroDRot; - bool ZeroDLoc; - bool ZeroLinearVelocity; - bool ZeroAngularVelocity; -}; - -class KX_ObjectActuator : public SCA_IActuator -{ - Py_Header - - MT_Vector3 m_force; - MT_Vector3 m_torque; - MT_Vector3 m_dloc; - MT_Vector3 m_drot; - MT_Vector3 m_linear_velocity; - MT_Vector3 m_angular_velocity; - MT_Vector3 m_pid; - MT_Scalar m_linear_length2; - MT_Scalar m_angular_length2; - // used in damping - MT_Scalar m_current_linear_factor; - MT_Scalar m_current_angular_factor; - short m_damping; - // used in servo control - MT_Vector3 m_previous_error; - MT_Vector3 m_error_accumulator; - KX_LocalFlags m_bitLocalFlag; - KX_GameObject* m_reference; - // A hack bool -- oh no sorry everyone - // This bool is used to check if we have informed - // the physics object that we are no longer - // setting linear velocity. - - bool m_active_combined_velocity; - bool m_linear_damping_active; - bool m_angular_damping_active; - bool m_jumping; - -public: - enum KX_OBJECT_ACT_VEC_TYPE { - KX_OBJECT_ACT_NODEF = 0, - KX_OBJECT_ACT_FORCE, - KX_OBJECT_ACT_TORQUE, - KX_OBJECT_ACT_DLOC, - KX_OBJECT_ACT_DROT, - KX_OBJECT_ACT_LINEAR_VELOCITY, - KX_OBJECT_ACT_ANGULAR_VELOCITY, - KX_OBJECT_ACT_MAX - }; - - /** - * Check whether this is a valid vector mode - */ - bool isValid(KX_OBJECT_ACT_VEC_TYPE type); - - KX_ObjectActuator( - SCA_IObject* gameobj, - KX_GameObject* refobj, - const MT_Vector3& force, - const MT_Vector3& torque, - const MT_Vector3& dloc, - const MT_Vector3& drot, - const MT_Vector3& linV, - const MT_Vector3& angV, - const short damping, - const KX_LocalFlags& flag - ); - ~KX_ObjectActuator(); - CValue* GetReplica(); - void ProcessReplica(); - bool UnlinkObject(SCA_IObject* clientobj); - void Relink(CTR_Map *obj_map); - - void SetForceLoc(const double force[3]) { /*m_force=force;*/ } - void UpdateFuzzyFlags() - { - m_bitLocalFlag.ZeroForce = MT_fuzzyZero(m_force); - m_bitLocalFlag.ZeroTorque = MT_fuzzyZero(m_torque); - m_bitLocalFlag.ZeroDLoc = MT_fuzzyZero(m_dloc); - m_bitLocalFlag.ZeroDRot = MT_fuzzyZero(m_drot); - m_bitLocalFlag.ZeroLinearVelocity = MT_fuzzyZero(m_linear_velocity); - m_linear_length2 = (m_bitLocalFlag.ZeroLinearVelocity) ? 0.0f : m_linear_velocity.length2(); - m_bitLocalFlag.ZeroAngularVelocity = MT_fuzzyZero(m_angular_velocity); - m_angular_length2 = (m_bitLocalFlag.ZeroAngularVelocity) ? 0.0f : m_angular_velocity.length2(); - } - virtual bool Update(); - -#ifdef WITH_PYTHON - - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - - /* Attributes */ - static PyObject* pyattr_get_forceLimitX(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_forceLimitX(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_forceLimitY(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_forceLimitY(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_forceLimitZ(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_forceLimitZ(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_reference(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_reference(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - -#ifdef USE_MATHUTILS - static PyObject* pyattr_get_linV(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_linV(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_angV(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_angV(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); -#endif - - // This lets the attribute macros use UpdateFuzzyFlags() - static int PyUpdateFuzzyFlags(void *self, const PyAttributeDef *attrdef) - { - KX_ObjectActuator* act = reinterpret_cast(self); - act->UpdateFuzzyFlags(); - return 0; - } - - // This is the keep the PID values in check after they are assigned with Python - static int PyCheckPid(void *self, const PyAttributeDef *attrdef) - { - KX_ObjectActuator* act = reinterpret_cast(self); - - //P 0 to 200 - if (act->m_pid[0] < 0) { - act->m_pid[0] = 0; - } else if (act->m_pid[0] > 200) { - act->m_pid[0] = 200; - } - - //I 0 to 3 - if (act->m_pid[1] < 0) { - act->m_pid[1] = 0; - } else if (act->m_pid[1] > 3) { - act->m_pid[1] = 3; - } - - //D -100 to 100 - if (act->m_pid[2] < -100) { - act->m_pid[2] = -100; - } else if (act->m_pid[2] > 100) { - act->m_pid[2] = 100; - } - - return 0; - } - -#endif /* WITH_PYTHON */ - -}; - -#endif /* __KX_OBJECTACTUATOR_H__ */ diff --git a/source/gameengine/Ketsji/KX_ObstacleSimulation.cpp b/source/gameengine/Ketsji/KX_ObstacleSimulation.cpp deleted file mode 100644 index c84b2474c90..00000000000 --- a/source/gameengine/Ketsji/KX_ObstacleSimulation.cpp +++ /dev/null @@ -1,832 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_ObstacleSimulation.cpp - * \ingroup ketsji - * - * Simulation for obstacle avoidance behavior - */ - -#include "KX_ObstacleSimulation.h" -#include "KX_NavMeshObject.h" -#include "KX_PythonInit.h" -#include "DNA_object_types.h" -#include "BLI_math.h" - -namespace -{ - inline float perp(const MT_Vector2& a, const MT_Vector2& b) { return a.x()*b.y() - a.y()*b.x(); } - - inline float sqr(float x) { return x * x; } - inline float lerp(float a, float b, float t) { return a + (b - a) * t; } - inline float clamp(float a, float mn, float mx) { return a < mn ? mn : (a > mx ? mx : a); } - inline void vset(float v[2], float x, float y) { v[0] = x; v[1] = y; } -} - -/* grr, seems moto provides no nice way to do this */ -#define MT_3D_AS_2D(v) MT_Vector2((v)[0], (v)[1]) - -static int sweepCircleCircle( - const MT_Vector2 &pos0, const MT_Scalar r0, const MT_Vector2 &v, - const MT_Vector2 &pos1, const MT_Scalar r1, - float& tmin, float& tmax) -{ - static const float EPS = 0.0001f; - MT_Vector2 c0(pos0.x(), pos0.y()); - MT_Vector2 c1(pos1.x(), pos1.y()); - MT_Vector2 s = c1 - c0; - MT_Scalar r = r0+r1; - float c = s.length2() - r*r; - float a = v.length2(); - if (a < EPS) return 0; // not moving - - // Overlap, calc time to exit. - float b = MT_dot(v,s); - float d = b*b - a*c; - if (d < 0.0f) return 0; // no intersection. - tmin = (b - sqrtf(d)) / a; - tmax = (b + sqrtf(d)) / a; - return 1; -} - -static int sweepCircleSegment( - const MT_Vector2 &pos0, const MT_Scalar r0, const MT_Vector2 &v, - const MT_Vector2& pa, const MT_Vector2 &pb, const MT_Scalar sr, - float& tmin, float &tmax) -{ - // equation parameters - MT_Vector2 c0(pos0.x(), pos0.y()); - MT_Vector2 sa(pa.x(), pa.y()); - MT_Vector2 sb(pb.x(), pb.y()); - MT_Vector2 L = sb-sa; - MT_Vector2 H = c0-sa; - MT_Scalar radius = r0+sr; - float l2 = L.length2(); - float r2 = radius * radius; - float dl = perp(v, L); - float hl = perp(H, L); - float a = dl * dl; - float b = 2.0f * hl * dl; - float c = hl * hl - (r2 * l2); - float d = (b*b) - (4.0f * a * c); - - // infinite line missed by infinite ray. - if (d < 0.0f) - return 0; - - d = sqrtf(d); - tmin = (-b - d) / (2.0f * a); - tmax = (-b + d) / (2.0f * a); - - // line missed by ray range. - /* if (tmax < 0.0f || tmin > 1.0f) - return 0;*/ - - // find what part of the ray was collided. - MT_Vector2 Pedge; - Pedge = c0+v*tmin; - H = Pedge - sa; - float e0 = MT_dot(H, L) / l2; - Pedge = c0 + v*tmax; - H = Pedge - sa; - float e1 = MT_dot(H, L) / l2; - - if (e0 < 0.0f || e1 < 0.0f) - { - float ctmin, ctmax; - if (sweepCircleCircle(pos0, r0, v, pa, sr, ctmin, ctmax)) - { - if (e0 < 0.0f && ctmin > tmin) - tmin = ctmin; - if (e1 < 0.0f && ctmax < tmax) - tmax = ctmax; - } - else - { - return 0; - } - } - - if (e0 > 1.0f || e1 > 1.0f) - { - float ctmin, ctmax; - if (sweepCircleCircle(pos0, r0, v, pb, sr, ctmin, ctmax)) - { - if (e0 > 1.0f && ctmin > tmin) - tmin = ctmin; - if (e1 > 1.0f && ctmax < tmax) - tmax = ctmax; - } - else - { - return 0; - } - } - - return 1; -} - -static bool inBetweenAngle(float a, float amin, float amax, float& t) -{ - if (amax < amin) amax += (float)M_PI*2; - if (a < amin-(float)M_PI) a += (float)M_PI*2; - if (a > amin+(float)M_PI) a -= (float)M_PI*2; - if (a >= amin && a < amax) - { - t = (a-amin) / (amax-amin); - return true; - } - return false; -} - -static float interpolateToi(float a, const float* dir, const float* toi, const int ntoi) -{ - for (int i = 0; i < ntoi; ++i) - { - int next = (i+1) % ntoi; - float t; - if (inBetweenAngle(a, dir[i], dir[next], t)) - { - return lerp(toi[i], toi[next], t); - } - } - return 0; -} - -KX_ObstacleSimulation::KX_ObstacleSimulation(MT_Scalar levelHeight, bool enableVisualization) -: m_levelHeight(levelHeight) -, m_enableVisualization(enableVisualization) -{ - -} - -KX_ObstacleSimulation::~KX_ObstacleSimulation() -{ - for (size_t i=0; im_gameObj = gameobj; - - vset(obstacle->vel, 0,0); - vset(obstacle->pvel, 0,0); - vset(obstacle->dvel, 0,0); - vset(obstacle->nvel, 0,0); - for (int i = 0; i < VEL_HIST_SIZE; ++i) - vset(&obstacle->hvel[i*2], 0,0); - obstacle->hhead = 0; - - gameobj->RegisterObstacle(this); - m_obstacles.push_back(obstacle); - return obstacle; -} - -void KX_ObstacleSimulation::AddObstacleForObj(KX_GameObject* gameobj) -{ - KX_Obstacle* obstacle = CreateObstacle(gameobj); - struct Object* blenderobject = gameobj->GetBlenderObject(); - obstacle->m_type = KX_OBSTACLE_OBJ; - obstacle->m_shape = KX_OBSTACLE_CIRCLE; - obstacle->m_rad = blenderobject->obstacleRad; -} - -void KX_ObstacleSimulation::AddObstaclesForNavMesh(KX_NavMeshObject* navmeshobj) -{ - dtStatNavMesh* navmesh = navmeshobj->GetNavMesh(); - if (navmesh) - { - int npoly = navmesh->getPolyCount(); - for (int pi=0; pigetPoly(pi); - - for (int i = 0, j = (int)poly->nv-1; i < (int)poly->nv; j = i++) - { - if (poly->n[j]) continue; - const float* vj = navmesh->getVertex(poly->v[j]); - const float* vi = navmesh->getVertex(poly->v[i]); - - KX_Obstacle* obstacle = CreateObstacle(navmeshobj); - obstacle->m_type = KX_OBSTACLE_NAV_MESH; - obstacle->m_shape = KX_OBSTACLE_SEGMENT; - obstacle->m_pos = MT_Point3(vj[0], vj[2], vj[1]); - obstacle->m_pos2 = MT_Point3(vi[0], vi[2], vi[1]); - obstacle->m_rad = 0; - } - } - } -} - -void KX_ObstacleSimulation::DestroyObstacleForObj(KX_GameObject* gameobj) -{ - for (size_t i=0; im_gameObj == gameobj) - { - KX_Obstacle* obstacle = m_obstacles[i]; - obstacle->m_gameObj->UnregisterObstacle(); - m_obstacles[i] = m_obstacles.back(); - m_obstacles.pop_back(); - delete obstacle; - } - else - i++; - } -} - -void KX_ObstacleSimulation::UpdateObstacles() -{ - for (size_t i=0; im_type==KX_OBSTACLE_NAV_MESH || m_obstacles[i]->m_shape==KX_OBSTACLE_SEGMENT) - continue; - - KX_Obstacle* obs = m_obstacles[i]; - obs->m_pos = obs->m_gameObj->NodeGetWorldPosition(); - obs->vel[0] = obs->m_gameObj->GetLinearVelocity().x(); - obs->vel[1] = obs->m_gameObj->GetLinearVelocity().y(); - - // Update velocity history and calculate perceived (average) velocity. - copy_v2_v2(&obs->hvel[obs->hhead * 2], obs->vel); - obs->hhead = (obs->hhead+1) % VEL_HIST_SIZE; - vset(obs->pvel,0,0); - for (int j = 0; j < VEL_HIST_SIZE; ++j) - add_v2_v2v2(obs->pvel, obs->pvel, &obs->hvel[j * 2]); - mul_v2_fl(obs->pvel, 1.0f / VEL_HIST_SIZE); - } -} - -KX_Obstacle* KX_ObstacleSimulation::GetObstacle(KX_GameObject* gameobj) -{ - for (size_t i=0; im_gameObj == gameobj) - return m_obstacles[i]; - } - - return NULL; -} - -void KX_ObstacleSimulation::AdjustObstacleVelocity(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj, - MT_Vector3& velocity, MT_Scalar maxDeltaSpeed,MT_Scalar maxDeltaAngle) -{ -} - -void KX_ObstacleSimulation::DrawObstacles() -{ - if (!m_enableVisualization) - return; - static const MT_Vector3 bluecolor(0,0,1); - static const MT_Vector3 normal(0.0f, 0.0f, 1.0f); - static const int SECTORS_NUM = 32; - for (size_t i=0; im_shape==KX_OBSTACLE_SEGMENT) - { - MT_Point3 p1 = m_obstacles[i]->m_pos; - MT_Point3 p2 = m_obstacles[i]->m_pos2; - //apply world transform - if (m_obstacles[i]->m_type == KX_OBSTACLE_NAV_MESH) - { - KX_NavMeshObject* navmeshobj = static_cast(m_obstacles[i]->m_gameObj); - p1 = navmeshobj->TransformToWorldCoords(p1); - p2 = navmeshobj->TransformToWorldCoords(p2); - } - - KX_RasterizerDrawDebugLine(p1, p2, bluecolor); - } - else if (m_obstacles[i]->m_shape==KX_OBSTACLE_CIRCLE) - { - KX_RasterizerDrawDebugCircle(m_obstacles[i]->m_pos, m_obstacles[i]->m_rad, bluecolor, - normal, SECTORS_NUM); - } - } -} - -static MT_Point3 nearestPointToObstacle(MT_Point3& pos ,KX_Obstacle* obstacle) -{ - switch (obstacle->m_shape) - { - case KX_OBSTACLE_SEGMENT : - { - MT_Vector3 ab = obstacle->m_pos2 - obstacle->m_pos; - if (!ab.fuzzyZero()) - { - const MT_Scalar dist = ab.length(); - MT_Vector3 abdir = ab.normalized(); - MT_Vector3 v = pos - obstacle->m_pos; - MT_Scalar proj = abdir.dot(v); - CLAMP(proj, 0, dist); - MT_Point3 res = obstacle->m_pos + abdir*proj; - return res; - } - ATTR_FALLTHROUGH; - } - case KX_OBSTACLE_CIRCLE : - default: - return obstacle->m_pos; - } -} - -static bool filterObstacle(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj, KX_Obstacle* otherObst, - float levelHeight) -{ - //filter obstacles by type - if ( (otherObst == activeObst) || - (otherObst->m_type==KX_OBSTACLE_NAV_MESH && otherObst->m_gameObj!=activeNavMeshObj) ) - return false; - - //filter obstacles by position - MT_Point3 p = nearestPointToObstacle(activeObst->m_pos, otherObst); - if ( fabsf(activeObst->m_pos.z() - p.z()) > levelHeight) - return false; - - return true; -} - -///////////*********TOI_rays**********///////////////// -KX_ObstacleSimulationTOI::KX_ObstacleSimulationTOI(MT_Scalar levelHeight, bool enableVisualization) -: KX_ObstacleSimulation(levelHeight, enableVisualization), - m_maxSamples(32), - m_minToi(0.0f), - m_maxToi(0.0f), - m_velWeight(1.0f), - m_curVelWeight(1.0f), - m_toiWeight(1.0f), - m_collisionWeight(1.0f) -{ -} - - -void KX_ObstacleSimulationTOI::AdjustObstacleVelocity(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj, - MT_Vector3& velocity, MT_Scalar maxDeltaSpeed, MT_Scalar maxDeltaAngle) -{ - int nobs = m_obstacles.size(); - int obstidx = std::find(m_obstacles.begin(), m_obstacles.end(), activeObst) - m_obstacles.begin(); - if (obstidx == nobs) - return; - - vset(activeObst->dvel, velocity.x(), velocity.y()); - - //apply RVO - sampleRVO(activeObst, activeNavMeshObj, maxDeltaAngle); - - // Fake dynamic constraint. - float dv[2]; - float vel[2]; - sub_v2_v2v2(dv, activeObst->nvel, activeObst->vel); - float ds = len_v2(dv); - if (ds > maxDeltaSpeed || ds<-maxDeltaSpeed) - mul_v2_fl(dv, fabs(maxDeltaSpeed / ds)); - add_v2_v2v2(vel, activeObst->vel, dv); - - velocity.x() = vel[0]; - velocity.y() = vel[1]; -} - -///////////*********TOI_rays**********///////////////// -static const int AVOID_MAX_STEPS = 128; -struct TOICircle -{ - TOICircle() : n(0), minToi(0), maxToi(1) {} - float toi[AVOID_MAX_STEPS]; // Time of impact (seconds) - float toie[AVOID_MAX_STEPS]; // Time of exit (seconds) - float dir[AVOID_MAX_STEPS]; // Direction (radians) - int n; // Number of samples - float minToi, maxToi; // Min/max TOI (seconds) -}; - -KX_ObstacleSimulationTOI_rays::KX_ObstacleSimulationTOI_rays(MT_Scalar levelHeight, bool enableVisualization): - KX_ObstacleSimulationTOI(levelHeight, enableVisualization) -{ - m_maxSamples = 32; - m_minToi = 0.5f; - m_maxToi = 1.2f; - m_velWeight = 4.0f; - m_toiWeight = 1.0f; - m_collisionWeight = 100.0f; -} - - -void KX_ObstacleSimulationTOI_rays::sampleRVO(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj, - const float maxDeltaAngle) -{ - MT_Vector2 vel(activeObst->dvel[0], activeObst->dvel[1]); - float vmax = (float) vel.length(); - float odir = (float) atan2(vel.y(), vel.x()); - - MT_Vector2 ddir = vel; - ddir.normalize(); - - float bestScore = FLT_MAX; - float bestDir = odir; - float bestToi = 0; - - TOICircle tc; - tc.n = m_maxSamples; - tc.minToi = m_minToi; - tc.maxToi = m_maxToi; - - const int iforw = m_maxSamples/2; - const float aoff = (float)iforw / (float)m_maxSamples; - - size_t nobs = m_obstacles.size(); - for (int iter = 0; iter < m_maxSamples; ++iter) - { - // Calculate sample velocity - const float ndir = ((float)iter/(float)m_maxSamples) - aoff; - const float dir = odir+ndir*(float)M_PI*2.0f; - MT_Vector2 svel; - svel.x() = cosf(dir) * vmax; - svel.y() = sinf(dir) * vmax; - - // Find min time of impact and exit amongst all obstacles. - float tmin = m_maxToi; - float tmine = 0.0f; - for (int i = 0; i < nobs; ++i) - { - KX_Obstacle* ob = m_obstacles[i]; - bool res = filterObstacle(activeObst, activeNavMeshObj, ob, m_levelHeight); - if (!res) - continue; - - float htmin,htmax; - - if (ob->m_shape == KX_OBSTACLE_CIRCLE) - { - MT_Vector2 vab; - if (len_v2(ob->vel) < 0.01f * 0.01f) { - // Stationary, use VO - vab = svel; - } - else - { - // Moving, use RVO - vab = 2*svel - vel - ob->vel; - } - - if (!sweepCircleCircle(MT_3D_AS_2D(activeObst->m_pos), activeObst->m_rad, - vab, MT_3D_AS_2D(ob->m_pos), ob->m_rad, htmin, htmax)) - { - continue; - } - } - else if (ob->m_shape == KX_OBSTACLE_SEGMENT) - { - MT_Point3 p1 = ob->m_pos; - MT_Point3 p2 = ob->m_pos2; - //apply world transform - if (ob->m_type == KX_OBSTACLE_NAV_MESH) - { - KX_NavMeshObject* navmeshobj = static_cast(ob->m_gameObj); - p1 = navmeshobj->TransformToWorldCoords(p1); - p2 = navmeshobj->TransformToWorldCoords(p2); - } - - if (!sweepCircleSegment(MT_3D_AS_2D(activeObst->m_pos), activeObst->m_rad, svel, - MT_3D_AS_2D(p1), MT_3D_AS_2D(p2), ob->m_rad, htmin, htmax)) - { - continue; - } - } - else { - continue; - } - - if (htmin > 0.0f) - { - // The closest obstacle is somewhere ahead of us, keep track of nearest obstacle. - if (htmin < tmin) - tmin = htmin; - } - else if (htmax > 0.0f) - { - // The agent overlaps the obstacle, keep track of first safe exit. - if (htmax > tmine) - tmine = htmax; - } - } - - // Calculate sample penalties and final score. - const float apen = m_velWeight * fabsf(ndir); - const float tpen = m_toiWeight * (1.0f/(0.0001f+tmin/m_maxToi)); - const float cpen = m_collisionWeight * (tmine/m_minToi)*(tmine/m_minToi); - const float score = apen + tpen + cpen; - - // Update best score. - if (score < bestScore) - { - bestDir = dir; - bestToi = tmin; - bestScore = score; - } - - tc.dir[iter] = dir; - tc.toi[iter] = tmin; - tc.toie[iter] = tmine; - } - - if (len_v2(activeObst->vel) > 0.1f) { - // Constrain max turn rate. - float cura = atan2(activeObst->vel[1],activeObst->vel[0]); - float da = bestDir - cura; - if (da < -M_PI) da += (float)M_PI*2; - if (da > M_PI) da -= (float)M_PI*2; - if (da < -maxDeltaAngle) - { - bestDir = cura - maxDeltaAngle; - bestToi = min(bestToi, interpolateToi(bestDir, tc.dir, tc.toi, tc.n)); - } - else if (da > maxDeltaAngle) - { - bestDir = cura + maxDeltaAngle; - bestToi = min(bestToi, interpolateToi(bestDir, tc.dir, tc.toi, tc.n)); - } - } - - // Adjust speed when time of impact is less than min TOI. - if (bestToi < m_minToi) - vmax *= bestToi/m_minToi; - - // New steering velocity. - activeObst->nvel[0] = cosf(bestDir) * vmax; - activeObst->nvel[1] = sinf(bestDir) * vmax; -} - -///////////********* TOI_cells**********///////////////// - -static void processSamples(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj, - KX_Obstacles& obstacles, float levelHeight, const float vmax, - const float* spos, const float cs, const int nspos, float* res, - float maxToi, float velWeight, float curVelWeight, float sideWeight, - float toiWeight) -{ - vset(res, 0,0); - - const float ivmax = 1.0f / vmax; - - float adir[2] /*, adist */; - if (normalize_v2_v2(adir, activeObst->pvel) <= 0.01f) { - zero_v2(adir); - } - - float activeObstPos[2]; - vset(activeObstPos, activeObst->m_pos.x(), activeObst->m_pos.y()); - /* adist = vdot(adir, activeObstPos); */ - - float minPenalty = FLT_MAX; - - for (int n = 0; n < nspos; ++n) - { - float vcand[2]; - copy_v2_v2(vcand, &spos[n * 2]); - - // Find min time of impact and exit amongst all obstacles. - float tmin = maxToi; - float side = 0; - int nside = 0; - - for (int i = 0; i < obstacles.size(); ++i) - { - KX_Obstacle* ob = obstacles[i]; - bool res = filterObstacle(activeObst, activeNavMeshObj, ob, levelHeight); - if (!res) - continue; - float htmin, htmax; - - if (ob->m_shape==KX_OBSTACLE_CIRCLE) - { - float vab[2]; - - // Moving, use RVO - mul_v2_v2fl(vab, vcand, 2); - sub_v2_v2v2(vab, vab, activeObst->vel); - sub_v2_v2v2(vab, vab, ob->vel); - - // Side - // NOTE: dp, and dv are constant over the whole calculation, - // they can be precomputed per object. - const float* pa = activeObstPos; - float pb[2]; - vset(pb, ob->m_pos.x(), ob->m_pos.y()); - - const float orig[2] = {0, 0}; - float dp[2], dv[2], np[2]; - sub_v2_v2v2(dp, pb, pa); - normalize_v2(dp); - sub_v2_v2v2(dv, ob->dvel, activeObst->dvel); - - /* TODO: use line_point_side_v2 */ - if (area_tri_signed_v2(orig, dp, dv) < 0.01f) { - np[0] = -dp[1]; - np[1] = dp[0]; - } - else { - np[0] = dp[1]; - np[1] = -dp[0]; - } - - side += clamp(min(dot_v2v2(dp, vab), - dot_v2v2(np, vab)) * 2.0f, 0.0f, 1.0f); - nside++; - - if (!sweepCircleCircle(MT_3D_AS_2D(activeObst->m_pos), activeObst->m_rad, - vab, MT_3D_AS_2D(ob->m_pos), ob->m_rad, htmin, htmax)) - { - continue; - } - - // Handle overlapping obstacles. - if (htmin < 0.0f && htmax > 0.0f) - { - // Avoid more when overlapped. - htmin = -htmin * 0.5f; - } - } - else if (ob->m_shape == KX_OBSTACLE_SEGMENT) - { - MT_Point3 p1 = ob->m_pos; - MT_Point3 p2 = ob->m_pos2; - //apply world transform - if (ob->m_type == KX_OBSTACLE_NAV_MESH) - { - KX_NavMeshObject* navmeshobj = static_cast(ob->m_gameObj); - p1 = navmeshobj->TransformToWorldCoords(p1); - p2 = navmeshobj->TransformToWorldCoords(p2); - } - float p[2], q[2]; - vset(p, p1.x(), p1.y()); - vset(q, p2.x(), p2.y()); - - // NOTE: the segments are assumed to come from a navmesh which is shrunken by - // the agent radius, hence the use of really small radius. - // This can be handle more efficiently by using seg-seg test instead. - // If the whole segment is to be treated as obstacle, use agent->rad instead of 0.01f! - const float r = 0.01f; // agent->rad - if (dist_squared_to_line_segment_v2(activeObstPos, p, q) < sqr(r + ob->m_rad)) { - float sdir[2], snorm[2]; - sub_v2_v2v2(sdir, q, p); - snorm[0] = sdir[1]; - snorm[1] = -sdir[0]; - // If the velocity is pointing towards the segment, no collision. - if (dot_v2v2(snorm, vcand) < 0.0f) - continue; - // Else immediate collision. - htmin = 0.0f; - htmax = 10.0f; - } - else - { - if (!sweepCircleSegment(activeObstPos, r, vcand, p, q, ob->m_rad, htmin, htmax)) - continue; - } - - // Avoid less when facing walls. - htmin *= 2.0f; - } - else { - continue; - } - - if (htmin >= 0.0f) - { - // The closest obstacle is somewhere ahead of us, keep track of nearest obstacle. - if (htmin < tmin) - tmin = htmin; - } - } - - // Normalize side bias, to prevent it dominating too much. - if (nside) - side /= nside; - - const float vpen = velWeight * (len_v2v2(vcand, activeObst->dvel) * ivmax); - const float vcpen = curVelWeight * (len_v2v2(vcand, activeObst->vel) * ivmax); - const float spen = sideWeight * side; - const float tpen = toiWeight * (1.0f/(0.1f+tmin/maxToi)); - - const float penalty = vpen + vcpen + spen + tpen; - - if (penalty < minPenalty) { - minPenalty = penalty; - copy_v2_v2(res, vcand); - } - } -} - -void KX_ObstacleSimulationTOI_cells::sampleRVO(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj, - const float maxDeltaAngle) -{ - vset(activeObst->nvel, 0.f, 0.f); - float vmax = len_v2(activeObst->dvel); - - float* spos = new float[2*m_maxSamples]; - int nspos = 0; - - if (!m_adaptive) - { - const float cvx = activeObst->dvel[0]*m_bias; - const float cvy = activeObst->dvel[1]*m_bias; - float vmax = len_v2(activeObst->dvel); - const float vrange = vmax*(1-m_bias); - const float cs = 1.0f / (float)m_sampleRadius*vrange; - - for (int y = -m_sampleRadius; y <= m_sampleRadius; ++y) - { - for (int x = -m_sampleRadius; x <= m_sampleRadius; ++x) - { - if (nspos < m_maxSamples) - { - const float vx = cvx + (float)(x+0.5f)*cs; - const float vy = cvy + (float)(y+0.5f)*cs; - if (vx*vx+vy*vy > sqr(vmax+cs/2)) continue; - spos[nspos*2+0] = vx; - spos[nspos*2+1] = vy; - nspos++; - } - } - } - processSamples(activeObst, activeNavMeshObj, m_obstacles, m_levelHeight, vmax, spos, cs/2, - nspos, activeObst->nvel, m_maxToi, m_velWeight, m_curVelWeight, m_collisionWeight, m_toiWeight); - } - else - { - int rad; - float res[2]; - float cs; - // First sample location. - rad = 4; - res[0] = activeObst->dvel[0]*m_bias; - res[1] = activeObst->dvel[1]*m_bias; - cs = vmax*(2-m_bias*2) / (float)(rad-1); - - for (int k = 0; k < 5; ++k) - { - const float half = (rad-1)*cs*0.5f; - - nspos = 0; - for (int y = 0; y < rad; ++y) - { - for (int x = 0; x < rad; ++x) - { - const float v_xy[2] = { - res[0] + x * cs - half, - res[1] + y * cs - half}; - - if (len_squared_v2(v_xy) > sqr(vmax + cs / 2)) - continue; - - copy_v2_v2(&spos[nspos * 2 + 0], v_xy); - nspos++; - } - } - - processSamples(activeObst, activeNavMeshObj, m_obstacles, m_levelHeight, vmax, spos, cs/2, - nspos, res, m_maxToi, m_velWeight, m_curVelWeight, m_collisionWeight, m_toiWeight); - - cs *= 0.5f; - } - copy_v2_v2(activeObst->nvel, res); - } - - delete [] spos; -} - -KX_ObstacleSimulationTOI_cells::KX_ObstacleSimulationTOI_cells(MT_Scalar levelHeight, bool enableVisualization) -: KX_ObstacleSimulationTOI(levelHeight, enableVisualization) -, m_bias(0.4f) -, m_adaptive(true) -, m_sampleRadius(15) -{ - m_maxSamples = (m_sampleRadius*2+1)*(m_sampleRadius*2+1) + 100; - m_maxToi = 1.5f; - m_velWeight = 2.0f; - m_curVelWeight = 0.75f; - m_toiWeight = 2.5f; - m_collisionWeight = 0.75f; //side_weight -} diff --git a/source/gameengine/Ketsji/KX_ObstacleSimulation.h b/source/gameengine/Ketsji/KX_ObstacleSimulation.h deleted file mode 100644 index 50589b5bc69..00000000000 --- a/source/gameengine/Ketsji/KX_ObstacleSimulation.h +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Simulation for obstacle avoidance behavior - * (based on Cane Project - http://code.google.com/p/cane by Mikko Mononen (c) 2009) - * - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -#ifndef __KX_OBSTACLESIMULATION_H__ -#define __KX_OBSTACLESIMULATION_H__ - -#include -#include "MT_Point2.h" -#include "MT_Point3.h" - -class KX_GameObject; -class KX_NavMeshObject; - -enum KX_OBSTACLE_TYPE -{ - KX_OBSTACLE_OBJ, - KX_OBSTACLE_NAV_MESH, -}; - -enum KX_OBSTACLE_SHAPE -{ - KX_OBSTACLE_CIRCLE, - KX_OBSTACLE_SEGMENT, -}; - -#define VEL_HIST_SIZE 6 -struct KX_Obstacle -{ - KX_OBSTACLE_TYPE m_type; - KX_OBSTACLE_SHAPE m_shape; - MT_Point3 m_pos; - MT_Point3 m_pos2; - MT_Scalar m_rad; - - float vel[2]; - float pvel[2]; - float dvel[2]; - float nvel[2]; - float hvel[VEL_HIST_SIZE*2]; - int hhead; - - - KX_GameObject* m_gameObj; -}; -typedef std::vector KX_Obstacles; - -class KX_ObstacleSimulation -{ -protected: - KX_Obstacles m_obstacles; - - MT_Scalar m_levelHeight; - bool m_enableVisualization; - - KX_Obstacle* CreateObstacle(KX_GameObject* gameobj); -public: - KX_ObstacleSimulation(MT_Scalar levelHeight, bool enableVisualization); - virtual ~KX_ObstacleSimulation(); - - void DrawObstacles(); - //void DebugDraw(); - - void AddObstacleForObj(KX_GameObject* gameobj); - void DestroyObstacleForObj(KX_GameObject* gameobj); - void AddObstaclesForNavMesh(KX_NavMeshObject* navmesh); - KX_Obstacle* GetObstacle(KX_GameObject* gameobj); - void UpdateObstacles(); - virtual void AdjustObstacleVelocity(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj, - MT_Vector3& velocity, MT_Scalar maxDeltaSpeed,MT_Scalar maxDeltaAngle); - -}; -class KX_ObstacleSimulationTOI: public KX_ObstacleSimulation -{ -protected: - int m_maxSamples; // Number of sample steps - float m_minToi; // Min TOI - float m_maxToi; // Max TOI - float m_velWeight; // Sample selection angle weight - float m_curVelWeight; // Sample selection current velocity weight - float m_toiWeight; // Sample selection TOI weight - float m_collisionWeight; // Sample selection collision weight - - virtual void sampleRVO(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj, - const float maxDeltaAngle) = 0; -public: - KX_ObstacleSimulationTOI(MT_Scalar levelHeight, bool enableVisualization); - virtual void AdjustObstacleVelocity(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj, - MT_Vector3& velocity, MT_Scalar maxDeltaSpeed,MT_Scalar maxDeltaAngle); -}; - -class KX_ObstacleSimulationTOI_rays: public KX_ObstacleSimulationTOI -{ -protected: - virtual void sampleRVO(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj, - const float maxDeltaAngle); -public: - KX_ObstacleSimulationTOI_rays(MT_Scalar levelHeight, bool enableVisualization); -}; - -class KX_ObstacleSimulationTOI_cells: public KX_ObstacleSimulationTOI -{ -protected: - float m_bias; - bool m_adaptive; - int m_sampleRadius; - virtual void sampleRVO(KX_Obstacle* activeObst, KX_NavMeshObject* activeNavMeshObj, - const float maxDeltaAngle); -public: - KX_ObstacleSimulationTOI_cells(MT_Scalar levelHeight, bool enableVisualization); -}; - -#endif diff --git a/source/gameengine/Ketsji/KX_OrientationInterpolator.cpp b/source/gameengine/Ketsji/KX_OrientationInterpolator.cpp deleted file mode 100644 index bcaa1e60e92..00000000000 --- a/source/gameengine/Ketsji/KX_OrientationInterpolator.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_OrientationInterpolator.cpp - * \ingroup ketsji - */ - - -#include "KX_OrientationInterpolator.h" -#include "MT_Matrix3x3.h" -#include "KX_IScalarInterpolator.h" - -void KX_OrientationInterpolator::Execute(float currentTime) const -{ - MT_Vector3 eul(m_ipos[0]->GetValue(currentTime), - m_ipos[1]->GetValue(currentTime), - m_ipos[2]->GetValue(currentTime)); - MT_Scalar ci = cosf(eul[0]); - MT_Scalar cj = cosf(eul[1]); - MT_Scalar ch = cosf(eul[2]); - MT_Scalar si = sinf(eul[0]); - MT_Scalar sj = sinf(eul[1]); - MT_Scalar sh = sinf(eul[2]); - MT_Scalar cc = ci*ch; - MT_Scalar cs = ci*sh; - MT_Scalar sc = si*ch; - MT_Scalar ss = si*sh; - - m_target.setValue(cj*ch, sj*sc-cs, sj*cc+ss, - cj*sh, sj*ss+cc, sj*cs-sc, - -sj, cj*si, cj*ci); -} diff --git a/source/gameengine/Ketsji/KX_OrientationInterpolator.h b/source/gameengine/Ketsji/KX_OrientationInterpolator.h deleted file mode 100644 index 59014b70174..00000000000 --- a/source/gameengine/Ketsji/KX_OrientationInterpolator.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_OrientationInterpolator.h - * \ingroup ketsji - */ - -#ifndef __KX_ORIENTATIONINTERPOLATOR_H__ -#define __KX_ORIENTATIONINTERPOLATOR_H__ - -#include "KX_IInterpolator.h" - -class MT_Matrix3x3; -class KX_IScalarInterpolator; - -class KX_OrientationInterpolator : public KX_IInterpolator { -public: - KX_OrientationInterpolator(MT_Matrix3x3& target, - KX_IScalarInterpolator **ipos) - : m_target(target) - { - m_ipos[0] = ipos[0]; - m_ipos[1] = ipos[1]; - m_ipos[2] = ipos[2]; - } - - virtual void Execute(float currentTime) const; - -private: - MT_Matrix3x3& m_target; - KX_IScalarInterpolator *m_ipos[3]; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_OrientationInterpolator") -#endif -}; - -#endif - diff --git a/source/gameengine/Ketsji/KX_ParentActuator.cpp b/source/gameengine/Ketsji/KX_ParentActuator.cpp deleted file mode 100644 index 0b133400920..00000000000 --- a/source/gameengine/Ketsji/KX_ParentActuator.cpp +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Set or remove an objects parent - * - * - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_ParentActuator.cpp - * \ingroup ketsji - */ - - -#include "KX_ParentActuator.h" -#include "KX_GameObject.h" -#include "KX_PythonInit.h" - -#include "EXP_PyObjectPlus.h" - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -KX_ParentActuator::KX_ParentActuator(SCA_IObject *gameobj, - int mode, - bool addToCompound, - bool ghost, - SCA_IObject *ob) - : SCA_IActuator(gameobj, KX_ACT_PARENT), - m_mode(mode), - m_addToCompound(addToCompound), - m_ghost(ghost), - m_ob(ob) -{ - if (m_ob) - m_ob->RegisterActuator(this); -} - - - -KX_ParentActuator::~KX_ParentActuator() -{ - if (m_ob) - m_ob->UnregisterActuator(this); -} - - - -CValue* KX_ParentActuator::GetReplica() -{ - KX_ParentActuator* replica = new KX_ParentActuator(*this); - // replication just copy the m_base pointer => common random generator - replica->ProcessReplica(); - return replica; -} - -void KX_ParentActuator::ProcessReplica() -{ - if (m_ob) - m_ob->RegisterActuator(this); - SCA_IActuator::ProcessReplica(); -} - - -bool KX_ParentActuator::UnlinkObject(SCA_IObject* clientobj) -{ - if (clientobj == m_ob) - { - // this object is being deleted, we cannot continue to track it. - m_ob = NULL; - return true; - } - return false; -} - -void KX_ParentActuator::Relink(CTR_Map *obj_map) -{ - void **h_obj = (*obj_map)[m_ob]; - if (h_obj) { - if (m_ob) - m_ob->UnregisterActuator(this); - m_ob = (SCA_IObject*)(*h_obj); - m_ob->RegisterActuator(this); - } -} - - - -bool KX_ParentActuator::Update() -{ - bool bNegativeEvent = IsNegativeEvent(); - RemoveAllEvents(); - - if (bNegativeEvent) - return false; // do nothing on negative events - - KX_GameObject *obj = (KX_GameObject*) GetParent(); - KX_Scene *scene = KX_GetActiveScene(); - switch (m_mode) { - case KX_PARENT_SET: - if (m_ob) - obj->SetParent(scene, (KX_GameObject*)m_ob, m_addToCompound, m_ghost); - break; - case KX_PARENT_REMOVE: - obj->RemoveParent(scene); - break; - }; - - return false; -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject KX_ParentActuator::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_ParentActuator", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &SCA_IActuator::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_ParentActuator::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_ParentActuator::Attributes[] = { - KX_PYATTRIBUTE_RW_FUNCTION("object", KX_ParentActuator, pyattr_get_object, pyattr_set_object), - KX_PYATTRIBUTE_INT_RW("mode", KX_PARENT_NODEF+1, KX_PARENT_MAX-1, true, KX_ParentActuator, m_mode), - KX_PYATTRIBUTE_BOOL_RW("compound", KX_ParentActuator, m_addToCompound), - KX_PYATTRIBUTE_BOOL_RW("ghost", KX_ParentActuator, m_ghost), - { NULL } //Sentinel -}; - -PyObject *KX_ParentActuator::pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_ParentActuator* actuator = static_cast(self); - if (!actuator->m_ob) - Py_RETURN_NONE; - else - return actuator->m_ob->GetProxy(); -} - -int KX_ParentActuator::pyattr_set_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_ParentActuator* actuator = static_cast(self); - KX_GameObject *gameobj; - - if (!ConvertPythonToGameObject(actuator->GetLogicManager(), value, &gameobj, true, "actuator.object = value: KX_ParentActuator")) - return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error - - if (actuator->m_ob != NULL) - actuator->m_ob->UnregisterActuator(actuator); - - actuator->m_ob = (SCA_IObject*) gameobj; - - if (actuator->m_ob) - actuator->m_ob->RegisterActuator(actuator); - - return PY_SET_ATTR_SUCCESS; -} - -#endif // WITH_PYTHON - -/* eof */ diff --git a/source/gameengine/Ketsji/KX_ParentActuator.h b/source/gameengine/Ketsji/KX_ParentActuator.h deleted file mode 100644 index 40baac6b2b2..00000000000 --- a/source/gameengine/Ketsji/KX_ParentActuator.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_ParentActuator.h - * \ingroup ketsji - * \brief Set or remove an objects parent - */ - -#ifndef __KX_PARENTACTUATOR_H__ -#define __KX_PARENTACTUATOR_H__ - -#include "SCA_IActuator.h" -#include "SCA_LogicManager.h" - -class KX_ParentActuator : public SCA_IActuator -{ - Py_Header - - /** Mode */ - int m_mode; - - /** option */ - bool m_addToCompound; - bool m_ghost; - /** Object to set as parent */ - SCA_IObject *m_ob; - - - -public: - enum KX_PARENTACT_MODE - { - KX_PARENT_NODEF = 0, - KX_PARENT_SET, - KX_PARENT_REMOVE, - KX_PARENT_MAX - - }; - - KX_ParentActuator(class SCA_IObject* gameobj, - int mode, - bool addToCompound, - bool ghost, - SCA_IObject *ob); - virtual ~KX_ParentActuator(); - virtual bool Update(); - - virtual CValue* GetReplica(); - virtual void ProcessReplica(); - virtual void Relink(CTR_Map *obj_map); - virtual bool UnlinkObject(SCA_IObject* clientobj); - -#ifdef WITH_PYTHON - - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - - /* These are used to get and set m_ob */ - static PyObject *pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - -#endif /* WITH_PYTHON */ - -}; /* end of class KX_ParentActuator : public SCA_PropertyActuator */ - -#endif /* __KX_PARENTACTUATOR_H__ */ diff --git a/source/gameengine/Ketsji/KX_PhysicsEngineEnums.h b/source/gameengine/Ketsji/KX_PhysicsEngineEnums.h deleted file mode 100644 index ca99c2e7526..00000000000 --- a/source/gameengine/Ketsji/KX_PhysicsEngineEnums.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_PhysicsEngineEnums.h - * \ingroup ketsji - */ - -#ifndef __KX_PHYSICSENGINEENUMS_H__ -#define __KX_PHYSICSENGINEENUMS_H__ - -enum e_PhysicsEngine -{ - NoSelection = -1, - UseNone = 0, - UseBullet = 5, -}; - -#endif /* __KX_PHYSICSENGINEENUMS_H__ */ diff --git a/source/gameengine/Ketsji/KX_PolyProxy.cpp b/source/gameengine/Ketsji/KX_PolyProxy.cpp deleted file mode 100644 index 4454543161b..00000000000 --- a/source/gameengine/Ketsji/KX_PolyProxy.cpp +++ /dev/null @@ -1,266 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_PolyProxy.cpp - * \ingroup ketsji - */ - - -#ifdef WITH_PYTHON - -#include "KX_PolyProxy.h" -#include "KX_MeshProxy.h" -#include "RAS_MeshObject.h" -#include "RAS_Polygon.h" -#include "KX_BlenderMaterial.h" - -#include "KX_PyMath.h" - -PyTypeObject KX_PolyProxy::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_PolyProxy", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &CValue::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_PolyProxy::Methods[] = { - KX_PYMETHODTABLE_NOARGS(KX_PolyProxy,getMaterialIndex), - KX_PYMETHODTABLE_NOARGS(KX_PolyProxy,getNumVertex), - KX_PYMETHODTABLE_NOARGS(KX_PolyProxy,isVisible), - KX_PYMETHODTABLE_NOARGS(KX_PolyProxy,isCollider), - KX_PYMETHODTABLE_NOARGS(KX_PolyProxy,getMaterialName), - KX_PYMETHODTABLE_NOARGS(KX_PolyProxy,getTextureName), - KX_PYMETHODTABLE(KX_PolyProxy,getVertexIndex), - KX_PYMETHODTABLE_NOARGS(KX_PolyProxy,getMesh), - KX_PYMETHODTABLE_NOARGS(KX_PolyProxy,getMaterial), - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_PolyProxy::Attributes[] = { - KX_PYATTRIBUTE_RO_FUNCTION("material_name", KX_PolyProxy, pyattr_get_material_name), - KX_PYATTRIBUTE_RO_FUNCTION("texture_name", KX_PolyProxy, pyattr_get_texture_name), - KX_PYATTRIBUTE_RO_FUNCTION("material", KX_PolyProxy, pyattr_get_material), - KX_PYATTRIBUTE_RO_FUNCTION("material_id", KX_PolyProxy, pyattr_get_material_id), - KX_PYATTRIBUTE_RO_FUNCTION("v1", KX_PolyProxy, pyattr_get_v1), - KX_PYATTRIBUTE_RO_FUNCTION("v2", KX_PolyProxy, pyattr_get_v2), - KX_PYATTRIBUTE_RO_FUNCTION("v3", KX_PolyProxy, pyattr_get_v3), - KX_PYATTRIBUTE_RO_FUNCTION("v4", KX_PolyProxy, pyattr_get_v4), - KX_PYATTRIBUTE_RO_FUNCTION("visible", KX_PolyProxy, pyattr_get_visible), - KX_PYATTRIBUTE_RO_FUNCTION("collide", KX_PolyProxy, pyattr_get_collide), - { NULL } //Sentinel -}; - -KX_PolyProxy::KX_PolyProxy(const RAS_MeshObject*mesh, RAS_Polygon* polygon) -: m_polygon(polygon), - m_mesh((RAS_MeshObject*)mesh) -{ -} - -KX_PolyProxy::~KX_PolyProxy() -{ -} - - -// stuff for cvalue related things -CValue* KX_PolyProxy::Calc(VALUE_OPERATOR, CValue *) { return NULL;} -CValue* KX_PolyProxy::CalcFinal(VALUE_DATA_TYPE, VALUE_OPERATOR, CValue *) { return NULL;} -static STR_String sPolyName = "polygone"; -const STR_String & KX_PolyProxy::GetText() {return sPolyName;}; -double KX_PolyProxy::GetNumber() { return -1;} -STR_String& KX_PolyProxy::GetName() { return sPolyName;} -void KX_PolyProxy::SetName(const char *) { }; -CValue* KX_PolyProxy::GetReplica() { return NULL;} - -// stuff for python integration - -PyObject *KX_PolyProxy::pyattr_get_material_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_PolyProxy* self = static_cast(self_v); - return self->PygetMaterialName(); -} - -PyObject *KX_PolyProxy::pyattr_get_texture_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_PolyProxy* self = static_cast(self_v); - return self->PygetTextureName(); -} - -PyObject *KX_PolyProxy::pyattr_get_material(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_PolyProxy* self = static_cast(self_v); - return self->PygetMaterial(); -} - -PyObject *KX_PolyProxy::pyattr_get_material_id(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_PolyProxy* self = static_cast(self_v); - return self->PygetMaterialIndex(); -} - -PyObject *KX_PolyProxy::pyattr_get_v1(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_PolyProxy* self = static_cast(self_v); - - return PyLong_FromLong(self->m_polygon->GetVertexOffsetAbsolute(0)); -} - -PyObject *KX_PolyProxy::pyattr_get_v2(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_PolyProxy* self = static_cast(self_v); - - return PyLong_FromLong(self->m_polygon->GetVertexOffsetAbsolute(1)); -} - -PyObject *KX_PolyProxy::pyattr_get_v3(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_PolyProxy* self = static_cast(self_v); - - return PyLong_FromLong(self->m_polygon->GetVertexOffsetAbsolute(2)); -} - -PyObject *KX_PolyProxy::pyattr_get_v4(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_PolyProxy* self = static_cast(self_v); - - if (3 < self->m_polygon->VertexCount()) - { - return PyLong_FromLong(self->m_polygon->GetVertexOffsetAbsolute(3)); - } - return PyLong_FromLong(0); -} - -PyObject *KX_PolyProxy::pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_PolyProxy* self = static_cast(self_v); - return self->PyisVisible(); -} - -PyObject *KX_PolyProxy::pyattr_get_collide(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_PolyProxy* self = static_cast(self_v); - return self->PyisCollider(); -} - -KX_PYMETHODDEF_DOC_NOARGS(KX_PolyProxy, getMaterialIndex, -"getMaterialIndex() : return the material index of the polygon in the mesh\n") -{ - RAS_MaterialBucket* polyBucket = m_polygon->GetMaterial(); - unsigned int matid; - for (matid=0; matid<(unsigned int)m_mesh->NumMaterials(); matid++) - { - RAS_MeshMaterial* meshMat = m_mesh->GetMeshMaterial(matid); - if (meshMat->m_bucket == polyBucket) - // found it - break; - } - return PyLong_FromLong(matid); -} - -KX_PYMETHODDEF_DOC_NOARGS(KX_PolyProxy, getNumVertex, -"getNumVertex() : returns the number of vertex of the polygon, 3 or 4\n") -{ - return PyLong_FromLong(m_polygon->VertexCount()); -} - -KX_PYMETHODDEF_DOC_NOARGS(KX_PolyProxy, isVisible, -"isVisible() : returns whether the polygon is visible or not\n") -{ - return PyLong_FromLong(m_polygon->IsVisible()); -} - -KX_PYMETHODDEF_DOC_NOARGS(KX_PolyProxy, isCollider, -"isCollider() : returns whether the polygon is receives collision or not\n") -{ - return PyLong_FromLong(m_polygon->IsCollider()); -} - -KX_PYMETHODDEF_DOC_NOARGS(KX_PolyProxy, getMaterialName, -"getMaterialName() : returns the polygon material name, \"NoMaterial\" if no material\n") -{ - return PyUnicode_From_STR_String(m_polygon->GetMaterial()->GetPolyMaterial()->GetMaterialName()); -} - -KX_PYMETHODDEF_DOC_NOARGS(KX_PolyProxy, getTextureName, -"getTexturelName() : returns the polygon texture name, \"NULL\" if no texture\n") -{ - return PyUnicode_From_STR_String(m_polygon->GetMaterial()->GetPolyMaterial()->GetTextureName()); -} - -KX_PYMETHODDEF_DOC(KX_PolyProxy, getVertexIndex, -"getVertexIndex(vertex) : returns the mesh vertex index of a polygon vertex\n" -"vertex: index of the vertex in the polygon: 0->3\n" -"return value can be used to retrieve the vertex details through mesh proxy\n" -"Note: getVertexIndex(3) on a triangle polygon returns 0\n") -{ - int index; - if (!PyArg_ParseTuple(args,"i:getVertexIndex",&index)) - { - return NULL; - } - if (index < 0 || index > 3) - { - PyErr_SetString(PyExc_AttributeError, "poly.getVertexIndex(int): KX_PolyProxy, expected an index between 0-3"); - return NULL; - } - if (index < m_polygon->VertexCount()) - { - return PyLong_FromLong(m_polygon->GetVertexOffsetAbsolute(index)); - } - return PyLong_FromLong(0); -} - -KX_PYMETHODDEF_DOC_NOARGS(KX_PolyProxy, getMesh, -"getMesh() : returns a mesh proxy\n") -{ - KX_MeshProxy* meshproxy = new KX_MeshProxy((RAS_MeshObject*)m_mesh); - return meshproxy->NewProxy(true); -} - -KX_PYMETHODDEF_DOC_NOARGS(KX_PolyProxy, getMaterial, -"getMaterial() : returns a material\n") -{ - RAS_IPolyMaterial *polymat = m_polygon->GetMaterial()->GetPolyMaterial(); - KX_BlenderMaterial* mat = static_cast(polymat); - return mat->GetProxy(); -} - -#endif // WITH_PYTHON diff --git a/source/gameengine/Ketsji/KX_PolyProxy.h b/source/gameengine/Ketsji/KX_PolyProxy.h deleted file mode 100644 index 837e7f8354c..00000000000 --- a/source/gameengine/Ketsji/KX_PolyProxy.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_PolyProxy.h - * \ingroup ketsji - */ - -#ifndef __KX_POLYPROXY_H__ -#define __KX_POLYPROXY_H__ - -#ifdef WITH_PYTHON - -#include "SCA_IObject.h" - -class KX_PolyProxy : public CValue -{ - Py_Header -protected: - class RAS_Polygon* m_polygon; - class RAS_MeshObject* m_mesh; -public: - KX_PolyProxy(const class RAS_MeshObject*mesh, class RAS_Polygon* polygon); - virtual ~KX_PolyProxy(); - - // stuff for cvalue related things - CValue* Calc(VALUE_OPERATOR op, CValue *val); - CValue* CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val); - const STR_String & GetText(); - double GetNumber(); - STR_String& GetName(); - void SetName(const char *name); // Set the name of the value - CValue* GetReplica(); - - -// stuff for python integration - static PyObject *pyattr_get_material_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_texture_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_material(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_material_id(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_v1(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_v2(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_v3(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_v4(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_collide(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - - KX_PYMETHOD_DOC_NOARGS(KX_PolyProxy,getMaterialIndex) - KX_PYMETHOD_DOC_NOARGS(KX_PolyProxy,getNumVertex) - KX_PYMETHOD_DOC_NOARGS(KX_PolyProxy,isVisible) - KX_PYMETHOD_DOC_NOARGS(KX_PolyProxy,isCollider) - KX_PYMETHOD_DOC_NOARGS(KX_PolyProxy,getMaterialName) - KX_PYMETHOD_DOC_NOARGS(KX_PolyProxy,getTextureName) - KX_PYMETHOD_DOC(KX_PolyProxy,getVertexIndex) - KX_PYMETHOD_DOC_NOARGS(KX_PolyProxy,getMesh) - KX_PYMETHOD_DOC_NOARGS(KX_PolyProxy,getMaterial) - -}; - -#endif /* WITH_PYTHON */ - -#endif /* __KX_POLYPROXY_H__ */ diff --git a/source/gameengine/Ketsji/KX_PositionInterpolator.cpp b/source/gameengine/Ketsji/KX_PositionInterpolator.cpp deleted file mode 100644 index 1e217ecf616..00000000000 --- a/source/gameengine/Ketsji/KX_PositionInterpolator.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_PositionInterpolator.cpp - * \ingroup ketsji - */ - - -#include "KX_PositionInterpolator.h" -#include "MT_Point3.h" -#include "KX_IScalarInterpolator.h" - -void KX_PositionInterpolator::Execute(float currentTime) const -{ - m_target.setValue(m_ipos[0]->GetValue(currentTime), - m_ipos[1]->GetValue(currentTime), - m_ipos[2]->GetValue(currentTime)); -} diff --git a/source/gameengine/Ketsji/KX_PositionInterpolator.h b/source/gameengine/Ketsji/KX_PositionInterpolator.h deleted file mode 100644 index b5ab053bb0e..00000000000 --- a/source/gameengine/Ketsji/KX_PositionInterpolator.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_PositionInterpolator.h - * \ingroup ketsji - */ - -#ifndef __KX_POSITIONINTERPOLATOR_H__ -#define __KX_POSITIONINTERPOLATOR_H__ - -#include "KX_IInterpolator.h" - -class MT_Point3; -class KX_IScalarInterpolator; - -class KX_PositionInterpolator : public KX_IInterpolator { -public: - KX_PositionInterpolator(MT_Point3& target, - KX_IScalarInterpolator *ipos[]) : - m_target(target) - { - m_ipos[0] = ipos[0]; - m_ipos[1] = ipos[1]; - m_ipos[2] = ipos[2]; - } - - virtual void Execute(float currentTime) const; - -private: - MT_Point3& m_target; - KX_IScalarInterpolator *m_ipos[3]; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_PositionInterpolator") -#endif -}; - -#endif - diff --git a/source/gameengine/Ketsji/KX_PyConstraintBinding.cpp b/source/gameengine/Ketsji/KX_PyConstraintBinding.cpp deleted file mode 100644 index 81fe3be1fcf..00000000000 --- a/source/gameengine/Ketsji/KX_PyConstraintBinding.cpp +++ /dev/null @@ -1,750 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_PyConstraintBinding.cpp - * \ingroup ketsji - */ - -#include "KX_PyConstraintBinding.h" -#include "PHY_IPhysicsEnvironment.h" -#include "KX_ConstraintWrapper.h" -#include "KX_VehicleWrapper.h" -#include "KX_CharacterWrapper.h" -#include "PHY_IPhysicsController.h" -#include "PHY_IVehicle.h" -#include "PHY_DynamicTypes.h" -#include "MT_Matrix3x3.h" - -#include "KX_GameObject.h" // ConvertPythonToGameObject() -#include "KX_PythonInit.h" - -#include "EXP_PyObjectPlus.h" - -#ifdef WITH_BULLET -# include "LinearMath/btIDebugDraw.h" -#endif - -#ifdef WITH_PYTHON - -// macro copied from KX_PythonInit.cpp -#define KX_MACRO_addTypesToDict(dict, name, name2) PyDict_SetItemString(dict, #name, item=PyLong_FromLong(name2)); Py_DECREF(item) - -// nasty glob variable to connect scripting language -// if there is a better way (without global), please do so! -static PHY_IPhysicsEnvironment* g_CurrentActivePhysicsEnvironment = NULL; - - -PyDoc_STRVAR(PhysicsConstraints_module_documentation, -"This is the Python API for the Physics Constraints" -); - -PyDoc_STRVAR(gPySetGravity__doc__, -"setGravity(float x,float y,float z)\n" -"" -); -PyDoc_STRVAR(gPySetDebugMode__doc__, -"setDebugMode(int mode)\n" -"" -); - -PyDoc_STRVAR(gPySetNumIterations__doc__, -"setNumIterations(int numiter)\n" -"This sets the number of iterations for an iterative constraint solver" -); -PyDoc_STRVAR(gPySetNumTimeSubSteps__doc__, -"setNumTimeSubSteps(int numsubstep)\n" -"This sets the number of substeps for each physics proceed. Tradeoff quality for performance." -); - -PyDoc_STRVAR(gPySetDeactivationTime__doc__, -"setDeactivationTime(float time)\n" -"This sets the time after which a resting rigidbody gets deactived" -); -PyDoc_STRVAR(gPySetDeactivationLinearTreshold__doc__, -"setDeactivationLinearTreshold(float linearTreshold)\n" -"" -); -PyDoc_STRVAR(gPySetDeactivationAngularTreshold__doc__, -"setDeactivationAngularTreshold(float angularTreshold)\n" -"" -); -PyDoc_STRVAR(gPySetContactBreakingTreshold__doc__, -"setContactBreakingTreshold(float breakingTreshold)\n" -"Reasonable default is 0.02 (if units are meters)" -); - -PyDoc_STRVAR(gPySetCcdMode__doc__, -"setCcdMode(int ccdMode)\n" -"Very experimental, not recommended" -); -PyDoc_STRVAR(gPySetSorConstant__doc__, -"setSorConstant(float sor)\n" -"Very experimental, not recommended" -); -PyDoc_STRVAR(gPySetSolverTau__doc__, -"setTau(float tau)\n" -"Very experimental, not recommended" -); -PyDoc_STRVAR(gPySetSolverDamping__doc__, -"setDamping(float damping)\n" -"Very experimental, not recommended" -); -PyDoc_STRVAR(gPySetLinearAirDamping__doc__, -"setLinearAirDamping(float damping)\n" -"Very experimental, not recommended" -); -PyDoc_STRVAR(gPySetUseEpa__doc__, -"setUseEpa(int epa)\n" -"Very experimental, not recommended" -); -PyDoc_STRVAR(gPySetSolverType__doc__, -"setSolverType(int solverType)\n" -"Very experimental, not recommended" -); - -PyDoc_STRVAR(gPyCreateConstraint__doc__, -"createConstraint(ob1,ob2,float restLength,float restitution,float damping)\n" -"" -); -PyDoc_STRVAR(gPyGetVehicleConstraint__doc__, -"getVehicleConstraint(int constraintId)\n" -"" -); -PyDoc_STRVAR(gPyGetCharacter__doc__, -"getCharacter(KX_GameObject obj)\n" -"" -); -PyDoc_STRVAR(gPyRemoveConstraint__doc__, -"removeConstraint(int constraintId)\n" -"" -); -PyDoc_STRVAR(gPyGetAppliedImpulse__doc__, -"getAppliedImpulse(int constraintId)\n" -"" -); - - - - -static PyObject *gPySetGravity(PyObject *self, - PyObject *args, - PyObject *kwds) -{ - float x,y,z; - if (PyArg_ParseTuple(args,"fff",&x,&y,&z)) - { - if (PHY_GetActiveEnvironment()) - PHY_GetActiveEnvironment()->SetGravity(x,y,z); - } - else { - return NULL; - } - - Py_RETURN_NONE; -} - -static PyObject *gPySetDebugMode(PyObject *self, - PyObject *args, - PyObject *kwds) -{ - int mode; - if (PyArg_ParseTuple(args,"i",&mode)) - { - if (PHY_GetActiveEnvironment()) - { - PHY_GetActiveEnvironment()->SetDebugMode(mode); - - } - - } - else { - return NULL; - } - - Py_RETURN_NONE; -} - - - -static PyObject *gPySetNumTimeSubSteps(PyObject *self, - PyObject *args, - PyObject *kwds) -{ - int substep; - if (PyArg_ParseTuple(args,"i",&substep)) - { - if (PHY_GetActiveEnvironment()) - { - PHY_GetActiveEnvironment()->SetNumTimeSubSteps(substep); - } - } - else { - return NULL; - } - Py_RETURN_NONE; -} - - -static PyObject *gPySetNumIterations(PyObject *self, - PyObject *args, - PyObject *kwds) -{ - int iter; - if (PyArg_ParseTuple(args,"i",&iter)) - { - if (PHY_GetActiveEnvironment()) - { - PHY_GetActiveEnvironment()->SetNumIterations(iter); - } - } - else { - return NULL; - } - Py_RETURN_NONE; -} - - -static PyObject *gPySetDeactivationTime(PyObject *self, - PyObject *args, - PyObject *kwds) -{ - float deactive_time; - if (PyArg_ParseTuple(args,"f",&deactive_time)) - { - if (PHY_GetActiveEnvironment()) - { - PHY_GetActiveEnvironment()->SetDeactivationTime(deactive_time); - } - } - else { - return NULL; - } - Py_RETURN_NONE; -} - - -static PyObject *gPySetDeactivationLinearTreshold(PyObject *self, - PyObject *args, - PyObject *kwds) -{ - float linearDeactivationTreshold; - if (PyArg_ParseTuple(args,"f",&linearDeactivationTreshold)) - { - if (PHY_GetActiveEnvironment()) - { - PHY_GetActiveEnvironment()->SetDeactivationLinearTreshold( linearDeactivationTreshold); - } - } - else { - return NULL; - } - Py_RETURN_NONE; -} - - -static PyObject *gPySetDeactivationAngularTreshold(PyObject *self, - PyObject *args, - PyObject *kwds) -{ - float angularDeactivationTreshold; - if (PyArg_ParseTuple(args,"f",&angularDeactivationTreshold)) - { - if (PHY_GetActiveEnvironment()) - { - PHY_GetActiveEnvironment()->SetDeactivationAngularTreshold( angularDeactivationTreshold); - } - } - else { - return NULL; - } - Py_RETURN_NONE; -} - -static PyObject *gPySetContactBreakingTreshold(PyObject *self, - PyObject *args, - PyObject *kwds) -{ - float contactBreakingTreshold; - if (PyArg_ParseTuple(args,"f",&contactBreakingTreshold)) - { - if (PHY_GetActiveEnvironment()) - { - PHY_GetActiveEnvironment()->SetContactBreakingTreshold( contactBreakingTreshold); - } - } - else { - return NULL; - } - Py_RETURN_NONE; -} - - -static PyObject *gPySetCcdMode(PyObject *self, - PyObject *args, - PyObject *kwds) -{ - float ccdMode; - if (PyArg_ParseTuple(args,"f",&ccdMode)) - { - if (PHY_GetActiveEnvironment()) - { - PHY_GetActiveEnvironment()->SetCcdMode( ccdMode); - } - } - else { - return NULL; - } - Py_RETURN_NONE; -} - -static PyObject *gPySetSorConstant(PyObject *self, - PyObject *args, - PyObject *kwds) -{ - float sor; - if (PyArg_ParseTuple(args,"f",&sor)) - { - if (PHY_GetActiveEnvironment()) - { - PHY_GetActiveEnvironment()->SetSolverSorConstant( sor); - } - } - else { - return NULL; - } - Py_RETURN_NONE; -} - -static PyObject *gPySetSolverTau(PyObject *self, - PyObject *args, - PyObject *kwds) -{ - float tau; - if (PyArg_ParseTuple(args,"f",&tau)) - { - if (PHY_GetActiveEnvironment()) - { - PHY_GetActiveEnvironment()->SetSolverTau( tau); - } - } - else { - return NULL; - } - Py_RETURN_NONE; -} - - -static PyObject *gPySetSolverDamping(PyObject *self, - PyObject *args, - PyObject *kwds) -{ - float damping; - if (PyArg_ParseTuple(args,"f",&damping)) - { - if (PHY_GetActiveEnvironment()) - { - PHY_GetActiveEnvironment()->SetSolverDamping( damping); - } - } - else { - return NULL; - } - Py_RETURN_NONE; -} - -static PyObject *gPySetLinearAirDamping(PyObject *self, - PyObject *args, - PyObject *kwds) -{ - float damping; - if (PyArg_ParseTuple(args,"f",&damping)) - { - if (PHY_GetActiveEnvironment()) - { - PHY_GetActiveEnvironment()->SetLinearAirDamping( damping); - } - } - else { - return NULL; - } - Py_RETURN_NONE; -} - - -static PyObject *gPySetUseEpa(PyObject *self, - PyObject *args, - PyObject *kwds) -{ - int epa; - if (PyArg_ParseTuple(args,"i",&epa)) - { - if (PHY_GetActiveEnvironment()) - { - PHY_GetActiveEnvironment()->SetUseEpa(epa); - } - } - else { - return NULL; - } - Py_RETURN_NONE; -} -static PyObject *gPySetSolverType(PyObject *self, - PyObject *args, - PyObject *kwds) -{ - int solverType; - if (PyArg_ParseTuple(args,"i",&solverType)) - { - if (PHY_GetActiveEnvironment()) - { - PHY_GetActiveEnvironment()->SetSolverType(solverType); - } - } - else { - return NULL; - } - Py_RETURN_NONE; -} - - - -static PyObject *gPyGetVehicleConstraint(PyObject *self, - PyObject *args, - PyObject *kwds) -{ -#if defined(_WIN64) - __int64 constraintid; - if (PyArg_ParseTuple(args,"L",&constraintid)) -#else - long constraintid; - if (PyArg_ParseTuple(args,"l",&constraintid)) -#endif - { - if (PHY_GetActiveEnvironment()) - { - - PHY_IVehicle* vehicle = PHY_GetActiveEnvironment()->GetVehicleConstraint(constraintid); - if (vehicle) - { - KX_VehicleWrapper* pyWrapper = new KX_VehicleWrapper(vehicle,PHY_GetActiveEnvironment()); - return pyWrapper->NewProxy(true); - } - - } - } - else { - return NULL; - } - - Py_RETURN_NONE; -} - -static PyObject* gPyGetCharacter(PyObject* self, - PyObject* args, - PyObject* kwds) -{ - PyObject* pyob; - KX_GameObject *ob; - - if (!PyArg_ParseTuple(args,"O", &pyob)) - return NULL; - - if (!ConvertPythonToGameObject(KX_GetActiveScene()->GetLogicManager(), pyob, &ob, false, "bge.constraints.getCharacter(value)")) - return NULL; - - if (PHY_GetActiveEnvironment()) - { - - PHY_ICharacter* character= PHY_GetActiveEnvironment()->GetCharacterController(ob); - if (character) - { - KX_CharacterWrapper* pyWrapper = new KX_CharacterWrapper(character); - return pyWrapper->NewProxy(true); - } - - } - - Py_RETURN_NONE; -} - -static PyObject *gPyCreateConstraint(PyObject *self, - PyObject *args, - PyObject *kwds) -{ - /* FIXME - physicsid is a long being cast to a pointer, should at least use PyCapsule */ - unsigned long long physicsid = 0, physicsid2 = 0; - int constrainttype = 0; - int flag = 0; - float pivotX = 0.0f, pivotY = 0.0f, pivotZ = 0.0f, axisX = 0.0f, axisY = 0.0f, axisZ = 0.0f; - - static const char *kwlist[] = {"physicsid_1", "physicsid_2", "constraint_type", "pivot_x", "pivot_y", "pivot_z", - "axis_x", "axis_y", "axis_z", "flag", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "KKi|ffffffi:createConstraint", (char **)kwlist, - &physicsid, &physicsid2, &constrainttype, - &pivotX, &pivotY, &pivotZ, &axisX, &axisY, &axisZ, &flag)) - { - return NULL; - } - - if (PHY_GetActiveEnvironment()) { - PHY_IPhysicsController *physctrl = (PHY_IPhysicsController*)physicsid; - PHY_IPhysicsController *physctrl2 = (PHY_IPhysicsController*)physicsid2; - if (physctrl) { //TODO:check for existence of this pointer! - //convert from euler angle into axis - const float deg2rad = 0.017453292f; - - //we need to pass a full constraint frame, not just axis - //localConstraintFrameBasis - MT_Matrix3x3 localCFrame(MT_Vector3(deg2rad*axisX, deg2rad*axisY, deg2rad*axisZ)); - MT_Vector3 axis0 = localCFrame.getColumn(0); - MT_Vector3 axis1 = localCFrame.getColumn(1); - MT_Vector3 axis2 = localCFrame.getColumn(2); - - int constraintid = PHY_GetActiveEnvironment()->CreateConstraint( - physctrl, physctrl2, (enum PHY_ConstraintType)constrainttype, pivotX, pivotY, pivotZ, - (float)axis0.x(), (float)axis0.y(), (float)axis0.z(), - (float)axis1.x(), (float)axis1.y(), (float)axis1.z(), - (float)axis2.x(), (float)axis2.y(), (float)axis2.z(), flag); - - KX_ConstraintWrapper *wrap = new KX_ConstraintWrapper( - (enum PHY_ConstraintType)constrainttype, constraintid, PHY_GetActiveEnvironment()); - - return wrap->NewProxy(true); - } - } - Py_RETURN_NONE; -} - - - - -static PyObject *gPyGetAppliedImpulse(PyObject *self, - PyObject *args, - PyObject *kwds) -{ - float appliedImpulse = 0.f; - -#if defined(_WIN64) - __int64 constraintid; - if (PyArg_ParseTuple(args,"L",&constraintid)) -#else - long constraintid; - if (PyArg_ParseTuple(args,"l",&constraintid)) -#endif - { - if (PHY_GetActiveEnvironment()) - { - appliedImpulse = PHY_GetActiveEnvironment()->GetAppliedImpulse(constraintid); - } - } - else { - return NULL; - } - - return PyFloat_FromDouble(appliedImpulse); -} - - -static PyObject *gPyRemoveConstraint(PyObject *self, - PyObject *args, - PyObject *kwds) -{ -#if defined(_WIN64) - __int64 constraintid; - if (PyArg_ParseTuple(args,"L",&constraintid)) -#else - long constraintid; - if (PyArg_ParseTuple(args,"l",&constraintid)) -#endif - { - if (PHY_GetActiveEnvironment()) - { - PHY_GetActiveEnvironment()->RemoveConstraintById(constraintid); - } - } - else { - return NULL; - } - - Py_RETURN_NONE; -} - -static PyObject *gPyExportBulletFile(PyObject *, PyObject *args) -{ - char* filename; - if (!PyArg_ParseTuple(args,"s:exportBulletFile",&filename)) - return NULL; - - if (PHY_GetActiveEnvironment()) - { - PHY_GetActiveEnvironment()->ExportFile(filename); - } - Py_RETURN_NONE; -} - -static struct PyMethodDef physicsconstraints_methods[] = { - {"setGravity",(PyCFunction) gPySetGravity, - METH_VARARGS, (const char*)gPySetGravity__doc__}, - {"setDebugMode",(PyCFunction) gPySetDebugMode, - METH_VARARGS, (const char *)gPySetDebugMode__doc__}, - - /// settings that influence quality of the rigidbody dynamics - {"setNumIterations",(PyCFunction) gPySetNumIterations, - METH_VARARGS, (const char *)gPySetNumIterations__doc__}, - - {"setNumTimeSubSteps",(PyCFunction) gPySetNumTimeSubSteps, - METH_VARARGS, (const char *)gPySetNumTimeSubSteps__doc__}, - - {"setDeactivationTime",(PyCFunction) gPySetDeactivationTime, - METH_VARARGS, (const char *)gPySetDeactivationTime__doc__}, - - {"setDeactivationLinearTreshold",(PyCFunction) gPySetDeactivationLinearTreshold, - METH_VARARGS, (const char *)gPySetDeactivationLinearTreshold__doc__}, - {"setDeactivationAngularTreshold",(PyCFunction) gPySetDeactivationAngularTreshold, - METH_VARARGS, (const char *)gPySetDeactivationAngularTreshold__doc__}, - - {"setContactBreakingTreshold",(PyCFunction) gPySetContactBreakingTreshold, - METH_VARARGS, (const char *)gPySetContactBreakingTreshold__doc__}, - {"setCcdMode",(PyCFunction) gPySetCcdMode, - METH_VARARGS, (const char *)gPySetCcdMode__doc__}, - {"setSorConstant",(PyCFunction) gPySetSorConstant, - METH_VARARGS, (const char *)gPySetSorConstant__doc__}, - {"setSolverTau",(PyCFunction) gPySetSolverTau, - METH_VARARGS, (const char *)gPySetSolverTau__doc__}, - {"setSolverDamping",(PyCFunction) gPySetSolverDamping, - METH_VARARGS, (const char *)gPySetSolverDamping__doc__}, - - {"setLinearAirDamping",(PyCFunction) gPySetLinearAirDamping, - METH_VARARGS, (const char *)gPySetLinearAirDamping__doc__}, - - {"setUseEpa",(PyCFunction) gPySetUseEpa, - METH_VARARGS, (const char *)gPySetUseEpa__doc__}, - {"setSolverType",(PyCFunction) gPySetSolverType, - METH_VARARGS, (const char *)gPySetSolverType__doc__}, - - - {"createConstraint",(PyCFunction) gPyCreateConstraint, - METH_VARARGS|METH_KEYWORDS, (const char *)gPyCreateConstraint__doc__}, - {"getVehicleConstraint",(PyCFunction) gPyGetVehicleConstraint, - METH_VARARGS, (const char *)gPyGetVehicleConstraint__doc__}, - - {"getCharacter",(PyCFunction) gPyGetCharacter, - METH_VARARGS, (const char *)gPyGetCharacter__doc__}, - - {"removeConstraint",(PyCFunction) gPyRemoveConstraint, - METH_VARARGS, (const char *)gPyRemoveConstraint__doc__}, - {"getAppliedImpulse",(PyCFunction) gPyGetAppliedImpulse, - METH_VARARGS, (const char *)gPyGetAppliedImpulse__doc__}, - - {"exportBulletFile",(PyCFunction)gPyExportBulletFile, - METH_VARARGS, "export a .bullet file"}, - - //sentinel - { NULL, (PyCFunction) NULL, 0, NULL } -}; - -static struct PyModuleDef PhysicsConstraints_module_def = { - PyModuleDef_HEAD_INIT, - "PhysicsConstraints", /* m_name */ - PhysicsConstraints_module_documentation, /* m_doc */ - 0, /* m_size */ - physicsconstraints_methods, /* m_methods */ - 0, /* m_reload */ - 0, /* m_traverse */ - 0, /* m_clear */ - 0, /* m_free */ -}; - -PyMODINIT_FUNC initConstraintPythonBinding() -{ - - PyObject *ErrorObject; - PyObject *m; - PyObject *d; - PyObject *item; - - m = PyModule_Create(&PhysicsConstraints_module_def); - PyDict_SetItemString(PySys_GetObject("modules"), PhysicsConstraints_module_def.m_name, m); - - // Add some symbolic constants to the module - d = PyModule_GetDict(m); - ErrorObject = PyUnicode_FromString("PhysicsConstraints.error"); - PyDict_SetItemString(d, "error", ErrorObject); - Py_DECREF(ErrorObject); - -#ifdef WITH_BULLET - //Debug Modes constants to be used with setDebugMode() python function - KX_MACRO_addTypesToDict(d, DBG_NODEBUG, btIDebugDraw::DBG_NoDebug); - KX_MACRO_addTypesToDict(d, DBG_DRAWWIREFRAME, btIDebugDraw::DBG_DrawWireframe); - KX_MACRO_addTypesToDict(d, DBG_DRAWAABB, btIDebugDraw::DBG_DrawAabb); - KX_MACRO_addTypesToDict(d, DBG_DRAWFREATURESTEXT, btIDebugDraw::DBG_DrawFeaturesText); - KX_MACRO_addTypesToDict(d, DBG_DRAWCONTACTPOINTS, btIDebugDraw::DBG_DrawContactPoints); - KX_MACRO_addTypesToDict(d, DBG_NOHELPTEXT, btIDebugDraw::DBG_NoHelpText); - KX_MACRO_addTypesToDict(d, DBG_DRAWTEXT, btIDebugDraw::DBG_DrawText); - KX_MACRO_addTypesToDict(d, DBG_PROFILETIMINGS, btIDebugDraw::DBG_ProfileTimings); - KX_MACRO_addTypesToDict(d, DBG_ENABLESATCOMPARISION, btIDebugDraw::DBG_EnableSatComparison); - KX_MACRO_addTypesToDict(d, DBG_DISABLEBULLETLCP, btIDebugDraw::DBG_DisableBulletLCP); - KX_MACRO_addTypesToDict(d, DBG_ENABLECCD, btIDebugDraw::DBG_EnableCCD); - KX_MACRO_addTypesToDict(d, DBG_DRAWCONSTRAINTS, btIDebugDraw::DBG_DrawConstraints); - KX_MACRO_addTypesToDict(d, DBG_DRAWCONSTRAINTLIMITS, btIDebugDraw::DBG_DrawConstraintLimits); - KX_MACRO_addTypesToDict(d, DBG_FASTWIREFRAME, btIDebugDraw::DBG_FastWireframe); -#endif // WITH_BULLET - - //Constraint types to be used with createConstraint() python function - KX_MACRO_addTypesToDict(d, POINTTOPOINT_CONSTRAINT, PHY_POINT2POINT_CONSTRAINT); - KX_MACRO_addTypesToDict(d, LINEHINGE_CONSTRAINT, PHY_LINEHINGE_CONSTRAINT); - KX_MACRO_addTypesToDict(d, ANGULAR_CONSTRAINT, PHY_ANGULAR_CONSTRAINT); - KX_MACRO_addTypesToDict(d, CONETWIST_CONSTRAINT, PHY_CONE_TWIST_CONSTRAINT); - KX_MACRO_addTypesToDict(d, VEHICLE_CONSTRAINT, PHY_VEHICLE_CONSTRAINT); - KX_MACRO_addTypesToDict(d, GENERIC_6DOF_CONSTRAINT, PHY_GENERIC_6DOF_CONSTRAINT); - - // Check for errors - if (PyErr_Occurred()) { - Py_FatalError("can't initialize module PhysicsConstraints"); - } - - return m; -} - -#if 0 -static void KX_RemovePythonConstraintBinding() -{ -} -#endif - -void PHY_SetActiveEnvironment(class PHY_IPhysicsEnvironment* env) -{ - g_CurrentActivePhysicsEnvironment = env; -} - -PHY_IPhysicsEnvironment* PHY_GetActiveEnvironment() -{ - return g_CurrentActivePhysicsEnvironment; -} - -#endif // WITH_PYTHON diff --git a/source/gameengine/Ketsji/KX_PyConstraintBinding.h b/source/gameengine/Ketsji/KX_PyConstraintBinding.h deleted file mode 100644 index 2bf9f7e197d..00000000000 --- a/source/gameengine/Ketsji/KX_PyConstraintBinding.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_PyConstraintBinding.h - * \ingroup ketsji - */ - -#ifndef __KX_PYCONSTRAINTBINDING_H__ -#define __KX_PYCONSTRAINTBINDING_H__ - -#ifdef WITH_PYTHON - -#include - -PyMODINIT_FUNC initConstraintPythonBinding(); - -void PHY_SetActiveEnvironment(class PHY_IPhysicsEnvironment* env); -PHY_IPhysicsEnvironment* PHY_GetActiveEnvironment(); -#endif /* WITH_PYTHON */ - -#endif /* __KX_PYCONSTRAINTBINDING_H__ */ diff --git a/source/gameengine/Ketsji/KX_PyMath.cpp b/source/gameengine/Ketsji/KX_PyMath.cpp deleted file mode 100644 index ee05fd442ab..00000000000 --- a/source/gameengine/Ketsji/KX_PyMath.cpp +++ /dev/null @@ -1,215 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - * Initialize Python thingies. - */ - -/** \file gameengine/Ketsji/KX_PyMath.cpp - * \ingroup ketsji - */ - - -#ifdef _MSC_VER -# pragma warning (disable:4786) -#endif - -#ifdef WITH_PYTHON - -#include "MT_Vector3.h" -#include "MT_Vector4.h" -#include "MT_Matrix4x4.h" -#include "MT_Point2.h" - -#include "EXP_ListValue.h" - -#include "EXP_Python.h" -#include "KX_PyMath.h" - -bool PyOrientationTo(PyObject *pyval, MT_Matrix3x3 &rot, const char *error_prefix) -{ - int size= PySequence_Size(pyval); - - if (size == 4) - { - MT_Quaternion qrot; - if (PyQuatTo(pyval, qrot)) - { - rot.setRotation(qrot); - return true; - } - } - else if (size == 3) { - /* 3x3 matrix or euler */ - MT_Vector3 erot; - if (PyVecTo(pyval, erot)) - { - rot.setEuler(erot); - return true; - } - PyErr_Clear(); - - if (PyMatTo(pyval, rot)) - { - return true; - } - } - - PyErr_Format(PyExc_TypeError, "%s, could not set the orientation from a 3x3 matrix, quaternion or euler sequence", error_prefix); - return false; -} - -bool PyQuatTo(PyObject *pyval, MT_Quaternion &qrot) -{ - if (!PyVecTo(pyval, qrot)) - return false; - - /* annoying!, Blender/Mathutils have the W axis first! */ - MT_Scalar w = qrot[0]; /* from python, this is actually the W */ - qrot[0] = qrot[1]; - qrot[1] = qrot[2]; - qrot[2] = qrot[3]; - qrot[3] = w; - - return true; -} - -PyObject *PyObjectFrom(const MT_Matrix4x4 &mat) -{ -#ifdef USE_MATHUTILS - float fmat[16]; - mat.getValue(fmat); - return Matrix_CreatePyObject(fmat, 4, 4, NULL); -#else - PyObject *collist = PyList_New(4); - PyObject *col; - int i; - - for (i=0; i < 4; i++) { - col = PyList_New(4); - PyList_SET_ITEM(col, 0, PyFloat_FromDouble(mat[0][i])); - PyList_SET_ITEM(col, 1, PyFloat_FromDouble(mat[1][i])); - PyList_SET_ITEM(col, 2, PyFloat_FromDouble(mat[2][i])); - PyList_SET_ITEM(col, 3, PyFloat_FromDouble(mat[3][i])); - PyList_SET_ITEM(collist, i, col); - } - - return collist; -#endif -} - -PyObject *PyObjectFrom(const MT_Matrix3x3 &mat) -{ -#ifdef USE_MATHUTILS - float fmat[9]; - mat.getValue3x3(fmat); - return Matrix_CreatePyObject(fmat, 3, 3, NULL); -#else - PyObject *collist = PyList_New(3); - PyObject *col; - int i; - - for (i=0; i < 3; i++) { - col = PyList_New(3); - PyList_SET_ITEM(col, 0, PyFloat_FromDouble(mat[0][i])); - PyList_SET_ITEM(col, 1, PyFloat_FromDouble(mat[1][i])); - PyList_SET_ITEM(col, 2, PyFloat_FromDouble(mat[2][i])); - PyList_SET_ITEM(collist, i, col); - } - - return collist; -#endif -} - -#ifdef USE_MATHUTILS -PyObject *PyObjectFrom(const MT_Quaternion &qrot) -{ - /* NOTE, were re-ordering here for Mathutils compat */ - float fvec[4]; - qrot.getValue(fvec); - return Quaternion_CreatePyObject(fvec, NULL); -} -#endif - -PyObject *PyObjectFrom(const MT_Tuple4 &vec) -{ -#ifdef USE_MATHUTILS - float fvec[4]; - vec.getValue(fvec); - return Vector_CreatePyObject(fvec, 4, NULL); -#else - PyObject *list = PyList_New(4); - PyList_SET_ITEM(list, 0, PyFloat_FromDouble(vec[0])); - PyList_SET_ITEM(list, 1, PyFloat_FromDouble(vec[1])); - PyList_SET_ITEM(list, 2, PyFloat_FromDouble(vec[2])); - PyList_SET_ITEM(list, 3, PyFloat_FromDouble(vec[3])); - return list; -#endif -} - -PyObject *PyObjectFrom(const MT_Tuple3 &vec) -{ -#ifdef USE_MATHUTILS - float fvec[3]; - vec.getValue(fvec); - return Vector_CreatePyObject(fvec, 3, NULL); -#else - PyObject *list = PyList_New(3); - PyList_SET_ITEM(list, 0, PyFloat_FromDouble(vec[0])); - PyList_SET_ITEM(list, 1, PyFloat_FromDouble(vec[1])); - PyList_SET_ITEM(list, 2, PyFloat_FromDouble(vec[2])); - return list; -#endif -} - -PyObject *PyObjectFrom(const MT_Tuple2 &vec) -{ -#ifdef USE_MATHUTILS - float fvec[2]; - vec.getValue(fvec); - return Vector_CreatePyObject(fvec, 2, NULL); -#else - PyObject *list = PyList_New(2); - PyList_SET_ITEM(list, 0, PyFloat_FromDouble(vec[0])); - PyList_SET_ITEM(list, 1, PyFloat_FromDouble(vec[1])); - return list; -#endif -} - -PyObject *PyColorFromVector(const MT_Vector3 &vec) -{ -#ifdef USE_MATHUTILS - float fvec[3]; - vec.getValue(fvec); - return Color_CreatePyObject(fvec, NULL); -#else - PyObject *list = PyList_New(3); - PyList_SET_ITEM(list, 0, PyFloat_FromDouble(vec[0])); - PyList_SET_ITEM(list, 1, PyFloat_FromDouble(vec[1])); - PyList_SET_ITEM(list, 2, PyFloat_FromDouble(vec[2])); - return list; -#endif -} - -#endif // WITH_PYTHON diff --git a/source/gameengine/Ketsji/KX_PyMath.h b/source/gameengine/Ketsji/KX_PyMath.h deleted file mode 100644 index 917fd0fcda6..00000000000 --- a/source/gameengine/Ketsji/KX_PyMath.h +++ /dev/null @@ -1,281 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_PyMath.h - * \ingroup ketsji - * \brief Initialize Python thingies. - */ - -#ifndef __KX_PYMATH_H__ -#define __KX_PYMATH_H__ - -#include "MT_Point2.h" -#include "MT_Point3.h" -#include "MT_Vector2.h" -#include "MT_Vector3.h" -#include "MT_Vector4.h" -#include "MT_Matrix3x3.h" -#include "MT_Matrix4x4.h" - -#include "EXP_Python.h" -#include "EXP_PyObjectPlus.h" - -#ifdef WITH_PYTHON -#ifdef USE_MATHUTILS -extern "C" { -#include "../../blender/python/mathutils/mathutils.h" /* so we can have mathutils callbacks */ -} -#endif - -inline unsigned int Size(const MT_Matrix4x4&) { return 4; } -inline unsigned int Size(const MT_Matrix3x3&) { return 3; } -inline unsigned int Size(const MT_Tuple2&) { return 2; } -inline unsigned int Size(const MT_Tuple3&) { return 3; } -inline unsigned int Size(const MT_Tuple4&) { return 4; } - -/** - * Converts the given python matrix (column-major) to an MT class (row-major). - */ -template -bool PyMatTo(PyObject *pymat, T& mat) -{ - bool noerror = true; - mat.setIdentity(); - - -#ifdef USE_MATHUTILS - - if (MatrixObject_Check(pymat)) - { - MatrixObject *pymatrix = (MatrixObject *)pymat; - - if (BaseMath_ReadCallback(pymatrix) == -1) - return false; - - if (pymatrix->num_col != Size(mat) || pymatrix->num_row != Size(mat)) - return false; - - for (unsigned int row = 0; row < Size(mat); row++) - { - for (unsigned int col = 0; col < Size(mat); col++) - { - mat[row][col] = *(pymatrix->matrix + col * pymatrix->num_row + row); - } - } - } - else - -#endif /* USE_MATHUTILS */ - - - if (PySequence_Check(pymat)) - { - unsigned int rows = PySequence_Size(pymat); - if (rows != Size(mat)) - return false; - - for (unsigned int row = 0; noerror && row < rows; row++) - { - PyObject *pyrow = PySequence_GetItem(pymat, row); /* new ref */ - if (!PyErr_Occurred() && PySequence_Check(pyrow)) - { - unsigned int cols = PySequence_Size(pyrow); - if (cols != Size(mat)) { - noerror = false; - } - else { - for (unsigned int col = 0; col < cols; col++) { - PyObject *item = PySequence_GetItem(pyrow, col); /* new ref */ - mat[row][col] = PyFloat_AsDouble(item); - Py_DECREF(item); - } - } - } - else { - noerror = false; - } - Py_DECREF(pyrow); - } - } else - noerror = false; - - if (noerror==false) - PyErr_SetString(PyExc_TypeError, "could not be converted to a matrix (sequence of sequences)"); - - return noerror; -} - -/** - * Converts a python sequence to a MT class. - */ -template -bool PyVecTo(PyObject *pyval, T& vec) -{ -#ifdef USE_MATHUTILS - /* no need for BaseMath_ReadCallback() here, reading the sequences will do this */ - - if (VectorObject_Check(pyval)) { - VectorObject *pyvec= (VectorObject *)pyval; - if (BaseMath_ReadCallback(pyvec) == -1) { - return false; /* exception raised */ - } - if (pyvec->size != Size(vec)) { - PyErr_Format(PyExc_AttributeError, "error setting vector, %d args, should be %d", pyvec->size, Size(vec)); - return false; - } - vec.setValue((float *) pyvec->vec); - return true; - } - else if (QuaternionObject_Check(pyval)) { - QuaternionObject *pyquat= (QuaternionObject *)pyval; - if (BaseMath_ReadCallback(pyquat) == -1) { - return false; /* exception raised */ - } - if (4 != Size(vec)) { - PyErr_Format(PyExc_AttributeError, "error setting vector, %d args, should be %d", 4, Size(vec)); - return false; - } - /* xyzw -> wxyz reordering is done by PyQuatTo */ - vec.setValue((float *) pyquat->quat); - return true; - } - else if (EulerObject_Check(pyval)) { - EulerObject *pyeul= (EulerObject *)pyval; - if (BaseMath_ReadCallback(pyeul) == -1) { - return false; /* exception raised */ - } - if (3 != Size(vec)) { - PyErr_Format(PyExc_AttributeError, "error setting vector, %d args, should be %d", 3, Size(vec)); - return false; - } - vec.setValue((float *) pyeul->eul); - return true; - } - else -#endif - if (PyTuple_Check(pyval)) { - unsigned int numitems = PyTuple_GET_SIZE(pyval); - if (numitems != Size(vec)) { - PyErr_Format(PyExc_AttributeError, "error setting vector, %d args, should be %d", numitems, Size(vec)); - return false; - } - - for (unsigned int x = 0; x < numitems; x++) - vec[x] = PyFloat_AsDouble(PyTuple_GET_ITEM(pyval, x)); /* borrow ref */ - - if (PyErr_Occurred()) { - PyErr_SetString(PyExc_AttributeError, "one or more of the items in the sequence was not a float"); - return false; - } - - return true; - } - else if (PyObject_TypeCheck(pyval, (PyTypeObject *)&PyObjectPlus::Type)) { - /* note, include this check because PySequence_Check does too much introspection - * on the PyObject (like getting its __class__, on a BGE type this means searching up - * the parent list each time only to discover its not a sequence. - * GameObjects are often used as an alternative to vectors so this is a common case - * better to do a quick check for it, likely the error below will be ignored. - * - * This is not 'correct' since we have proxy type CListValues's which could - * contain floats/ints but there no cases of CValueLists being this way - */ - PyErr_Format(PyExc_AttributeError, "expected a sequence type"); - return false; - } - else if (PySequence_Check(pyval)) { - unsigned int numitems = PySequence_Size(pyval); - if (numitems != Size(vec)) { - PyErr_Format(PyExc_AttributeError, "error setting vector, %d args, should be %d", numitems, Size(vec)); - return false; - } - - for (unsigned int x = 0; x < numitems; x++) { - PyObject *item = PySequence_GetItem(pyval, x); /* new ref */ - vec[x] = PyFloat_AsDouble(item); - Py_DECREF(item); - } - - if (PyErr_Occurred()) { - PyErr_SetString(PyExc_AttributeError, "one or more of the items in the sequence was not a float"); - return false; - } - - return true; - } - else { - PyErr_Format(PyExc_AttributeError, "not a sequence type, expected a sequence of numbers size %d", Size(vec)); - } - - return false; -} - - -bool PyQuatTo(PyObject *pyval, MT_Quaternion &qrot); - -bool PyOrientationTo(PyObject *pyval, MT_Matrix3x3 &mat, const char *error_prefix); - -/** - * Converts an MT_Matrix4x4 to a python object. - */ -PyObject *PyObjectFrom(const MT_Matrix4x4 &mat); - -/** - * Converts an MT_Matrix3x3 to a python object. - */ -PyObject *PyObjectFrom(const MT_Matrix3x3 &mat); - -/** - * Converts an MT_Tuple2 to a python object. - */ -PyObject *PyObjectFrom(const MT_Tuple2 &vec); - -/** - * Converts an MT_Tuple3 to a python object - */ -PyObject *PyObjectFrom(const MT_Tuple3 &vec); - -#ifdef USE_MATHUTILS -/** - * Converts an MT_Quaternion to a python object. - */ -PyObject *PyObjectFrom(const MT_Quaternion &qrot); -#endif - -/** - * Converts an MT_Tuple4 to a python object. - */ -PyObject *PyObjectFrom(const MT_Tuple4 &pos); - -#endif - -/** - * Converts an MT_Vector3 to a python color object. - */ -PyObject *PyColorFromVector(const MT_Vector3 &vec); - -#endif /* WITH_PYTHON */ diff --git a/source/gameengine/Ketsji/KX_PythonInit.cpp b/source/gameengine/Ketsji/KX_PythonInit.cpp deleted file mode 100644 index 5540aad7a3f..00000000000 --- a/source/gameengine/Ketsji/KX_PythonInit.cpp +++ /dev/null @@ -1,2953 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - * Initialize Python thingies. - */ - -/** \file gameengine/Ketsji/KX_PythonInit.cpp - * \ingroup ketsji - */ - -#include "GPU_glew.h" - -#ifdef _MSC_VER -# pragma warning (disable:4786) -#endif - -#ifdef WITH_PYTHON -# ifdef _XOPEN_SOURCE -# undef _XOPEN_SOURCE -# endif -# include - -extern "C" { - # include "BLI_utildefines.h" - # include "python_utildefines.h" - # include "bpy_internal_import.h" /* from the blender python api, but we want to import text too! */ - # include "py_capi_utils.h" - # include "mathutils.h" // 'mathutils' module copied here so the blenderlayer can use. - # include "bgl.h" - # include "blf_py_api.h" - - # include "marshal.h" /* python header for loading/saving dicts */ -} -#include "../../../../intern/audaspace/intern/AUD_PyInit.h" - -#endif /* WITH_PYTHON */ - -#include "KX_PythonInit.h" - -// directory header for py function getBlendFileList -#ifndef WIN32 -# include -# include -#else -# include -# include "BLI_winstuff.h" -#endif - -//python physics binding -#include "KX_PyConstraintBinding.h" - -#include "KX_KetsjiEngine.h" -#include "KX_RadarSensor.h" -#include "KX_RaySensor.h" -#include "KX_ArmatureSensor.h" -#include "KX_SceneActuator.h" -#include "KX_GameActuator.h" -#include "KX_ParentActuator.h" -#include "KX_SCA_DynamicActuator.h" -#include "KX_SteeringActuator.h" -#include "KX_NavMeshObject.h" -#include "KX_MouseActuator.h" -#include "KX_TrackToActuator.h" - -#include "SCA_IInputDevice.h" -#include "SCA_PropertySensor.h" -#include "SCA_RandomActuator.h" -#include "SCA_KeyboardSensor.h" /* IsPrintable, ToCharacter */ -#include "SCA_JoystickManager.h" /* JOYINDEX_MAX */ -#include "SCA_PythonJoystick.h" -#include "SCA_PythonKeyboard.h" -#include "SCA_PythonMouse.h" -#include "KX_ConstraintActuator.h" -#include "KX_SoundActuator.h" -#include "KX_StateActuator.h" -#include "BL_ActionActuator.h" -#include "BL_ArmatureObject.h" -#include "RAS_IRasterizer.h" -#include "RAS_ICanvas.h" -#include "RAS_IOffScreen.h" -#include "RAS_BucketManager.h" -#include "RAS_2DFilterManager.h" -#include "MT_Vector3.h" -#include "MT_Point3.h" -#include "EXP_ListValue.h" -#include "EXP_InputParser.h" -#include "KX_Scene.h" - -#include "NG_NetworkScene.h" //Needed for sendMessage() - -#include "BL_Shader.h" -#include "BL_Action.h" - -#include "KX_PyMath.h" - -#include "EXP_PyObjectPlus.h" - -#include "KX_PythonInitTypes.h" - -/* we only need this to get a list of libraries from the main struct */ -#include "DNA_ID.h" -#include "DNA_scene_types.h" - -#include "PHY_IPhysicsEnvironment.h" - -extern "C" { -#include "BKE_main.h" -#include "BKE_global.h" -#include "BKE_library.h" -#include "BKE_appdir.h" -#include "BKE_blender_version.h" -#include "BLI_blenlib.h" -#include "GPU_material.h" -#include "MEM_guardedalloc.h" -} - -/* for converting new scenes */ -#include "KX_BlenderSceneConverter.h" -#include "KX_LibLoadStatus.h" -#include "KX_MeshProxy.h" /* for creating a new library of mesh objects */ -extern "C" { - #include "BKE_idcode.h" -} - -// 'local' copy of canvas ptr, for window height/width python scripts - -#ifdef WITH_PYTHON - -static RAS_ICanvas* gp_Canvas = NULL; -static char gp_GamePythonPath[FILE_MAX] = ""; -static char gp_GamePythonPathOrig[FILE_MAX] = ""; // not super happy about this, but we need to remember the first loaded file for the global/dict load save - -static SCA_PythonKeyboard* gp_PythonKeyboard = NULL; -static SCA_PythonMouse* gp_PythonMouse = NULL; -static SCA_PythonJoystick* gp_PythonJoysticks[JOYINDEX_MAX] = {NULL}; -#endif // WITH_PYTHON - -static KX_Scene* gp_KetsjiScene = NULL; -static KX_KetsjiEngine* gp_KetsjiEngine = NULL; -static RAS_IRasterizer* gp_Rasterizer = NULL; - - -void KX_SetActiveScene(class KX_Scene* scene) -{ - gp_KetsjiScene = scene; -} - -class KX_Scene* KX_GetActiveScene() -{ - return gp_KetsjiScene; -} - -class KX_KetsjiEngine* KX_GetActiveEngine() -{ - return gp_KetsjiEngine; -} - -/* why is this in python? */ -void KX_RasterizerDrawDebugLine(const MT_Vector3& from,const MT_Vector3& to,const MT_Vector3& color) -{ - if (gp_Rasterizer) - gp_Rasterizer->DrawDebugLine(gp_KetsjiScene, from, to, color); -} - -void KX_RasterizerDrawDebugCircle(const MT_Vector3& center, const MT_Scalar radius, const MT_Vector3& color, - const MT_Vector3& normal, int nsector) -{ - if (gp_Rasterizer) - gp_Rasterizer->DrawDebugCircle(gp_KetsjiScene, center, radius, color, normal, nsector); -} - -#ifdef WITH_PYTHON - - -static struct { - PyObject *path; - PyObject *meta_path; - PyObject *modules; -} gp_sys_backup = {NULL}; - -/* Macro for building the keyboard translation */ -//#define KX_MACRO_addToDict(dict, name) PyDict_SetItemString(dict, #name, PyLong_FromLong(SCA_IInputDevice::KX_##name)) -//#define KX_MACRO_addToDict(dict, name) PyDict_SetItemString(dict, #name, item=PyLong_FromLong(name)); Py_DECREF(item) -/* For the defines for types from logic bricks, we do stuff explicitly... */ -#define KX_MACRO_addTypesToDict(dict, name, value) KX_MACRO_addTypesToDict_fn(dict, #name, value) -static void KX_MACRO_addTypesToDict_fn(PyObject *dict, const char *name, long value) -{ - PyObject *item; - - item = PyLong_FromLong(value); - PyDict_SetItemString(dict, name, item); - Py_DECREF(item); -} - - - -// temporarily python stuff, will be put in another place later ! -#include "EXP_Python.h" -#include "SCA_PythonController.h" -// List of methods defined in the module - -static PyObject *ErrorObject; - -PyDoc_STRVAR(gPyGetRandomFloat_doc, -"getRandomFloat()\n" -"returns a random floating point value in the range [0..1]" -); -static PyObject *gPyGetRandomFloat(PyObject *) -{ - return PyFloat_FromDouble(MT_random()); -} - -static PyObject *gPySetGravity(PyObject *, PyObject *value) -{ - MT_Vector3 vec; - if (!PyVecTo(value, vec)) - return NULL; - - if (gp_KetsjiScene) - gp_KetsjiScene->SetGravity(vec); - - Py_RETURN_NONE; -} - -PyDoc_STRVAR(gPyExpandPath_doc, -"expandPath(path)\n" -"Converts a blender internal path into a proper file system path.\n" -" path - the string path to convert.\n" -"Use / as directory separator in path\n" -"You can use '//' at the start of the string to define a relative path." -"Blender replaces that string by the directory of the current .blend or runtime file to make a full path name.\n" -"The function also converts the directory separator to the local file system format." -); -static PyObject *gPyExpandPath(PyObject *, PyObject *args) -{ - char expanded[FILE_MAX]; - char* filename; - - if (!PyArg_ParseTuple(args,"s:ExpandPath",&filename)) - return NULL; - - BLI_strncpy(expanded, filename, FILE_MAX); - BLI_path_abs(expanded, gp_GamePythonPath); - return PyC_UnicodeFromByte(expanded); -} - -PyDoc_STRVAR(gPyStartGame_doc, -"startGame(blend)\n" -"Loads the blend file" -); -static PyObject *gPyStartGame(PyObject *, PyObject *args) -{ - char* blendfile; - - if (!PyArg_ParseTuple(args, "s:startGame", &blendfile)) - return NULL; - - gp_KetsjiEngine->RequestExit(KX_EXIT_REQUEST_START_OTHER_GAME); - gp_KetsjiEngine->SetNameNextGame(blendfile); - - Py_RETURN_NONE; -} - -PyDoc_STRVAR(gPyEndGame_doc, -"endGame()\n" -"Ends the current game" -); -static PyObject *gPyEndGame(PyObject *) -{ - gp_KetsjiEngine->RequestExit(KX_EXIT_REQUEST_QUIT_GAME); - - //printf("%s\n", gp_GamePythonPath); - - Py_RETURN_NONE; -} - -PyDoc_STRVAR(gPyRestartGame_doc, -"restartGame()\n" -"Restarts the current game by reloading the .blend file" -); -static PyObject *gPyRestartGame(PyObject *) -{ - gp_KetsjiEngine->RequestExit(KX_EXIT_REQUEST_RESTART_GAME); - gp_KetsjiEngine->SetNameNextGame(gp_GamePythonPath); - - Py_RETURN_NONE; -} - -PyDoc_STRVAR(gPySaveGlobalDict_doc, -"saveGlobalDict()\n" -"Saves bge.logic.globalDict to a file" -); -static PyObject *gPySaveGlobalDict(PyObject *) -{ - char marshal_path[512]; - char *marshal_buffer = NULL; - unsigned int marshal_length; - FILE *fp = NULL; - - pathGamePythonConfig(marshal_path); - marshal_length = saveGamePythonConfig(&marshal_buffer); - - if (marshal_length && marshal_buffer) - { - fp = fopen(marshal_path, "wb"); - - if (fp) - { - if (fwrite(marshal_buffer, 1, marshal_length, fp) != marshal_length) - printf("Warning: could not write marshal data\n"); - - fclose(fp); - } else { - printf("Warning: could not open marshal file\n"); - } - } else { - printf("Warning: could not create marshal buffer\n"); - } - - if (marshal_buffer) - delete [] marshal_buffer; - - Py_RETURN_NONE; -} - -PyDoc_STRVAR(gPyLoadGlobalDict_doc, -"LoadGlobalDict()\n" -"Loads bge.logic.globalDict from a file" -); -static PyObject *gPyLoadGlobalDict(PyObject *) -{ - char marshal_path[512]; - char *marshal_buffer = NULL; - int marshal_length; - FILE *fp = NULL; - int result; - - pathGamePythonConfig(marshal_path); - - fp = fopen(marshal_path, "rb"); - - if (fp) { - // obtain file size: - fseek (fp, 0, SEEK_END); - marshal_length = ftell(fp); - if (marshal_length == -1) { - printf("Warning: could not read position of '%s'\n", marshal_path); - fclose(fp); - Py_RETURN_NONE; - } - rewind(fp); - - marshal_buffer = (char*)malloc (sizeof(char)*marshal_length); - - result = fread(marshal_buffer, 1, marshal_length, fp); - - if (result == marshal_length) { - loadGamePythonConfig(marshal_buffer, marshal_length); - } else { - printf("Warning: could not read all of '%s'\n", marshal_path); - } - - free(marshal_buffer); - fclose(fp); - } else { - printf("Warning: could not open '%s'\n", marshal_path); - } - - Py_RETURN_NONE; -} - -PyDoc_STRVAR(gPyGetProfileInfo_doc, -"getProfileInfo()\n" -"returns a dictionary with profiling information" -); -static PyObject *gPyGetProfileInfo(PyObject *) -{ - return gp_KetsjiEngine->GetPyProfileDict(); -} - -PyDoc_STRVAR(gPySendMessage_doc, -"sendMessage(subject, [body, to, from])\n" -"sends a message in same manner as a message actuator" -" subject = Subject of the message" -" body = Message body" -" to = Name of object to send the message to" -" from = Name of object to send the string from" -); -static PyObject *gPySendMessage(PyObject *, PyObject *args) -{ - char* subject; - char* body = (char *)""; - char* to = (char *)""; - char* from = (char *)""; - - if (!PyArg_ParseTuple(args, "s|sss:sendMessage", &subject, &body, &to, &from)) - return NULL; - - gp_KetsjiScene->GetNetworkScene()->SendMessage(to, from, subject, body); - - Py_RETURN_NONE; -} - -// this gets a pointer to an array filled with floats -static PyObject *gPyGetSpectrum(PyObject *) -{ - PyObject *resultlist = PyList_New(512); - - for (int index = 0; index < 512; index++) - { - PyList_SET_ITEM(resultlist, index, PyFloat_FromDouble(0.0)); - } - - return resultlist; -} - -static PyObject *gPySetLogicTicRate(PyObject *, PyObject *args) -{ - float ticrate; - if (!PyArg_ParseTuple(args, "f:setLogicTicRate", &ticrate)) - return NULL; - - KX_KetsjiEngine::SetTicRate(ticrate); - Py_RETURN_NONE; -} - -static PyObject *gPyGetLogicTicRate(PyObject *) -{ - return PyFloat_FromDouble(KX_KetsjiEngine::GetTicRate()); -} - -static PyObject *gPySetExitKey(PyObject *, PyObject *args) -{ - short exitkey; - if (!PyArg_ParseTuple(args, "h:setExitKey", &exitkey)) - return NULL; - KX_KetsjiEngine::SetExitKey(exitkey); - Py_RETURN_NONE; -} - -static PyObject *gPyGetExitKey(PyObject *) -{ - return PyLong_FromLong(KX_KetsjiEngine::GetExitKey()); -} - -static PyObject *gPySetRender(PyObject *, PyObject *args) -{ - int render; - if (!PyArg_ParseTuple(args, "i:setRender", &render)) - return NULL; - KX_KetsjiEngine::SetRender(render); - Py_RETURN_NONE; -} - -static PyObject *gPyGetRender(PyObject *) -{ - return PyBool_FromLong(KX_KetsjiEngine::GetRender()); -} - - -static PyObject *gPySetMaxLogicFrame(PyObject *, PyObject *args) -{ - int frame; - if (!PyArg_ParseTuple(args, "i:setMaxLogicFrame", &frame)) - return NULL; - - KX_KetsjiEngine::SetMaxLogicFrame(frame); - Py_RETURN_NONE; -} - -static PyObject *gPyGetMaxLogicFrame(PyObject *) -{ - return PyLong_FromLong(KX_KetsjiEngine::GetMaxLogicFrame()); -} - -static PyObject *gPySetMaxPhysicsFrame(PyObject *, PyObject *args) -{ - int frame; - if (!PyArg_ParseTuple(args, "i:setMaxPhysicsFrame", &frame)) - return NULL; - - KX_KetsjiEngine::SetMaxPhysicsFrame(frame); - Py_RETURN_NONE; -} - -static PyObject *gPyGetMaxPhysicsFrame(PyObject *) -{ - return PyLong_FromLong(KX_KetsjiEngine::GetMaxPhysicsFrame()); -} - -static PyObject *gPySetPhysicsTicRate(PyObject *, PyObject *args) -{ - float ticrate; - if (!PyArg_ParseTuple(args, "f:setPhysicsTicRate", &ticrate)) - return NULL; - - PHY_GetActiveEnvironment()->SetFixedTimeStep(true,ticrate); - Py_RETURN_NONE; -} -#if 0 // unused -static PyObject *gPySetPhysicsDebug(PyObject *, PyObject *args) -{ - int debugMode; - if (!PyArg_ParseTuple(args, "i:setPhysicsDebug", &debugMode)) - return NULL; - - PHY_GetActiveEnvironment()->setDebugMode(debugMode); - Py_RETURN_NONE; -} -#endif - - -static PyObject *gPyGetPhysicsTicRate(PyObject *) -{ - return PyFloat_FromDouble(PHY_GetActiveEnvironment()->GetFixedTimeStep()); -} - -static PyObject *gPySetAnimRecordFrame(PyObject *, PyObject *args) -{ - int anim_record_frame; - - if (!PyArg_ParseTuple(args, "i:setAnimRecordFrame", &anim_record_frame)) - return NULL; - - if (anim_record_frame < 0 && (U.flag & USER_NONEGFRAMES)) { - PyErr_Format(PyExc_ValueError, "Frame number must be non-negative (was %i).", anim_record_frame); - return NULL; - } - - gp_KetsjiEngine->setAnimRecordFrame(anim_record_frame); - Py_RETURN_NONE; -} - -static PyObject *gPyGetAnimRecordFrame(PyObject *) -{ - return PyLong_FromLong(gp_KetsjiEngine->getAnimRecordFrame()); -} - -static PyObject *gPyGetAverageFrameRate(PyObject *) -{ - return PyFloat_FromDouble(KX_KetsjiEngine::GetAverageFrameRate()); -} - -static PyObject *gPyGetUseExternalClock(PyObject *) -{ - return PyBool_FromLong(gp_KetsjiEngine->GetUseExternalClock()); -} - -static PyObject *gPySetUseExternalClock(PyObject *, PyObject *args) -{ - bool bUseExternalClock; - - if (!PyArg_ParseTuple(args, "p:setUseExternalClock", &bUseExternalClock)) - return NULL; - - gp_KetsjiEngine->SetUseExternalClock(bUseExternalClock); - Py_RETURN_NONE; -} - -static PyObject *gPyGetClockTime(PyObject *) -{ - return PyFloat_FromDouble(gp_KetsjiEngine->GetClockTime()); -} - -static PyObject *gPySetClockTime(PyObject *, PyObject *args) -{ - double externalClockTime; - - if (!PyArg_ParseTuple(args, "d:setClockTime", &externalClockTime)) - return NULL; - - gp_KetsjiEngine->SetClockTime(externalClockTime); - Py_RETURN_NONE; -} - -static PyObject *gPyGetFrameTime(PyObject *) -{ - return PyFloat_FromDouble(gp_KetsjiEngine->GetFrameTime()); -} - -static PyObject *gPyGetRealTime(PyObject *) -{ - return PyFloat_FromDouble(gp_KetsjiEngine->GetRealTime()); -} - -static PyObject *gPyGetTimeScale(PyObject *) -{ - return PyFloat_FromDouble(gp_KetsjiEngine->GetTimeScale()); -} - -static PyObject *gPySetTimeScale(PyObject *, PyObject *args) -{ - double time_scale; - - if (!PyArg_ParseTuple(args, "d:setTimeScale", &time_scale)) - return NULL; - - gp_KetsjiEngine->SetTimeScale(time_scale); - Py_RETURN_NONE; -} - -static PyObject *gPyGetBlendFileList(PyObject *, PyObject *args) -{ - char cpath[sizeof(gp_GamePythonPath)]; - char *searchpath = NULL; - PyObject *list, *value; - - DIR *dp; - struct dirent *dirp; - - if (!PyArg_ParseTuple(args, "|s:getBlendFileList", &searchpath)) - return NULL; - - list = PyList_New(0); - - if (searchpath) { - BLI_strncpy(cpath, searchpath, FILE_MAX); - BLI_path_abs(cpath, gp_GamePythonPath); - } else { - /* Get the dir only */ - BLI_split_dir_part(gp_GamePythonPath, cpath, sizeof(cpath)); - } - - if ((dp = opendir(cpath)) == NULL) { - /* todo, show the errno, this shouldnt happen anyway if the blendfile is readable */ - fprintf(stderr, "Could not read directory (%s) failed, code %d (%s)\n", cpath, errno, strerror(errno)); - return list; - } - - while ((dirp = readdir(dp)) != NULL) { - if (BLI_testextensie(dirp->d_name, ".blend")) { - value = PyC_UnicodeFromByte(dirp->d_name); - PyList_Append(list, value); - Py_DECREF(value); - } - } - - closedir(dp); - return list; -} - -PyDoc_STRVAR(gPyAddScene_doc, -"addScene(name, [overlay])\n" -"Adds a scene to the game engine.\n" -" name = Name of the scene\n" -" overlay = Overlay or underlay" -); -static PyObject *gPyAddScene(PyObject *, PyObject *args) -{ - char* name; - int overlay = 1; - - if (!PyArg_ParseTuple(args, "s|i:addScene", &name , &overlay)) - return NULL; - - gp_KetsjiEngine->ConvertAndAddScene(name, (overlay != 0)); - - Py_RETURN_NONE; -} - -PyDoc_STRVAR(gPyGetCurrentScene_doc, -"getCurrentScene()\n" -"Gets a reference to the current scene." -); -static PyObject *gPyGetCurrentScene(PyObject *self) -{ - return gp_KetsjiScene->GetProxy(); -} - -PyDoc_STRVAR(gPyGetSceneList_doc, -"getSceneList()\n" -"Return a list of converted scenes." -); -static PyObject *gPyGetSceneList(PyObject *self) -{ - KX_KetsjiEngine* m_engine = KX_GetActiveEngine(); - PyObject *list; - KX_SceneList* scenes = m_engine->CurrentScenes(); - int numScenes = scenes->size(); - int i; - - list = PyList_New(numScenes); - - for (i=0;iat(i); - PyList_SET_ITEM(list, i, scene->GetProxy()); - } - - return list; -} - -static PyObject *pyPrintStats(PyObject *,PyObject *,PyObject *) -{ - gp_KetsjiScene->GetSceneConverter()->PrintStats(); - Py_RETURN_NONE; -} - -static PyObject *pyPrintExt(PyObject *,PyObject *,PyObject *) -{ - if (gp_Rasterizer) - gp_Rasterizer->PrintHardwareInfo(); - else - printf("Warning: no rasterizer detected for PrintGLInfo!\n"); - - Py_RETURN_NONE; -} - -static PyObject *gLibLoad(PyObject *, PyObject *args, PyObject *kwds) -{ - KX_Scene *kx_scene= gp_KetsjiScene; - char *path; - char *group; - Py_buffer py_buffer; - py_buffer.buf = NULL; - char *err_str= NULL; - KX_LibLoadStatus *status = NULL; - - short options=0; - int load_actions=0, verbose=0, load_scripts=1, async=0; - - static const char *kwlist[] = {"path", "group", "buffer", "load_actions", "verbose", "load_scripts", "async", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "ss|y*iiIi:LibLoad", const_cast(kwlist), - &path, &group, &py_buffer, &load_actions, &verbose, &load_scripts, &async)) - return NULL; - - /* setup options */ - if (load_actions != 0) - options |= KX_BlenderSceneConverter::LIB_LOAD_LOAD_ACTIONS; - if (verbose != 0) - options |= KX_BlenderSceneConverter::LIB_LOAD_VERBOSE; - if (load_scripts != 0) - options |= KX_BlenderSceneConverter::LIB_LOAD_LOAD_SCRIPTS; - if (async != 0) - options |= KX_BlenderSceneConverter::LIB_LOAD_ASYNC; - - if (!py_buffer.buf) - { - char abs_path[FILE_MAX]; - // Make the path absolute - BLI_strncpy(abs_path, path, sizeof(abs_path)); - BLI_path_abs(abs_path, gp_GamePythonPath); - - if ((status=kx_scene->GetSceneConverter()->LinkBlendFilePath(abs_path, group, kx_scene, &err_str, options))) { - return status->GetProxy(); - } - } - else - { - - if ((status=kx_scene->GetSceneConverter()->LinkBlendFileMemory(py_buffer.buf, py_buffer.len, path, group, kx_scene, &err_str, options))) { - PyBuffer_Release(&py_buffer); - return status->GetProxy(); - } - - PyBuffer_Release(&py_buffer); - } - - if (err_str) { - PyErr_SetString(PyExc_ValueError, err_str); - return NULL; - } - - Py_RETURN_FALSE; -} - -static PyObject *gLibNew(PyObject *, PyObject *args) -{ - KX_Scene *kx_scene= gp_KetsjiScene; - char *path; - char *group; - const char *name; - PyObject *names; - int idcode; - - if (!PyArg_ParseTuple(args,"ssO!:LibNew",&path, &group, &PyList_Type, &names)) - return NULL; - - if (kx_scene->GetSceneConverter()->GetMainDynamicPath(path)) - { - PyErr_SetString(PyExc_KeyError, "the name of the path given exists"); - return NULL; - } - - idcode= BKE_idcode_from_name(group); - if (idcode==0) { - PyErr_Format(PyExc_ValueError, "invalid group given \"%s\"", group); - return NULL; - } - - Main *maggie=BKE_main_new(); - kx_scene->GetSceneConverter()->GetMainDynamic().push_back(maggie); - strncpy(maggie->name, path, sizeof(maggie->name)-1); - - /* Copy the object into main */ - if (idcode==ID_ME) { - PyObject *ret= PyList_New(0); - PyObject *item; - for (Py_ssize_t i= 0; i < PyList_GET_SIZE(names); i++) { - name= _PyUnicode_AsString(PyList_GET_ITEM(names, i)); - if (name) { - RAS_MeshObject *meshobj= kx_scene->GetSceneConverter()->ConvertMeshSpecial(kx_scene, maggie, name); - if (meshobj) { - KX_MeshProxy* meshproxy = new KX_MeshProxy(meshobj); - item= meshproxy->NewProxy(true); - PyList_Append(ret, item); - Py_DECREF(item); - } - } - else { - PyErr_Clear(); /* wasnt a string, ignore for now */ - } - } - - return ret; - } - else { - PyErr_Format(PyExc_ValueError, "only \"Mesh\" group currently supported"); - return NULL; - } - - Py_RETURN_NONE; -} - -static PyObject *gLibFree(PyObject *, PyObject *args) -{ - KX_Scene *kx_scene= gp_KetsjiScene; - char *path; - - if (!PyArg_ParseTuple(args,"s:LibFree",&path)) - return NULL; - - if (kx_scene->GetSceneConverter()->FreeBlendFile(path)) - { - Py_RETURN_TRUE; - } - else { - Py_RETURN_FALSE; - } -} - -static PyObject *gLibList(PyObject *, PyObject *args) -{ - vector &dynMaggie = gp_KetsjiScene->GetSceneConverter()->GetMainDynamic(); - int i= 0; - PyObject *list= PyList_New(dynMaggie.size()); - - for (vector::iterator it=dynMaggie.begin(); !(it==dynMaggie.end()); it++) - { - PyList_SET_ITEM(list, i++, PyUnicode_FromString( (*it)->name) ); - } - - return list; -} - -struct PyNextFrameState pynextframestate; -static PyObject *gPyNextFrame(PyObject *) -{ - if (pynextframestate.func == NULL) Py_RETURN_NONE; - if (pynextframestate.state == NULL) Py_RETURN_NONE; //should never happen; raise exception instead? - - if (pynextframestate.func(pynextframestate.state)) //nonzero = stop - { - Py_RETURN_TRUE; - } - else // 0 = go on - { - Py_RETURN_FALSE; - } -} - - -static struct PyMethodDef game_methods[] = { - {"expandPath", (PyCFunction)gPyExpandPath, METH_VARARGS, (const char *)gPyExpandPath_doc}, - {"startGame", (PyCFunction)gPyStartGame, METH_VARARGS, (const char *)gPyStartGame_doc}, - {"endGame", (PyCFunction)gPyEndGame, METH_NOARGS, (const char *)gPyEndGame_doc}, - {"restartGame", (PyCFunction)gPyRestartGame, METH_NOARGS, (const char *)gPyRestartGame_doc}, - {"saveGlobalDict", (PyCFunction)gPySaveGlobalDict, METH_NOARGS, (const char *)gPySaveGlobalDict_doc}, - {"loadGlobalDict", (PyCFunction)gPyLoadGlobalDict, METH_NOARGS, (const char *)gPyLoadGlobalDict_doc}, - {"sendMessage", (PyCFunction)gPySendMessage, METH_VARARGS, (const char *)gPySendMessage_doc}, - {"getCurrentController", (PyCFunction) SCA_PythonController::sPyGetCurrentController, METH_NOARGS, SCA_PythonController::sPyGetCurrentController__doc__}, - {"getCurrentScene", (PyCFunction) gPyGetCurrentScene, METH_NOARGS, gPyGetCurrentScene_doc}, - {"getSceneList", (PyCFunction) gPyGetSceneList, METH_NOARGS, (const char *)gPyGetSceneList_doc}, - {"addScene", (PyCFunction)gPyAddScene, METH_VARARGS, (const char *)gPyAddScene_doc}, - {"getRandomFloat",(PyCFunction) gPyGetRandomFloat, METH_NOARGS, (const char *)gPyGetRandomFloat_doc}, - {"setGravity",(PyCFunction) gPySetGravity, METH_O, (const char *)"set Gravitation"}, - {"getSpectrum",(PyCFunction) gPyGetSpectrum, METH_NOARGS, (const char *)"get audio spectrum"}, - {"getMaxLogicFrame", (PyCFunction) gPyGetMaxLogicFrame, METH_NOARGS, (const char *)"Gets the max number of logic frame per render frame"}, - {"setMaxLogicFrame", (PyCFunction) gPySetMaxLogicFrame, METH_VARARGS, (const char *)"Sets the max number of logic frame per render frame"}, - {"getMaxPhysicsFrame", (PyCFunction) gPyGetMaxPhysicsFrame, METH_NOARGS, (const char *)"Gets the max number of physics frame per render frame"}, - {"setMaxPhysicsFrame", (PyCFunction) gPySetMaxPhysicsFrame, METH_VARARGS, (const char *)"Sets the max number of physics farme per render frame"}, - {"getLogicTicRate", (PyCFunction) gPyGetLogicTicRate, METH_NOARGS, (const char *)"Gets the logic tic rate"}, - {"setLogicTicRate", (PyCFunction) gPySetLogicTicRate, METH_VARARGS, (const char *)"Sets the logic tic rate"}, - {"getPhysicsTicRate", (PyCFunction) gPyGetPhysicsTicRate, METH_NOARGS, (const char *)"Gets the physics tic rate"}, - {"setPhysicsTicRate", (PyCFunction) gPySetPhysicsTicRate, METH_VARARGS, (const char *)"Sets the physics tic rate"}, - {"getAnimRecordFrame", (PyCFunction) gPyGetAnimRecordFrame, METH_NOARGS, (const char *)"Gets the current frame number used for animation recording"}, - {"setAnimRecordFrame", (PyCFunction) gPySetAnimRecordFrame, METH_VARARGS, (const char *)"Sets the current frame number used for animation recording"}, - {"getExitKey", (PyCFunction) gPyGetExitKey, METH_NOARGS, (const char *)"Gets the key used to exit the game engine"}, - {"setExitKey", (PyCFunction) gPySetExitKey, METH_VARARGS, (const char *)"Sets the key used to exit the game engine"}, - {"setRender", (PyCFunction) gPySetRender, METH_VARARGS, (const char *)"Set the global render flag"}, - {"getRender", (PyCFunction) gPyGetRender, METH_NOARGS, (const char *)"get the global render flag value"}, - {"getUseExternalClock", (PyCFunction) gPyGetUseExternalClock, METH_NOARGS, (const char *)"Get if we use the time provided by an external clock"}, - {"setUseExternalClock", (PyCFunction) gPySetUseExternalClock, METH_VARARGS, (const char *)"Set if we use the time provided by an external clock"}, - {"getClockTime", (PyCFunction) gPyGetClockTime, METH_NOARGS, (const char *)"Get the last BGE render time. " - "The BGE render time is the simulated time corresponding to the next scene that will be renderered"}, - {"setClockTime", (PyCFunction) gPySetClockTime, METH_VARARGS, (const char *)"Set the BGE render time. " - "The BGE render time is the simulated time corresponding to the next scene that will be rendered"}, - {"getFrameTime", (PyCFunction) gPyGetFrameTime, METH_NOARGS, (const char *)"Get the BGE last frametime. " - "The BGE frame time is the simulated time corresponding to the last call of the logic system"}, - {"getRealTime", (PyCFunction) gPyGetRealTime, METH_NOARGS, (const char *)"Get the real system time. " - "The real-time corresponds to the system time" }, - {"getAverageFrameRate", (PyCFunction) gPyGetAverageFrameRate, METH_NOARGS, (const char *)"Gets the estimated average frame rate"}, - {"getTimeScale", (PyCFunction) gPyGetTimeScale, METH_NOARGS, (const char *)"Get the time multiplier"}, - {"setTimeScale", (PyCFunction) gPySetTimeScale, METH_VARARGS, (const char *)"Set the time multiplier"}, - {"getBlendFileList", (PyCFunction)gPyGetBlendFileList, METH_VARARGS, (const char *)"Gets a list of blend files in the same directory as the current blend file"}, - {"PrintGLInfo", (PyCFunction)pyPrintExt, METH_NOARGS, (const char *)"Prints GL Extension Info"}, - {"PrintMemInfo", (PyCFunction)pyPrintStats, METH_NOARGS, (const char *)"Print engine statistics"}, - {"NextFrame", (PyCFunction)gPyNextFrame, METH_NOARGS, (const char *)"Render next frame (if Python has control)"}, - {"getProfileInfo", (PyCFunction)gPyGetProfileInfo, METH_NOARGS, gPyGetProfileInfo_doc}, - /* library functions */ - {"LibLoad", (PyCFunction)gLibLoad, METH_VARARGS|METH_KEYWORDS, (const char *)""}, - {"LibNew", (PyCFunction)gLibNew, METH_VARARGS, (const char *)""}, - {"LibFree", (PyCFunction)gLibFree, METH_VARARGS, (const char *)""}, - {"LibList", (PyCFunction)gLibList, METH_VARARGS, (const char *)""}, - - {NULL, (PyCFunction) NULL, 0, NULL } -}; - -static PyObject *gPyGetWindowHeight(PyObject *, PyObject *args) -{ - return PyLong_FromLong((gp_Canvas ? gp_Canvas->GetHeight() : 0)); -} - - - -static PyObject *gPyGetWindowWidth(PyObject *, PyObject *args) -{ - return PyLong_FromLong((gp_Canvas ? gp_Canvas->GetWidth() : 0)); -} - - - -// temporarility visibility thing, will be moved to rasterizer/renderer later -bool gUseVisibilityTemp = false; - -static PyObject *gPyEnableVisibility(PyObject *, PyObject *args) -{ - int visible; - if (!PyArg_ParseTuple(args,"i:enableVisibility",&visible)) - return NULL; - - gUseVisibilityTemp = (visible != 0); - Py_RETURN_NONE; -} - - - -static PyObject *gPyShowMouse(PyObject *, PyObject *args) -{ - int visible; - if (!PyArg_ParseTuple(args,"i:showMouse",&visible)) - return NULL; - - if (visible) - { - if (gp_Canvas) - gp_Canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL); - } else - { - if (gp_Canvas) - gp_Canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE); - } - - Py_RETURN_NONE; -} - - - -static PyObject *gPySetMousePosition(PyObject *, PyObject *args) -{ - int x,y; - if (!PyArg_ParseTuple(args,"ii:setMousePosition",&x,&y)) - return NULL; - - if (gp_Canvas) - gp_Canvas->SetMousePosition(x,y); - - Py_RETURN_NONE; -} - -static PyObject *gPySetEyeSeparation(PyObject *, PyObject *args) -{ - float sep; - if (!PyArg_ParseTuple(args, "f:setEyeSeparation", &sep)) - return NULL; - - if (!gp_Rasterizer) { - PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setEyeSeparation(float), Rasterizer not available"); - return NULL; - } - - gp_Rasterizer->SetEyeSeparation(sep); - - Py_RETURN_NONE; -} - -static PyObject *gPyGetEyeSeparation(PyObject *) -{ - if (!gp_Rasterizer) { - PyErr_SetString(PyExc_RuntimeError, "Rasterizer.getEyeSeparation(), Rasterizer not available"); - return NULL; - } - - return PyFloat_FromDouble(gp_Rasterizer->GetEyeSeparation()); -} - -static PyObject *gPySetFocalLength(PyObject *, PyObject *args) -{ - float focus; - if (!PyArg_ParseTuple(args, "f:setFocalLength", &focus)) - return NULL; - - if (!gp_Rasterizer) { - PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setFocalLength(float), Rasterizer not available"); - return NULL; - } - - gp_Rasterizer->SetFocalLength(focus); - - Py_RETURN_NONE; -} - -static PyObject *gPyGetFocalLength(PyObject *, PyObject *, PyObject *) -{ - if (!gp_Rasterizer) { - PyErr_SetString(PyExc_RuntimeError, "Rasterizer.getFocalLength(), Rasterizer not available"); - return NULL; - } - - return PyFloat_FromDouble(gp_Rasterizer->GetFocalLength()); - - Py_RETURN_NONE; -} - -static PyObject *gPyGetStereoEye(PyObject *, PyObject *, PyObject *) -{ - int flag = RAS_IRasterizer::RAS_STEREO_LEFTEYE; - - if (!gp_Rasterizer) { - PyErr_SetString(PyExc_RuntimeError, "Rasterizer.getStereoEye(), Rasterizer not available"); - return NULL; - } - - if (gp_Rasterizer->Stereo()) - flag = gp_Rasterizer->GetEye(); - - return PyLong_FromLong(flag); -} - -static PyObject *gPySetBackgroundColor(PyObject *, PyObject *value) -{ - MT_Vector4 vec; - if (!PyVecTo(value, vec)) - return NULL; - - KX_WorldInfo *wi = gp_KetsjiScene->GetWorldInfo(); - if (!wi->hasWorld()) { - PyErr_SetString(PyExc_RuntimeError, "bge.render.SetBackgroundColor(color), World not available"); - return NULL; - } - - ShowDeprecationWarning("setBackgroundColor()", "KX_WorldInfo.background_color"); - wi->setBackColor((float)vec[0], (float)vec[1], (float)vec[2]); - - Py_RETURN_NONE; -} - -static PyObject *gPyMakeScreenshot(PyObject *, PyObject *args) -{ - char* filename; - if (!PyArg_ParseTuple(args,"s:makeScreenshot",&filename)) - return NULL; - - if (gp_Canvas) - { - gp_Canvas->MakeScreenShot(filename); - } - - Py_RETURN_NONE; -} - -static PyObject *gPyEnableMotionBlur(PyObject *, PyObject *args) -{ - float motionblurvalue; - if (!PyArg_ParseTuple(args,"f:enableMotionBlur",&motionblurvalue)) - return NULL; - - if (!gp_Rasterizer) { - PyErr_SetString(PyExc_RuntimeError, "Rasterizer.enableMotionBlur(float), Rasterizer not available"); - return NULL; - } - - gp_Rasterizer->EnableMotionBlur(motionblurvalue); - - Py_RETURN_NONE; -} - -static PyObject *gPyDisableMotionBlur(PyObject *) -{ - if (!gp_Rasterizer) { - PyErr_SetString(PyExc_RuntimeError, "Rasterizer.disableMotionBlur(), Rasterizer not available"); - return NULL; - } - - gp_Rasterizer->DisableMotionBlur(); - - Py_RETURN_NONE; -} - -static int getGLSLSettingFlag(const char *setting) -{ - if (strcmp(setting, "lights") == 0) - return GAME_GLSL_NO_LIGHTS; - else if (strcmp(setting, "shaders") == 0) - return GAME_GLSL_NO_SHADERS; - else if (strcmp(setting, "shadows") == 0) - return GAME_GLSL_NO_SHADOWS; - else if (strcmp(setting, "ramps") == 0) - return GAME_GLSL_NO_RAMPS; - else if (strcmp(setting, "nodes") == 0) - return GAME_GLSL_NO_NODES; - else if (strcmp(setting, "extra_textures") == 0) - return GAME_GLSL_NO_EXTRA_TEX; - else - return -1; -} - -static PyObject *gPySetGLSLMaterialSetting(PyObject *, - PyObject *args, - PyObject *) -{ - GlobalSettings *gs= gp_KetsjiEngine->GetGlobalSettings(); - char *setting; - int enable, flag, sceneflag; - - if (!PyArg_ParseTuple(args,"si:setGLSLMaterialSetting",&setting,&enable)) - return NULL; - - flag = getGLSLSettingFlag(setting); - - if (flag == -1) { - PyErr_SetString(PyExc_ValueError, "Rasterizer.setGLSLMaterialSetting(string): glsl setting is not known"); - return NULL; - } - - sceneflag= gs->glslflag; - - if (enable) - gs->glslflag &= ~flag; - else - gs->glslflag |= flag; - - /* display lists and GLSL materials need to be remade */ - if (sceneflag != gs->glslflag) { - GPU_materials_free(); - if (gp_KetsjiEngine) { - KX_SceneList *scenes = gp_KetsjiEngine->CurrentScenes(); - KX_SceneList::iterator it; - - for (it=scenes->begin(); it!=scenes->end(); it++) { - // temporarily store the glsl settings in the scene for the GLSL materials - (*it)->GetBlenderScene()->gm.flag = gs->glslflag; - if ((*it)->GetBucketManager()) { - (*it)->GetBucketManager()->ReleaseDisplayLists(); - (*it)->GetBucketManager()->ReleaseMaterials(); - } - } - } - } - - Py_RETURN_NONE; -} - -static PyObject *gPyGetGLSLMaterialSetting(PyObject *, - PyObject *args, - PyObject *) -{ - GlobalSettings *gs= gp_KetsjiEngine->GetGlobalSettings(); - char *setting; - int enabled = 0, flag; - - if (!PyArg_ParseTuple(args,"s:getGLSLMaterialSetting",&setting)) - return NULL; - - flag = getGLSLSettingFlag(setting); - - if (flag == -1) { - PyErr_SetString(PyExc_ValueError, "Rasterizer.getGLSLMaterialSetting(string): glsl setting is not known"); - return NULL; - } - - enabled = ((gs->glslflag & flag) != 0); - return PyLong_FromLong(enabled); -} - -#define KX_BLENDER_MULTITEX_MATERIAL 1 -#define KX_BLENDER_GLSL_MATERIAL 2 - -static PyObject *gPySetMaterialType(PyObject *, - PyObject *args, - PyObject *) -{ - GlobalSettings *gs= gp_KetsjiEngine->GetGlobalSettings(); - int type; - - if (!PyArg_ParseTuple(args,"i:setMaterialType",&type)) - return NULL; - - if (type == KX_BLENDER_GLSL_MATERIAL) - gs->matmode= GAME_MAT_GLSL; - else if (type == KX_BLENDER_MULTITEX_MATERIAL) - gs->matmode= GAME_MAT_MULTITEX; - else { - PyErr_SetString(PyExc_ValueError, "Rasterizer.setMaterialType(int): material type is not known"); - return NULL; - } - - Py_RETURN_NONE; -} - -static PyObject *gPyGetMaterialType(PyObject *) -{ - GlobalSettings *gs= gp_KetsjiEngine->GetGlobalSettings(); - int flag; - - if (gs->matmode == GAME_MAT_GLSL) - flag = KX_BLENDER_GLSL_MATERIAL; - else - flag = KX_BLENDER_MULTITEX_MATERIAL; - - return PyLong_FromLong(flag); -} - -static PyObject *gPySetAnisotropicFiltering(PyObject *, PyObject *args) -{ - short level; - - if (!PyArg_ParseTuple(args, "h:setAnisotropicFiltering", &level)) - return NULL; - - if (level != 1 && level != 2 && level != 4 && level != 8 && level != 16) { - PyErr_SetString(PyExc_ValueError, "Rasterizer.setAnisotropicFiltering(level): Expected value of 1, 2, 4, 8, or 16 for value"); - return NULL; - } - - gp_Rasterizer->SetAnisotropicFiltering(level); - - Py_RETURN_NONE; -} - -static PyObject *gPyGetAnisotropicFiltering(PyObject *, PyObject *args) -{ - return PyLong_FromLong(gp_Rasterizer->GetAnisotropicFiltering()); -} - -static PyObject *gPyDrawLine(PyObject *, PyObject *args) -{ - PyObject *ob_from; - PyObject *ob_to; - PyObject *ob_color; - - if (!gp_Rasterizer) { - PyErr_SetString(PyExc_RuntimeError, "Rasterizer.drawLine(obFrom, obTo, color): Rasterizer not available"); - return NULL; - } - - if (!PyArg_ParseTuple(args,"OOO:drawLine",&ob_from,&ob_to,&ob_color)) - return NULL; - - MT_Vector3 from; - MT_Vector3 to; - MT_Vector3 color; - if (!PyVecTo(ob_from, from)) - return NULL; - if (!PyVecTo(ob_to, to)) - return NULL; - if (!PyVecTo(ob_color, color)) - return NULL; - - gp_Rasterizer->DrawDebugLine(gp_KetsjiScene, from, to, color); - - Py_RETURN_NONE; -} - -static PyObject *gPySetWindowSize(PyObject *, PyObject *args) -{ - int width, height; - if (!PyArg_ParseTuple(args, "ii:resize", &width, &height)) - return NULL; - - gp_Canvas->ResizeWindow(width, height); - Py_RETURN_NONE; -} - -static PyObject *gPySetFullScreen(PyObject *, PyObject *value) -{ - gp_Canvas->SetFullScreen(PyObject_IsTrue(value)); - Py_RETURN_NONE; -} - -static PyObject *gPyGetFullScreen(PyObject *) -{ - return PyBool_FromLong(gp_Canvas->GetFullScreen()); -} - -static PyObject *gPySetMipmapping(PyObject *, PyObject *args) -{ - int val = 0; - - if (!PyArg_ParseTuple(args, "i:setMipmapping", &val)) - return NULL; - - if (val < 0 || val > RAS_IRasterizer::RAS_MIPMAP_MAX) { - PyErr_SetString(PyExc_ValueError, "Rasterizer.setMipmapping(val): invalid mipmaping option"); - return NULL; - } - - if (!gp_Rasterizer) { - PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setMipmapping(val): Rasterizer not available"); - return NULL; - } - - gp_Rasterizer->SetMipmapping((RAS_IRasterizer::MipmapOption)val); - Py_RETURN_NONE; -} - -static PyObject *gPyGetMipmapping(PyObject *) -{ - if (!gp_Rasterizer) { - PyErr_SetString(PyExc_RuntimeError, "Rasterizer.getMipmapping(): Rasterizer not available"); - return NULL; - } - return PyLong_FromLong(gp_Rasterizer->GetMipmapping()); -} - -static PyObject *gPySetVsync(PyObject *, PyObject *args) -{ - int interval; - - if (!PyArg_ParseTuple(args, "i:setVsync", &interval)) - return NULL; - - if (interval < 0 || interval > VSYNC_ADAPTIVE) { - PyErr_SetString(PyExc_ValueError, "Rasterizer.setVsync(value): value must be VSYNC_OFF, VSYNC_ON, or VSYNC_ADAPTIVE"); - return NULL; - } - - if (interval == VSYNC_ADAPTIVE) - interval = -1; - gp_Canvas->SetSwapInterval((interval == VSYNC_ON) ? 1 : 0); - Py_RETURN_NONE; -} - -static PyObject *gPyGetVsync(PyObject *) -{ - int interval = 0; - gp_Canvas->GetSwapInterval(interval); - return PyLong_FromLong(interval); -} - -static PyObject *gPyShowFramerate(PyObject *, PyObject *args) -{ - int visible; - if (!PyArg_ParseTuple(args,"i:showFramerate",&visible)) - return NULL; - - if (visible && gp_KetsjiEngine) - gp_KetsjiEngine->SetShowFramerate(true); - else - gp_KetsjiEngine->SetShowFramerate(false); - - Py_RETURN_NONE; -} - -static PyObject *gPyShowProfile(PyObject *, PyObject *args) -{ - int visible; - if (!PyArg_ParseTuple(args,"i:showProfile",&visible)) - return NULL; - - if (visible && gp_KetsjiEngine) - gp_KetsjiEngine->SetShowProfile(true); - else - gp_KetsjiEngine->SetShowProfile(false); - - Py_RETURN_NONE; -} - -static PyObject *gPyShowProperties(PyObject *, PyObject *args) -{ - int visible; - if (!PyArg_ParseTuple(args,"i:showProperties",&visible)) - return NULL; - - if (visible && gp_KetsjiEngine) - gp_KetsjiEngine->SetShowProperties(true); - else - gp_KetsjiEngine->SetShowProperties(false); - - Py_RETURN_NONE; -} - -static PyObject *gPyAutoDebugList(PyObject *, PyObject *args) -{ - int add; - if (!PyArg_ParseTuple(args,"i:autoAddProperties",&add)) - return NULL; - - if (add && gp_KetsjiEngine) - gp_KetsjiEngine->SetAutoAddDebugProperties(true); - else - gp_KetsjiEngine->SetAutoAddDebugProperties(false); - - Py_RETURN_NONE; -} - -static PyObject *gPyClearDebugList(PyObject *) -{ - if (gp_KetsjiScene) - gp_KetsjiScene->RemoveAllDebugProperties(); - - Py_RETURN_NONE; -} - -static PyObject *gPyGetDisplayDimensions(PyObject *) -{ - PyObject *result; - int width, height; - - gp_Canvas->GetDisplayDimensions(width, height); - - result = PyTuple_New(2); - PyTuple_SET_ITEMS(result, - PyLong_FromLong(width), - PyLong_FromLong(height)); - - return result; -} - - -/* python wrapper around RAS_IOffScreen - * Should eventually gets its own file - */ - -static void PyRASOffScreen__tp_dealloc(PyRASOffScreen *self) -{ - if (self->ofs) - delete self->ofs; - Py_TYPE(self)->tp_free((PyObject *)self); -} - -PyDoc_STRVAR(py_RASOffScreen_doc, -"RASOffscreen(width, height) -> new GPU Offscreen object" -"initialized to hold a framebuffer object of ``width`` x ``height``.\n" -"" -); - -PyDoc_STRVAR(RASOffScreen_width_doc, "Offscreen buffer width.\n\n:type: integer"); -static PyObject *RASOffScreen_width_get(PyRASOffScreen *self, void *UNUSED(type)) -{ - return PyLong_FromLong(self->ofs->GetWidth()); -} - -PyDoc_STRVAR(RASOffScreen_height_doc, "Offscreen buffer height.\n\n:type: GLsizei"); -static PyObject *RASOffScreen_height_get(PyRASOffScreen *self, void *UNUSED(type)) -{ - return PyLong_FromLong(self->ofs->GetHeight()); -} - -PyDoc_STRVAR(RASOffScreen_color_doc, "Offscreen buffer texture object (if target is RAS_OFS_RENDER_TEXTURE).\n\n:type: GLuint"); -static PyObject *RASOffScreen_color_get(PyRASOffScreen *self, void *UNUSED(type)) -{ - return PyLong_FromLong(self->ofs->GetColor()); -} - -static PyGetSetDef RASOffScreen_getseters[] = { - {(char *)"width", (getter)RASOffScreen_width_get, (setter)NULL, RASOffScreen_width_doc, NULL}, - {(char *)"height", (getter)RASOffScreen_height_get, (setter)NULL, RASOffScreen_height_doc, NULL}, - {(char *)"color", (getter)RASOffScreen_color_get, (setter)NULL, RASOffScreen_color_doc, NULL}, - {NULL, NULL, NULL, NULL, NULL} /* Sentinel */ -}; - -static int PyRASOffScreen__tp_init(PyRASOffScreen *self, PyObject *args, PyObject *kwargs) -{ - int width, height, samples, target; - const char *keywords[] = {"width", "height", "samples", "target", NULL}; - - samples = 0; - target = RAS_IOffScreen::RAS_OFS_RENDER_BUFFER; - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ii|ii:RASOffscreen", (char **)keywords, &width, &height, &samples, &target)) { - return -1; - } - - if (width <= 0) { - PyErr_SetString(PyExc_ValueError, "negative 'width' given"); - return -1; - } - - if (height <= 0) { - PyErr_SetString(PyExc_ValueError, "negative 'height' given"); - return -1; - } - - if (samples < 0) { - PyErr_SetString(PyExc_ValueError, "negative 'samples' given"); - return -1; - } - - if (target != RAS_IOffScreen::RAS_OFS_RENDER_BUFFER && target != RAS_IOffScreen::RAS_OFS_RENDER_TEXTURE) - { - PyErr_SetString(PyExc_ValueError, "invalid 'target' given, can only be RAS_OFS_RENDER_BUFFER or RAS_OFS_RENDER_TEXTURE"); - return -1; - } - if (!gp_Rasterizer) - { - PyErr_SetString(PyExc_SystemError, "no rasterizer"); - return -1; - } - self->ofs = gp_Rasterizer->CreateOffScreen(width, height, samples, target); - if (!self->ofs) { - PyErr_SetString(PyExc_SystemError, "creation failed"); - return -1; - } - return 0; -} - -PyTypeObject PyRASOffScreen_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "RASOffScreen", /* tp_name */ - sizeof(PyRASOffScreen), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)PyRASOffScreen__tp_dealloc, /* tp_dealloc */ - NULL, /* tp_print */ - NULL, /* tp_getattr */ - NULL, /* tp_setattr */ - NULL, /* tp_compare */ - NULL, /* tp_repr */ - NULL, /* tp_as_number */ - NULL, /* tp_as_sequence */ - NULL, /* tp_as_mapping */ - NULL, /* tp_hash */ - NULL, /* tp_call */ - NULL, /* tp_str */ - NULL, /* tp_getattro */ - NULL, /* tp_setattro */ - NULL, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - py_RASOffScreen_doc, /* Documentation string */ - NULL, /* tp_traverse */ - NULL, /* tp_clear */ - NULL, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - NULL, /* tp_iter */ - NULL, /* tp_iternext */ - NULL, /* tp_methods */ - NULL, /* tp_members */ - RASOffScreen_getseters, /* tp_getset */ - NULL, /* tp_base */ - NULL, /* tp_dict */ - NULL, /* tp_descr_get */ - NULL, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)PyRASOffScreen__tp_init, /* tp_init */ - (allocfunc)PyType_GenericAlloc, /* tp_alloc */ - (newfunc)PyType_GenericNew, /* tp_new */ - (freefunc)0, /* tp_free */ - NULL, /* tp_is_gc */ - NULL, /* tp_bases */ - NULL, /* tp_mro */ - NULL, /* tp_cache */ - NULL, /* tp_subclasses */ - NULL, /* tp_weaklist */ - (destructor) NULL /* tp_del */ -}; - - -static PyObject *gPyOffScreenCreate(PyObject *UNUSED(self), PyObject *args) -{ - int width; - int height; - int samples; - int target; - - samples = 0; - if (!PyArg_ParseTuple(args, "ii|ii:offScreenCreate", &width, &height, &samples, &target)) - return NULL; - - return PyObject_CallObject((PyObject *) &PyRASOffScreen_Type, args); -} - -PyDoc_STRVAR(Rasterizer_module_documentation, -"This is the Python API for the game engine of Rasterizer" -); - -static struct PyMethodDef rasterizer_methods[] = { - {"getWindowWidth",(PyCFunction) gPyGetWindowWidth, - METH_VARARGS, "getWindowWidth doc"}, - {"getWindowHeight",(PyCFunction) gPyGetWindowHeight, - METH_VARARGS, "getWindowHeight doc"}, - {"makeScreenshot",(PyCFunction)gPyMakeScreenshot, - METH_VARARGS, "make Screenshot doc"}, - {"enableVisibility",(PyCFunction) gPyEnableVisibility, - METH_VARARGS, "enableVisibility doc"}, - {"showMouse",(PyCFunction) gPyShowMouse, - METH_VARARGS, "showMouse(bool visible)"}, - {"setMousePosition",(PyCFunction) gPySetMousePosition, - METH_VARARGS, "setMousePosition(int x,int y)"}, - {"setBackgroundColor",(PyCFunction)gPySetBackgroundColor,METH_O,"set Background Color (rgb)"}, - {"enableMotionBlur",(PyCFunction)gPyEnableMotionBlur,METH_VARARGS,"enable motion blur"}, - {"disableMotionBlur",(PyCFunction)gPyDisableMotionBlur,METH_NOARGS,"disable motion blur"}, - - {"setEyeSeparation", (PyCFunction) gPySetEyeSeparation, METH_VARARGS, "set the eye separation for stereo mode"}, - {"getEyeSeparation", (PyCFunction) gPyGetEyeSeparation, METH_NOARGS, "get the eye separation for stereo mode"}, - {"setFocalLength", (PyCFunction) gPySetFocalLength, METH_VARARGS, "set the focal length for stereo mode"}, - {"getFocalLength", (PyCFunction) gPyGetFocalLength, METH_VARARGS, "get the focal length for stereo mode"}, - {"getStereoEye", (PyCFunction) gPyGetStereoEye, METH_VARARGS, "get the current stereoscopy eye being rendered"}, - {"setMaterialMode",(PyCFunction) gPySetMaterialType, - METH_VARARGS, "set the material mode to use for OpenGL rendering"}, - {"getMaterialMode",(PyCFunction) gPyGetMaterialType, - METH_NOARGS, "get the material mode being used for OpenGL rendering"}, - {"setGLSLMaterialSetting",(PyCFunction) gPySetGLSLMaterialSetting, - METH_VARARGS, "set the state of a GLSL material setting"}, - {"getGLSLMaterialSetting",(PyCFunction) gPyGetGLSLMaterialSetting, - METH_VARARGS, "get the state of a GLSL material setting"}, - {"setAnisotropicFiltering", (PyCFunction) gPySetAnisotropicFiltering, - METH_VARARGS, "set the anisotropic filtering level (must be one of 1, 2, 4, 8, 16)"}, - {"getAnisotropicFiltering", (PyCFunction) gPyGetAnisotropicFiltering, - METH_VARARGS, "get the anisotropic filtering level"}, - {"drawLine", (PyCFunction) gPyDrawLine, - METH_VARARGS, "draw a line on the screen"}, - {"setWindowSize", (PyCFunction) gPySetWindowSize, METH_VARARGS, ""}, - {"setFullScreen", (PyCFunction) gPySetFullScreen, METH_O, ""}, - {"getFullScreen", (PyCFunction) gPyGetFullScreen, METH_NOARGS, ""}, - {"getDisplayDimensions", (PyCFunction) gPyGetDisplayDimensions, METH_NOARGS, - "Get the actual dimensions, in pixels, of the physical display (e.g., the monitor)."}, - {"setMipmapping", (PyCFunction) gPySetMipmapping, METH_VARARGS, ""}, - {"getMipmapping", (PyCFunction) gPyGetMipmapping, METH_NOARGS, ""}, - {"setVsync", (PyCFunction) gPySetVsync, METH_VARARGS, ""}, - {"getVsync", (PyCFunction) gPyGetVsync, METH_NOARGS, ""}, - {"showFramerate",(PyCFunction) gPyShowFramerate, METH_VARARGS, "show or hide the framerate"}, - {"showProfile",(PyCFunction) gPyShowProfile, METH_VARARGS, "show or hide the profile"}, - {"showProperties",(PyCFunction) gPyShowProperties, METH_VARARGS, "show or hide the debug properties"}, - {"autoDebugList",(PyCFunction) gPyAutoDebugList, METH_VARARGS, "enable or disable auto adding debug properties to the debug list"}, - {"clearDebugList",(PyCFunction) gPyClearDebugList, METH_NOARGS, "clears the debug property list"}, - {"offScreenCreate", (PyCFunction) gPyOffScreenCreate, METH_VARARGS, "create an offscreen buffer object, arguments are width and height in pixels"}, - { NULL, (PyCFunction) NULL, 0, NULL } -}; - - - -PyDoc_STRVAR(GameLogic_module_documentation, -"This is the Python API for the game engine of bge.logic" -); - -static struct PyModuleDef GameLogic_module_def = { - {}, /* m_base */ - "GameLogic", /* m_name */ - GameLogic_module_documentation, /* m_doc */ - 0, /* m_size */ - game_methods, /* m_methods */ - 0, /* m_reload */ - 0, /* m_traverse */ - 0, /* m_clear */ - 0, /* m_free */ -}; - -PyMODINIT_FUNC initGameLogicPythonBinding() -{ - PyObject *m; - PyObject *d; - PyObject *item; /* temp PyObject *storage */ - - gUseVisibilityTemp=false; - - PyObjectPlus::ClearDeprecationWarning(); /* Not that nice to call here but makes sure warnings are reset between loading scenes */ - - m = PyModule_Create(&GameLogic_module_def); - PyDict_SetItemString(PySys_GetObject("modules"), GameLogic_module_def.m_name, m); - - - // Add some symbolic constants to the module - d = PyModule_GetDict(m); - - // can be overwritten later for gameEngine instances that can load new blend files and re-initialize this module - // for now its safe to make sure it exists for other areas such as the web plugin - - PyDict_SetItemString(d, "globalDict", item=PyDict_New()); Py_DECREF(item); - - // Add keyboard and mouse attributes to this module - MT_assert(!gp_PythonKeyboard); - gp_PythonKeyboard = new SCA_PythonKeyboard(gp_KetsjiEngine->GetKeyboardDevice()); - PyDict_SetItemString(d, "keyboard", gp_PythonKeyboard->NewProxy(true)); - - MT_assert(!gp_PythonMouse); - gp_PythonMouse = new SCA_PythonMouse(gp_KetsjiEngine->GetMouseDevice(), gp_Canvas); - PyDict_SetItemString(d, "mouse", gp_PythonMouse->NewProxy(true)); - - PyObject* joylist = PyList_New(JOYINDEX_MAX); - for (int i=0; iConnected()) { - gp_PythonJoysticks[i] = new SCA_PythonJoystick(joy); - item = gp_PythonJoysticks[i]->NewProxy(true); - } - else { - if (joy) { - joy->ReleaseInstance(); - } - item = Py_None; - } - - Py_INCREF(item); - PyList_SET_ITEM(joylist, i, item); - } - PyDict_SetItemString(d, "joysticks", joylist); - - ErrorObject = PyUnicode_FromString("GameLogic.error"); - PyDict_SetItemString(d, "error", ErrorObject); - Py_DECREF(ErrorObject); - - // XXXX Add constants here - /* To use logic bricks, we need some sort of constants. Here, we associate */ - /* constants and sumbolic names. Add them to dictionary d. */ - - /* 1. true and false: needed for everyone */ - KX_MACRO_addTypesToDict(d, KX_TRUE, SCA_ILogicBrick::KX_TRUE); - KX_MACRO_addTypesToDict(d, KX_FALSE, SCA_ILogicBrick::KX_FALSE); - - /* 2. Property sensor */ - KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_EQUAL, SCA_PropertySensor::KX_PROPSENSOR_EQUAL); - KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_NOTEQUAL, SCA_PropertySensor::KX_PROPSENSOR_NOTEQUAL); - KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_INTERVAL, SCA_PropertySensor::KX_PROPSENSOR_INTERVAL); - KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_CHANGED, SCA_PropertySensor::KX_PROPSENSOR_CHANGED); - KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_EXPRESSION, SCA_PropertySensor::KX_PROPSENSOR_EXPRESSION); - KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_LESSTHAN, SCA_PropertySensor::KX_PROPSENSOR_LESSTHAN); - KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_GREATERTHAN, SCA_PropertySensor::KX_PROPSENSOR_GREATERTHAN); - - /* 3. Constraint actuator */ - KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCX); - KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCY); - KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCZ); - KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTX); - KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTY); - KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTZ); - KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPX); - KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPY); - KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPZ); - KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNX); - KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNY); - KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNZ); - KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIX); - KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIY); - KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIZ); - KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHPX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPX); - KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHPY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPY); - KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHPZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPZ); - KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHNX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNX); - KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHNY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNY); - KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHNZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNZ); - KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_NORMAL, KX_ConstraintActuator::KX_ACT_CONSTRAINT_NORMAL); - KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_MATERIAL, KX_ConstraintActuator::KX_ACT_CONSTRAINT_MATERIAL); - KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_PERMANENT, KX_ConstraintActuator::KX_ACT_CONSTRAINT_PERMANENT); - KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DISTANCE, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DISTANCE); - KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCAL, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCAL); - KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DOROTFH, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DOROTFH); - - /* 4. Random distribution types */ - KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_CONST, SCA_RandomActuator::KX_RANDOMACT_BOOL_CONST); - KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_UNIFORM, SCA_RandomActuator::KX_RANDOMACT_BOOL_UNIFORM); - KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_BERNOUILLI, SCA_RandomActuator::KX_RANDOMACT_BOOL_BERNOUILLI); - KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_CONST, SCA_RandomActuator::KX_RANDOMACT_INT_CONST); - KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_UNIFORM, SCA_RandomActuator::KX_RANDOMACT_INT_UNIFORM); - KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_POISSON, SCA_RandomActuator::KX_RANDOMACT_INT_POISSON); - KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_CONST, SCA_RandomActuator::KX_RANDOMACT_FLOAT_CONST); - KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_UNIFORM, SCA_RandomActuator::KX_RANDOMACT_FLOAT_UNIFORM); - KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_NORMAL, SCA_RandomActuator::KX_RANDOMACT_FLOAT_NORMAL); - KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL, SCA_RandomActuator::KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL); - - /* 5. Sound actuator */ - KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYSTOP, KX_SoundActuator::KX_SOUNDACT_PLAYSTOP); - KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYEND, KX_SoundActuator::KX_SOUNDACT_PLAYEND); - KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPSTOP, KX_SoundActuator::KX_SOUNDACT_LOOPSTOP); - KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPEND, KX_SoundActuator::KX_SOUNDACT_LOOPEND); - KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL, KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL); - KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP, KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP); - - /* 6. Action actuator */ - KX_MACRO_addTypesToDict(d, KX_ACTIONACT_PLAY, ACT_ACTION_PLAY); - KX_MACRO_addTypesToDict(d, KX_ACTIONACT_PINGPONG, ACT_ACTION_PINGPONG); - KX_MACRO_addTypesToDict(d, KX_ACTIONACT_FLIPPER, ACT_ACTION_FLIPPER); - KX_MACRO_addTypesToDict(d, KX_ACTIONACT_LOOPSTOP, ACT_ACTION_LOOP_STOP); - KX_MACRO_addTypesToDict(d, KX_ACTIONACT_LOOPEND, ACT_ACTION_LOOP_END); - KX_MACRO_addTypesToDict(d, KX_ACTIONACT_PROPERTY, ACT_ACTION_FROM_PROP); - - /* 7. GL_BlendFunc */ - KX_MACRO_addTypesToDict(d, BL_ZERO, GL_ZERO); - KX_MACRO_addTypesToDict(d, BL_ONE, GL_ONE); - KX_MACRO_addTypesToDict(d, BL_SRC_COLOR, GL_SRC_COLOR); - KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR); - KX_MACRO_addTypesToDict(d, BL_DST_COLOR, GL_DST_COLOR); - KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_DST_COLOR); - KX_MACRO_addTypesToDict(d, BL_SRC_ALPHA, GL_SRC_ALPHA); - KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - KX_MACRO_addTypesToDict(d, BL_DST_ALPHA, GL_DST_ALPHA); - KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA); - KX_MACRO_addTypesToDict(d, BL_SRC_ALPHA_SATURATE, GL_SRC_ALPHA_SATURATE); - - - /* 8. UniformTypes */ - KX_MACRO_addTypesToDict(d, SHD_TANGENT, BL_Shader::SHD_TANGENT); - KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX, BL_Shader::MODELVIEWMATRIX); - KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_TRANSPOSE, BL_Shader::MODELVIEWMATRIX_TRANSPOSE); - KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_INVERSE, BL_Shader::MODELVIEWMATRIX_INVERSE); - KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_INVERSETRANSPOSE, BL_Shader::MODELVIEWMATRIX_INVERSETRANSPOSE); - KX_MACRO_addTypesToDict(d, MODELMATRIX, BL_Shader::MODELMATRIX); - KX_MACRO_addTypesToDict(d, MODELMATRIX_TRANSPOSE, BL_Shader::MODELMATRIX_TRANSPOSE); - KX_MACRO_addTypesToDict(d, MODELMATRIX_INVERSE, BL_Shader::MODELMATRIX_INVERSE); - KX_MACRO_addTypesToDict(d, MODELMATRIX_INVERSETRANSPOSE, BL_Shader::MODELMATRIX_INVERSETRANSPOSE); - KX_MACRO_addTypesToDict(d, VIEWMATRIX, BL_Shader::VIEWMATRIX); - KX_MACRO_addTypesToDict(d, VIEWMATRIX_TRANSPOSE, BL_Shader::VIEWMATRIX_TRANSPOSE); - KX_MACRO_addTypesToDict(d, VIEWMATRIX_INVERSE, BL_Shader::VIEWMATRIX_INVERSE); - KX_MACRO_addTypesToDict(d, VIEWMATRIX_INVERSETRANSPOSE, BL_Shader::VIEWMATRIX_INVERSETRANSPOSE); - KX_MACRO_addTypesToDict(d, CAM_POS, BL_Shader::CAM_POS); - KX_MACRO_addTypesToDict(d, CONSTANT_TIMER, BL_Shader::CONSTANT_TIMER); - - /* 9. state actuator */ - KX_MACRO_addTypesToDict(d, KX_STATE1, (1<<0)); - KX_MACRO_addTypesToDict(d, KX_STATE2, (1<<1)); - KX_MACRO_addTypesToDict(d, KX_STATE3, (1<<2)); - KX_MACRO_addTypesToDict(d, KX_STATE4, (1<<3)); - KX_MACRO_addTypesToDict(d, KX_STATE5, (1<<4)); - KX_MACRO_addTypesToDict(d, KX_STATE6, (1<<5)); - KX_MACRO_addTypesToDict(d, KX_STATE7, (1<<6)); - KX_MACRO_addTypesToDict(d, KX_STATE8, (1<<7)); - KX_MACRO_addTypesToDict(d, KX_STATE9, (1<<8)); - KX_MACRO_addTypesToDict(d, KX_STATE10, (1<<9)); - KX_MACRO_addTypesToDict(d, KX_STATE11, (1<<10)); - KX_MACRO_addTypesToDict(d, KX_STATE12, (1<<11)); - KX_MACRO_addTypesToDict(d, KX_STATE13, (1<<12)); - KX_MACRO_addTypesToDict(d, KX_STATE14, (1<<13)); - KX_MACRO_addTypesToDict(d, KX_STATE15, (1<<14)); - KX_MACRO_addTypesToDict(d, KX_STATE16, (1<<15)); - KX_MACRO_addTypesToDict(d, KX_STATE17, (1<<16)); - KX_MACRO_addTypesToDict(d, KX_STATE18, (1<<17)); - KX_MACRO_addTypesToDict(d, KX_STATE19, (1<<18)); - KX_MACRO_addTypesToDict(d, KX_STATE20, (1<<19)); - KX_MACRO_addTypesToDict(d, KX_STATE21, (1<<20)); - KX_MACRO_addTypesToDict(d, KX_STATE22, (1<<21)); - KX_MACRO_addTypesToDict(d, KX_STATE23, (1<<22)); - KX_MACRO_addTypesToDict(d, KX_STATE24, (1<<23)); - KX_MACRO_addTypesToDict(d, KX_STATE25, (1<<24)); - KX_MACRO_addTypesToDict(d, KX_STATE26, (1<<25)); - KX_MACRO_addTypesToDict(d, KX_STATE27, (1<<26)); - KX_MACRO_addTypesToDict(d, KX_STATE28, (1<<27)); - KX_MACRO_addTypesToDict(d, KX_STATE29, (1<<28)); - KX_MACRO_addTypesToDict(d, KX_STATE30, (1<<29)); - - /* All Sensors */ - KX_MACRO_addTypesToDict(d, KX_SENSOR_JUST_ACTIVATED, SCA_ISensor::KX_SENSOR_JUST_ACTIVATED); - KX_MACRO_addTypesToDict(d, KX_SENSOR_ACTIVE, SCA_ISensor::KX_SENSOR_ACTIVE); - KX_MACRO_addTypesToDict(d, KX_SENSOR_JUST_DEACTIVATED, SCA_ISensor::KX_SENSOR_JUST_DEACTIVATED); - KX_MACRO_addTypesToDict(d, KX_SENSOR_INACTIVE, SCA_ISensor::KX_SENSOR_INACTIVE); - - /* Radar Sensor */ - KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_POS_X, KX_RadarSensor::KX_RADAR_AXIS_POS_X); - KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_POS_Y, KX_RadarSensor::KX_RADAR_AXIS_POS_Y); - KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_POS_Z, KX_RadarSensor::KX_RADAR_AXIS_POS_Z); - KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_NEG_X, KX_RadarSensor::KX_RADAR_AXIS_NEG_X); - KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_NEG_Y, KX_RadarSensor::KX_RADAR_AXIS_NEG_Y); - KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_NEG_Z, KX_RadarSensor::KX_RADAR_AXIS_NEG_Z); - - /* Ray Sensor */ - KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_POS_X, KX_RaySensor::KX_RAY_AXIS_POS_X); - KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_POS_Y, KX_RaySensor::KX_RAY_AXIS_POS_Y); - KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_POS_Z, KX_RaySensor::KX_RAY_AXIS_POS_Z); - KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_NEG_X, KX_RaySensor::KX_RAY_AXIS_NEG_X); - KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_NEG_Y, KX_RaySensor::KX_RAY_AXIS_NEG_Y); - KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_NEG_Z, KX_RaySensor::KX_RAY_AXIS_NEG_Z); - - /* TrackTo Actuator */ - KX_MACRO_addTypesToDict(d, KX_TRACK_UPAXIS_POS_X, KX_TrackToActuator::KX_TRACK_UPAXIS_POS_X); - KX_MACRO_addTypesToDict(d, KX_TRACK_UPAXIS_POS_Y, KX_TrackToActuator::KX_TRACK_UPAXIS_POS_Y); - KX_MACRO_addTypesToDict(d, KX_TRACK_UPAXIS_POS_Z, KX_TrackToActuator::KX_TRACK_UPAXIS_POS_Z); - KX_MACRO_addTypesToDict(d, KX_TRACK_TRAXIS_POS_X, KX_TrackToActuator::KX_TRACK_TRAXIS_POS_X); - KX_MACRO_addTypesToDict(d, KX_TRACK_TRAXIS_POS_Y, KX_TrackToActuator::KX_TRACK_TRAXIS_POS_Y); - KX_MACRO_addTypesToDict(d, KX_TRACK_TRAXIS_POS_Z, KX_TrackToActuator::KX_TRACK_TRAXIS_POS_Z); - KX_MACRO_addTypesToDict(d, KX_TRACK_TRAXIS_NEG_X, KX_TrackToActuator::KX_TRACK_TRAXIS_NEG_X); - KX_MACRO_addTypesToDict(d, KX_TRACK_TRAXIS_NEG_Y, KX_TrackToActuator::KX_TRACK_TRAXIS_NEG_Y); - KX_MACRO_addTypesToDict(d, KX_TRACK_TRAXIS_NEG_Z, KX_TrackToActuator::KX_TRACK_TRAXIS_NEG_Z); - - /* Dynamic actuator */ - KX_MACRO_addTypesToDict(d, KX_DYN_RESTORE_DYNAMICS, KX_SCA_DynamicActuator::KX_DYN_RESTORE_DYNAMICS); - KX_MACRO_addTypesToDict(d, KX_DYN_DISABLE_DYNAMICS, KX_SCA_DynamicActuator::KX_DYN_DISABLE_DYNAMICS); - KX_MACRO_addTypesToDict(d, KX_DYN_ENABLE_RIGID_BODY, KX_SCA_DynamicActuator::KX_DYN_ENABLE_RIGID_BODY); - KX_MACRO_addTypesToDict(d, KX_DYN_DISABLE_RIGID_BODY, KX_SCA_DynamicActuator::KX_DYN_DISABLE_RIGID_BODY); - KX_MACRO_addTypesToDict(d, KX_DYN_SET_MASS, KX_SCA_DynamicActuator::KX_DYN_SET_MASS); - - /* Input & Mouse Sensor */ - KX_MACRO_addTypesToDict(d, KX_INPUT_NONE, SCA_InputEvent::KX_NO_INPUTSTATUS); - KX_MACRO_addTypesToDict(d, KX_INPUT_JUST_ACTIVATED, SCA_InputEvent::KX_JUSTACTIVATED); - KX_MACRO_addTypesToDict(d, KX_INPUT_ACTIVE, SCA_InputEvent::KX_ACTIVE); - KX_MACRO_addTypesToDict(d, KX_INPUT_JUST_RELEASED, SCA_InputEvent::KX_JUSTRELEASED); - - KX_MACRO_addTypesToDict(d, KX_MOUSE_BUT_LEFT, SCA_IInputDevice::KX_LEFTMOUSE); - KX_MACRO_addTypesToDict(d, KX_MOUSE_BUT_MIDDLE, SCA_IInputDevice::KX_MIDDLEMOUSE); - KX_MACRO_addTypesToDict(d, KX_MOUSE_BUT_RIGHT, SCA_IInputDevice::KX_RIGHTMOUSE); - - /* 2D Filter Actuator */ - KX_MACRO_addTypesToDict(d, RAS_2DFILTER_ENABLED, RAS_2DFilterManager::RAS_2DFILTER_ENABLED); - KX_MACRO_addTypesToDict(d, RAS_2DFILTER_DISABLED, RAS_2DFilterManager::RAS_2DFILTER_DISABLED); - KX_MACRO_addTypesToDict(d, RAS_2DFILTER_NOFILTER, RAS_2DFilterManager::RAS_2DFILTER_NOFILTER); - KX_MACRO_addTypesToDict(d, RAS_2DFILTER_MOTIONBLUR, RAS_2DFilterManager::RAS_2DFILTER_MOTIONBLUR); - KX_MACRO_addTypesToDict(d, RAS_2DFILTER_BLUR, RAS_2DFilterManager::RAS_2DFILTER_BLUR); - KX_MACRO_addTypesToDict(d, RAS_2DFILTER_SHARPEN, RAS_2DFilterManager::RAS_2DFILTER_SHARPEN); - KX_MACRO_addTypesToDict(d, RAS_2DFILTER_DILATION, RAS_2DFilterManager::RAS_2DFILTER_DILATION); - KX_MACRO_addTypesToDict(d, RAS_2DFILTER_EROSION, RAS_2DFilterManager::RAS_2DFILTER_EROSION); - KX_MACRO_addTypesToDict(d, RAS_2DFILTER_LAPLACIAN, RAS_2DFilterManager::RAS_2DFILTER_LAPLACIAN); - KX_MACRO_addTypesToDict(d, RAS_2DFILTER_SOBEL, RAS_2DFilterManager::RAS_2DFILTER_SOBEL); - KX_MACRO_addTypesToDict(d, RAS_2DFILTER_PREWITT, RAS_2DFilterManager::RAS_2DFILTER_PREWITT); - KX_MACRO_addTypesToDict(d, RAS_2DFILTER_GRAYSCALE, RAS_2DFilterManager::RAS_2DFILTER_GRAYSCALE); - KX_MACRO_addTypesToDict(d, RAS_2DFILTER_SEPIA, RAS_2DFilterManager::RAS_2DFILTER_SEPIA); - KX_MACRO_addTypesToDict(d, RAS_2DFILTER_INVERT, RAS_2DFilterManager::RAS_2DFILTER_INVERT); - KX_MACRO_addTypesToDict(d, RAS_2DFILTER_CUSTOMFILTER, RAS_2DFilterManager::RAS_2DFILTER_CUSTOMFILTER); - - /* Sound Actuator */ - KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYSTOP, KX_SoundActuator::KX_SOUNDACT_PLAYSTOP); - KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYEND, KX_SoundActuator::KX_SOUNDACT_PLAYEND); - KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPSTOP, KX_SoundActuator::KX_SOUNDACT_LOOPSTOP); - KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPEND, KX_SoundActuator:: KX_SOUNDACT_LOOPEND); - KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL, KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL); - KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP, KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP); - - /* State Actuator */ - KX_MACRO_addTypesToDict(d, KX_STATE_OP_CPY, KX_StateActuator::OP_CPY); - KX_MACRO_addTypesToDict(d, KX_STATE_OP_SET, KX_StateActuator::OP_SET); - KX_MACRO_addTypesToDict(d, KX_STATE_OP_CLR, KX_StateActuator::OP_CLR); - KX_MACRO_addTypesToDict(d, KX_STATE_OP_NEG, KX_StateActuator::OP_NEG); - - /* Game Actuator Modes */ - KX_MACRO_addTypesToDict(d, KX_GAME_LOAD, KX_GameActuator::KX_GAME_LOAD); - KX_MACRO_addTypesToDict(d, KX_GAME_START, KX_GameActuator::KX_GAME_START); - KX_MACRO_addTypesToDict(d, KX_GAME_RESTART, KX_GameActuator::KX_GAME_RESTART); - KX_MACRO_addTypesToDict(d, KX_GAME_QUIT, KX_GameActuator::KX_GAME_QUIT); - KX_MACRO_addTypesToDict(d, KX_GAME_SAVECFG, KX_GameActuator::KX_GAME_SAVECFG); - KX_MACRO_addTypesToDict(d, KX_GAME_LOADCFG, KX_GameActuator::KX_GAME_LOADCFG); - KX_MACRO_addTypesToDict(d, KX_GAME_SCREENSHOT, KX_GameActuator::KX_GAME_SCREENSHOT); - - /* Scene Actuator Modes */ - KX_MACRO_addTypesToDict(d, KX_SCENE_RESTART, KX_SceneActuator::KX_SCENE_RESTART); - KX_MACRO_addTypesToDict(d, KX_SCENE_SET_SCENE, KX_SceneActuator::KX_SCENE_SET_SCENE); - KX_MACRO_addTypesToDict(d, KX_SCENE_SET_CAMERA, KX_SceneActuator::KX_SCENE_SET_CAMERA); - KX_MACRO_addTypesToDict(d, KX_SCENE_ADD_FRONT_SCENE, KX_SceneActuator::KX_SCENE_ADD_FRONT_SCENE); - KX_MACRO_addTypesToDict(d, KX_SCENE_ADD_BACK_SCENE, KX_SceneActuator::KX_SCENE_ADD_BACK_SCENE); - KX_MACRO_addTypesToDict(d, KX_SCENE_REMOVE_SCENE, KX_SceneActuator::KX_SCENE_REMOVE_SCENE); - KX_MACRO_addTypesToDict(d, KX_SCENE_SUSPEND, KX_SceneActuator::KX_SCENE_SUSPEND); - KX_MACRO_addTypesToDict(d, KX_SCENE_RESUME, KX_SceneActuator::KX_SCENE_RESUME); - - /* Parent Actuator Modes */ - KX_MACRO_addTypesToDict(d, KX_PARENT_SET, KX_ParentActuator::KX_PARENT_SET); - KX_MACRO_addTypesToDict(d, KX_PARENT_REMOVE, KX_ParentActuator::KX_PARENT_REMOVE); - - /* BL_ArmatureConstraint type */ - KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_TRACKTO, CONSTRAINT_TYPE_TRACKTO); - KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_KINEMATIC, CONSTRAINT_TYPE_KINEMATIC); - KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_ROTLIKE, CONSTRAINT_TYPE_ROTLIKE); - KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_LOCLIKE, CONSTRAINT_TYPE_LOCLIKE); - KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_MINMAX, CONSTRAINT_TYPE_MINMAX); - KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_SIZELIKE, CONSTRAINT_TYPE_SIZELIKE); - KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_LOCKTRACK, CONSTRAINT_TYPE_LOCKTRACK); - KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_STRETCHTO, CONSTRAINT_TYPE_STRETCHTO); - KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_CLAMPTO, CONSTRAINT_TYPE_CLAMPTO); - KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_TRANSFORM, CONSTRAINT_TYPE_TRANSFORM); - KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_DISTLIMIT, CONSTRAINT_TYPE_DISTLIMIT); - /* BL_ArmatureConstraint ik_type */ - KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_COPYPOSE, CONSTRAINT_IK_COPYPOSE); - KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_DISTANCE, CONSTRAINT_IK_DISTANCE); - /* BL_ArmatureConstraint ik_mode */ - KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_MODE_INSIDE, LIMITDIST_INSIDE); - KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_MODE_OUTSIDE, LIMITDIST_OUTSIDE); - KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_MODE_ONSURFACE, LIMITDIST_ONSURFACE); - /* BL_ArmatureConstraint ik_flag */ - KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_FLAG_TIP, CONSTRAINT_IK_TIP); - KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_FLAG_ROT, CONSTRAINT_IK_ROT); - KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_FLAG_STRETCH, CONSTRAINT_IK_STRETCH); - KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_FLAG_POS, CONSTRAINT_IK_POS); - /* KX_ArmatureSensor type */ - KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_STATE_CHANGED, SENS_ARM_STATE_CHANGED); - KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_LIN_ERROR_BELOW, SENS_ARM_LIN_ERROR_BELOW); - KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_LIN_ERROR_ABOVE, SENS_ARM_LIN_ERROR_ABOVE); - KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_ROT_ERROR_BELOW, SENS_ARM_ROT_ERROR_BELOW); - KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_ROT_ERROR_ABOVE, SENS_ARM_ROT_ERROR_ABOVE); - - /* BL_ArmatureActuator type */ - KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_RUN, ACT_ARM_RUN); - KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_ENABLE, ACT_ARM_ENABLE); - KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_DISABLE, ACT_ARM_DISABLE); - KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_SETTARGET, ACT_ARM_SETTARGET); - KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_SETWEIGHT, ACT_ARM_SETWEIGHT); - KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_SETINFLUENCE, ACT_ARM_SETINFLUENCE); - - /* BL_Armature Channel rotation_mode */ - KX_MACRO_addTypesToDict(d, ROT_MODE_QUAT, ROT_MODE_QUAT); - KX_MACRO_addTypesToDict(d, ROT_MODE_XYZ, ROT_MODE_XYZ); - KX_MACRO_addTypesToDict(d, ROT_MODE_XZY, ROT_MODE_XZY); - KX_MACRO_addTypesToDict(d, ROT_MODE_YXZ, ROT_MODE_YXZ); - KX_MACRO_addTypesToDict(d, ROT_MODE_YZX, ROT_MODE_YZX); - KX_MACRO_addTypesToDict(d, ROT_MODE_ZXY, ROT_MODE_ZXY); - KX_MACRO_addTypesToDict(d, ROT_MODE_ZYX, ROT_MODE_ZYX); - - /* Steering actuator */ - KX_MACRO_addTypesToDict(d, KX_STEERING_SEEK, KX_SteeringActuator::KX_STEERING_SEEK); - KX_MACRO_addTypesToDict(d, KX_STEERING_FLEE, KX_SteeringActuator::KX_STEERING_FLEE); - KX_MACRO_addTypesToDict(d, KX_STEERING_PATHFOLLOWING, KX_SteeringActuator::KX_STEERING_PATHFOLLOWING); - - /* KX_NavMeshObject render mode */ - KX_MACRO_addTypesToDict(d, RM_WALLS, KX_NavMeshObject::RM_WALLS); - KX_MACRO_addTypesToDict(d, RM_POLYS, KX_NavMeshObject::RM_POLYS); - KX_MACRO_addTypesToDict(d, RM_TRIS, KX_NavMeshObject::RM_TRIS); - - /* BL_Action play modes */ - KX_MACRO_addTypesToDict(d, KX_ACTION_MODE_PLAY, BL_Action::ACT_MODE_PLAY); - KX_MACRO_addTypesToDict(d, KX_ACTION_MODE_LOOP, BL_Action::ACT_MODE_LOOP); - KX_MACRO_addTypesToDict(d, KX_ACTION_MODE_PING_PONG, BL_Action::ACT_MODE_PING_PONG); - - /* BL_Action blend modes */ - KX_MACRO_addTypesToDict(d, KX_ACTION_BLEND_BLEND, BL_Action::ACT_BLEND_BLEND); - KX_MACRO_addTypesToDict(d, KX_ACTION_BLEND_ADD, BL_Action::ACT_BLEND_ADD); - - /* Mouse Actuator object axis*/ - KX_MACRO_addTypesToDict(d, KX_ACT_MOUSE_OBJECT_AXIS_X, KX_MouseActuator::KX_ACT_MOUSE_OBJECT_AXIS_X); - KX_MACRO_addTypesToDict(d, KX_ACT_MOUSE_OBJECT_AXIS_Y, KX_MouseActuator::KX_ACT_MOUSE_OBJECT_AXIS_Y); - KX_MACRO_addTypesToDict(d, KX_ACT_MOUSE_OBJECT_AXIS_Z, KX_MouseActuator::KX_ACT_MOUSE_OBJECT_AXIS_Z); - - - // Check for errors - if (PyErr_Occurred()) - { - Py_FatalError("can't initialize module bge.logic"); - } - - return m; -} - -/** - * Explanation of - * - * - backupPySysObjects() : stores sys.path in #gp_sys_backup - * - initPySysObjects(main) : initializes the blendfile and library paths - * - restorePySysObjects() : restores sys.path from #gp_sys_backup - * - * These exist so the current blend dir "//" can always be used to import modules from. - * the reason we need a few functions for this is that python is not only used by the game engine - * so we cant just add to sys.path all the time, it would leave pythons state in a mess. - * It would also be incorrect since loading blend files for new levels etc would always add to sys.path - * - * To play nice with blenders python, the sys.path is backed up and the current blendfile along - * with all its lib paths are added to the sys path. - * When loading a new blendfile, the original sys.path is restored and the new paths are added over the top. - */ - -/** - * So we can have external modules mixed with our blend files. - */ -static void backupPySysObjects(void) -{ - PyObject *sys_path = PySys_GetObject("path"); - PyObject *sys_meta_path = PySys_GetObject("meta_path"); - PyObject *sys_mods = PySys_GetObject("modules"); - - /* paths */ - Py_XDECREF(gp_sys_backup.path); /* just in case its set */ - gp_sys_backup.path = PyList_GetSlice(sys_path, 0, INT_MAX); /* copy the list */ - - /* meta_paths */ - Py_XDECREF(gp_sys_backup.meta_path); /* just in case its set */ - gp_sys_backup.meta_path = PyList_GetSlice(sys_meta_path, 0, INT_MAX); /* copy the list */ - - /* modules */ - Py_XDECREF(gp_sys_backup.modules); /* just in case its set */ - gp_sys_backup.modules = PyDict_Copy(sys_mods); /* copy the dict */ - -} - -/* for initPySysObjects only, - * takes a blend path and adds a scripts dir from it - * - * "/home/me/foo.blend" -> "/home/me/scripts" - */ -static void initPySysObjects__append(PyObject *sys_path, const char *filename) -{ - PyObject *item; - char expanded[FILE_MAX]; - - BLI_split_dir_part(filename, expanded, sizeof(expanded)); /* get the dir part of filename only */ - BLI_path_abs(expanded, gp_GamePythonPath); /* filename from lib->filename is (always?) absolute, so this may not be needed but it wont hurt */ - BLI_cleanup_file(gp_GamePythonPath, expanded); /* Don't use BLI_cleanup_dir because it adds a slash - BREAKS WIN32 ONLY */ - item = PyC_UnicodeFromByte(expanded); - -// printf("SysPath - '%s', '%s', '%s'\n", expanded, filename, gp_GamePythonPath); - - if (PySequence_Index(sys_path, item) == -1) { - PyErr_Clear(); /* PySequence_Index sets a ValueError */ - PyList_Insert(sys_path, 0, item); - } - - Py_DECREF(item); -} -static void initPySysObjects(Main *maggie) -{ - PyObject *sys_path = PySys_GetObject("path"); - PyObject *sys_meta_path = PySys_GetObject("meta_path"); - - if (gp_sys_backup.path == NULL) { - /* backup */ - backupPySysObjects(); - } - else { - /* get the original sys path when the BGE started */ - PyList_SetSlice(sys_path, 0, INT_MAX, gp_sys_backup.path); - PyList_SetSlice(sys_meta_path, 0, INT_MAX, gp_sys_backup.meta_path); - } - - Library *lib= (Library *)maggie->library.first; - - while (lib) { - /* lib->name wont work in some cases (on win32), - * even when expanding with gp_GamePythonPath, using lib->filename is less trouble */ - initPySysObjects__append(sys_path, lib->filepath); - lib= (Library *)lib->id.next; - } - - initPySysObjects__append(sys_path, gp_GamePythonPath); - -// fprintf(stderr, "\nNew Path: %d ", PyList_GET_SIZE(sys_path)); -// PyObject_Print(sys_path, stderr, 0); -} - -static void restorePySysObjects(void) -{ - if (gp_sys_backup.path == NULL) { - return; - } - - /* will never fail */ - PyObject *sys_path = PySys_GetObject("path"); - PyObject *sys_meta_path = PySys_GetObject("meta_path"); - PyObject *sys_mods = PySys_GetObject("modules"); - - /* paths */ - PyList_SetSlice(sys_path, 0, INT_MAX, gp_sys_backup.path); - Py_DECREF(gp_sys_backup.path); - gp_sys_backup.path = NULL; - - /* meta_path */ - PyList_SetSlice(sys_meta_path, 0, INT_MAX, gp_sys_backup.meta_path); - Py_DECREF(gp_sys_backup.meta_path); - gp_sys_backup.meta_path = NULL; - - /* modules */ - PyDict_Clear(sys_mods); - PyDict_Update(sys_mods, gp_sys_backup.modules); - Py_DECREF(gp_sys_backup.modules); - gp_sys_backup.modules = NULL; - - -// fprintf(stderr, "\nRestore Path: %d ", PyList_GET_SIZE(sys_path)); -// PyObject_Print(sys_path, stderr, 0); -} - -void addImportMain(struct Main *maggie) -{ - bpy_import_main_extra_add(maggie); -} - -void removeImportMain(struct Main *maggie) -{ - bpy_import_main_extra_remove(maggie); -} - - -PyDoc_STRVAR(BGE_module_documentation, - "This module contains submodules for the Blender Game Engine.\n" -); - -static struct PyModuleDef BGE_module_def = { - PyModuleDef_HEAD_INIT, - "bge", /* m_name */ - BGE_module_documentation, /* m_doc */ - 0, /* m_size */ - NULL, /* m_methods */ - NULL, /* m_reload */ - NULL, /* m_traverse */ - NULL, /* m_clear */ - NULL, /* m_free */ -}; - -PyMODINIT_FUNC initBGE(void) -{ - PyObject *mod; - PyObject *submodule; - PyObject *sys_modules = PyThreadState_GET()->interp->modules; - const char *mod_full; - - mod = PyModule_Create(&BGE_module_def); - - /* skip "bge." */ -#define SUBMOD (mod_full + 4) - - mod_full = "bge.app"; - PyModule_AddObject(mod, SUBMOD, (submodule = initApplicationPythonBinding())); - PyDict_SetItemString(sys_modules, mod_full, submodule); - Py_INCREF(submodule); - - mod_full = "bge.constraints"; - PyModule_AddObject(mod, SUBMOD, (submodule = initConstraintPythonBinding())); - PyDict_SetItemString(sys_modules, mod_full, submodule); - Py_INCREF(submodule); - - mod_full = "bge.events"; - PyModule_AddObject(mod, SUBMOD, (submodule = initGameKeysPythonBinding())); - PyDict_SetItemString(sys_modules, mod_full, submodule); - Py_INCREF(submodule); - - mod_full = "bge.logic"; - PyModule_AddObject(mod, SUBMOD, (submodule = initGameLogicPythonBinding())); - PyDict_SetItemString(sys_modules, mod_full, submodule); - Py_INCREF(submodule); - - mod_full = "bge.render"; - PyModule_AddObject(mod, SUBMOD, (submodule = initRasterizerPythonBinding())); - PyDict_SetItemString(sys_modules, mod_full, submodule); - Py_INCREF(submodule); - - mod_full = "bge.texture"; - PyModule_AddObject(mod, SUBMOD, (submodule = initVideoTexturePythonBinding())); - PyDict_SetItemString(sys_modules, mod_full, submodule); - Py_INCREF(submodule); - - mod_full = "bge.types"; - PyModule_AddObject(mod, SUBMOD, (submodule = initGameTypesPythonBinding())); - PyDict_SetItemString(sys_modules, mod_full, submodule); - Py_INCREF(submodule); - -#undef SUBMOD - - return mod; -} - - -/* minimal required blender modules to run blenderplayer */ -static struct _inittab bge_internal_modules[] = { - {"mathutils", PyInit_mathutils}, - {"bgl", BPyInit_bgl}, - {"blf", BPyInit_blf}, - {"aud", AUD_initPython}, - {NULL, NULL} -}; - -/** - * Python is not initialized. - * see bpy_interface.c's BPY_python_start() which shares the same functionality in blender. - */ -PyObject *initGamePlayerPythonScripting(Main *maggie, int argc, char** argv) -{ - /* Yet another gotcha in the py api - * Cant run PySys_SetArgv more than once because this adds the - * binary dir to the sys.path each time. - * Id have thought python being totally restarted would make this ok but - * somehow it remembers the sys.path - Campbell - */ - static bool first_time = true; - const char * const py_path_bundle = BKE_appdir_folder_id(BLENDER_SYSTEM_PYTHON, NULL); - - /* not essential but nice to set our name */ - static wchar_t program_path_wchar[FILE_MAX]; /* python holds a reference */ - BLI_strncpy_wchar_from_utf8(program_path_wchar, BKE_appdir_program_path(), ARRAY_SIZE(program_path_wchar)); - Py_SetProgramName(program_path_wchar); - - /* Update, Py3.3 resolves attempting to parse non-existing header */ -#if 0 - /* Python 3.2 now looks for '2.xx/python/include/python3.2d/pyconfig.h' to - * parse from the 'sysconfig' module which is used by 'site', - * so for now disable site. alternatively we could copy the file. */ - if (py_path_bundle != NULL) { - Py_NoSiteFlag = 1; /* inhibits the automatic importing of 'site' */ - } -#endif - - Py_FrozenFlag = 1; - - /* must run before python initializes */ - PyImport_ExtendInittab(bge_internal_modules); - - /* find local python installation */ - PyC_SetHomePath(py_path_bundle); - - Py_Initialize(); - - if (argv && first_time) { /* browser plugins don't currently set this */ - // Until python support ascii again, we use our own. - // PySys_SetArgv(argc, argv); - int i; - PyObject *py_argv= PyList_New(argc); - - for (i=0; iGetCanvas(); - gp_Rasterizer = ketsjiengine->GetRasterizer(); - gp_KetsjiEngine = ketsjiengine; - gp_KetsjiScene = startscene; - - if (argv) /* player only */ - dictionaryobject= initGamePlayerPythonScripting(blenderdata, argc, argv); - else - dictionaryobject= initGamePythonScripting(blenderdata); - - ketsjiengine->SetPyNamespace(dictionaryobject); - - modules = PyImport_GetModuleDict(); - - *gameLogic = PyDict_GetItemString(modules, "GameLogic"); - /* is set in initGameLogicPythonBinding so only set here if we want it to persist between scenes */ - if (pyGlobalDict) - PyDict_SetItemString(PyModule_GetDict(*gameLogic), "globalDict", pyGlobalDict); // Same as importing the module. - - *gameLogic_keys = PyDict_Keys(PyModule_GetDict(*gameLogic)); -} - -static struct PyModuleDef Rasterizer_module_def = { - PyModuleDef_HEAD_INIT, - "Rasterizer", /* m_name */ - Rasterizer_module_documentation, /* m_doc */ - 0, /* m_size */ - rasterizer_methods, /* m_methods */ - 0, /* m_reload */ - 0, /* m_traverse */ - 0, /* m_clear */ - 0, /* m_free */ -}; - -PyMODINIT_FUNC initRasterizerPythonBinding() -{ - PyObject *m; - PyObject *d; - - PyType_Ready(&PyRASOffScreen_Type); - - m = PyModule_Create(&Rasterizer_module_def); - PyDict_SetItemString(PySys_GetObject("modules"), Rasterizer_module_def.m_name, m); - - - // Add some symbolic constants to the module - d = PyModule_GetDict(m); - ErrorObject = PyUnicode_FromString("Rasterizer.error"); - PyDict_SetItemString(d, "error", ErrorObject); - Py_DECREF(ErrorObject); - - /* needed for get/setMaterialType */ - KX_MACRO_addTypesToDict(d, KX_BLENDER_MULTITEX_MATERIAL, KX_BLENDER_MULTITEX_MATERIAL); - KX_MACRO_addTypesToDict(d, KX_BLENDER_GLSL_MATERIAL, KX_BLENDER_GLSL_MATERIAL); - - KX_MACRO_addTypesToDict(d, RAS_MIPMAP_NONE, RAS_IRasterizer::RAS_MIPMAP_NONE); - KX_MACRO_addTypesToDict(d, RAS_MIPMAP_NEAREST, RAS_IRasterizer::RAS_MIPMAP_NEAREST); - KX_MACRO_addTypesToDict(d, RAS_MIPMAP_LINEAR, RAS_IRasterizer::RAS_MIPMAP_LINEAR); - - /* for get/setVsync */ - KX_MACRO_addTypesToDict(d, VSYNC_OFF, VSYNC_OFF); - KX_MACRO_addTypesToDict(d, VSYNC_ON, VSYNC_ON); - KX_MACRO_addTypesToDict(d, VSYNC_ADAPTIVE, VSYNC_ADAPTIVE); - - /* stereoscopy */ - KX_MACRO_addTypesToDict(d, LEFT_EYE, RAS_IRasterizer::RAS_STEREO_LEFTEYE); - KX_MACRO_addTypesToDict(d, RIGHT_EYE, RAS_IRasterizer::RAS_STEREO_RIGHTEYE); - - /* offscreen render */ - KX_MACRO_addTypesToDict(d, RAS_OFS_RENDER_BUFFER, RAS_IOffScreen::RAS_OFS_RENDER_BUFFER); - KX_MACRO_addTypesToDict(d, RAS_OFS_RENDER_TEXTURE, RAS_IOffScreen::RAS_OFS_RENDER_TEXTURE); - - - // XXXX Add constants here - - // Check for errors - if (PyErr_Occurred()) - { - Py_FatalError("can't initialize module Rasterizer"); - } - - return m; -} - - - -/* ------------------------------------------------------------------------- */ -/* GameKeys: symbolic constants for key mapping */ -/* ------------------------------------------------------------------------- */ - -PyDoc_STRVAR(GameKeys_module_documentation, -"This modules provides defines for key-codes" -); - -PyDoc_STRVAR(gPyEventToString_doc, -"EventToString(event)\n" -"Take a valid event from the GameKeys module or Keyboard Sensor and return a name" -); - -static PyObject *gPyEventToString(PyObject *, PyObject *value) -{ - PyObject *mod, *dict, *key, *val, *ret = NULL; - Py_ssize_t pos = 0; - - mod = PyImport_ImportModule( "GameKeys" ); - if (!mod) - return NULL; - - dict = PyModule_GetDict(mod); - - while (PyDict_Next(dict, &pos, &key, &val)) { - if (PyObject_RichCompareBool(value, val, Py_EQ)) { - ret = key; - break; - } - } - - PyErr_Clear(); // in case there was an error clearing - Py_DECREF(mod); - if (!ret) PyErr_SetString(PyExc_ValueError, "GameKeys.EventToString(int): expected a valid int keyboard event"); - else Py_INCREF(ret); - - return ret; -} - - -PyDoc_STRVAR(gPyEventToCharacter_doc, -"EventToCharacter(event, is_shift)\n" -"Take a valid event from the GameKeys module or Keyboard Sensor and return a character" -); - -static PyObject *gPyEventToCharacter(PyObject *, PyObject *args) -{ - int event, shift; - if (!PyArg_ParseTuple(args,"ii:EventToCharacter", &event, &shift)) - return NULL; - - if (IsPrintable(event)) { - char ch[2] = {'\0', '\0'}; - ch[0] = ToCharacter(event, (bool)shift); - return PyUnicode_FromString(ch); - } - else { - return PyUnicode_FromString(""); - } -} - - -static struct PyMethodDef gamekeys_methods[] = { - {"EventToCharacter", (PyCFunction)gPyEventToCharacter, METH_VARARGS, (const char *)gPyEventToCharacter_doc}, - {"EventToString", (PyCFunction)gPyEventToString, METH_O, (const char *)gPyEventToString_doc}, - { NULL, (PyCFunction) NULL, 0, NULL } -}; - -static struct PyModuleDef GameKeys_module_def = { - PyModuleDef_HEAD_INIT, - "GameKeys", /* m_name */ - GameKeys_module_documentation, /* m_doc */ - 0, /* m_size */ - gamekeys_methods, /* m_methods */ - 0, /* m_reload */ - 0, /* m_traverse */ - 0, /* m_clear */ - 0, /* m_free */ -}; - -PyMODINIT_FUNC initGameKeysPythonBinding() -{ - PyObject *m; - PyObject *d; - - m = PyModule_Create(&GameKeys_module_def); - PyDict_SetItemString(PySys_GetObject("modules"), GameKeys_module_def.m_name, m); - - // Add some symbolic constants to the module - d = PyModule_GetDict(m); - - // XXXX Add constants here - - KX_MACRO_addTypesToDict(d, AKEY, SCA_IInputDevice::KX_AKEY); - KX_MACRO_addTypesToDict(d, BKEY, SCA_IInputDevice::KX_BKEY); - KX_MACRO_addTypesToDict(d, CKEY, SCA_IInputDevice::KX_CKEY); - KX_MACRO_addTypesToDict(d, DKEY, SCA_IInputDevice::KX_DKEY); - KX_MACRO_addTypesToDict(d, EKEY, SCA_IInputDevice::KX_EKEY); - KX_MACRO_addTypesToDict(d, FKEY, SCA_IInputDevice::KX_FKEY); - KX_MACRO_addTypesToDict(d, GKEY, SCA_IInputDevice::KX_GKEY); - KX_MACRO_addTypesToDict(d, HKEY, SCA_IInputDevice::KX_HKEY); - KX_MACRO_addTypesToDict(d, IKEY, SCA_IInputDevice::KX_IKEY); - KX_MACRO_addTypesToDict(d, JKEY, SCA_IInputDevice::KX_JKEY); - KX_MACRO_addTypesToDict(d, KKEY, SCA_IInputDevice::KX_KKEY); - KX_MACRO_addTypesToDict(d, LKEY, SCA_IInputDevice::KX_LKEY); - KX_MACRO_addTypesToDict(d, MKEY, SCA_IInputDevice::KX_MKEY); - KX_MACRO_addTypesToDict(d, NKEY, SCA_IInputDevice::KX_NKEY); - KX_MACRO_addTypesToDict(d, OKEY, SCA_IInputDevice::KX_OKEY); - KX_MACRO_addTypesToDict(d, PKEY, SCA_IInputDevice::KX_PKEY); - KX_MACRO_addTypesToDict(d, QKEY, SCA_IInputDevice::KX_QKEY); - KX_MACRO_addTypesToDict(d, RKEY, SCA_IInputDevice::KX_RKEY); - KX_MACRO_addTypesToDict(d, SKEY, SCA_IInputDevice::KX_SKEY); - KX_MACRO_addTypesToDict(d, TKEY, SCA_IInputDevice::KX_TKEY); - KX_MACRO_addTypesToDict(d, UKEY, SCA_IInputDevice::KX_UKEY); - KX_MACRO_addTypesToDict(d, VKEY, SCA_IInputDevice::KX_VKEY); - KX_MACRO_addTypesToDict(d, WKEY, SCA_IInputDevice::KX_WKEY); - KX_MACRO_addTypesToDict(d, XKEY, SCA_IInputDevice::KX_XKEY); - KX_MACRO_addTypesToDict(d, YKEY, SCA_IInputDevice::KX_YKEY); - KX_MACRO_addTypesToDict(d, ZKEY, SCA_IInputDevice::KX_ZKEY); - - KX_MACRO_addTypesToDict(d, ZEROKEY, SCA_IInputDevice::KX_ZEROKEY); - KX_MACRO_addTypesToDict(d, ONEKEY, SCA_IInputDevice::KX_ONEKEY); - KX_MACRO_addTypesToDict(d, TWOKEY, SCA_IInputDevice::KX_TWOKEY); - KX_MACRO_addTypesToDict(d, THREEKEY, SCA_IInputDevice::KX_THREEKEY); - KX_MACRO_addTypesToDict(d, FOURKEY, SCA_IInputDevice::KX_FOURKEY); - KX_MACRO_addTypesToDict(d, FIVEKEY, SCA_IInputDevice::KX_FIVEKEY); - KX_MACRO_addTypesToDict(d, SIXKEY, SCA_IInputDevice::KX_SIXKEY); - KX_MACRO_addTypesToDict(d, SEVENKEY, SCA_IInputDevice::KX_SEVENKEY); - KX_MACRO_addTypesToDict(d, EIGHTKEY, SCA_IInputDevice::KX_EIGHTKEY); - KX_MACRO_addTypesToDict(d, NINEKEY, SCA_IInputDevice::KX_NINEKEY); - - KX_MACRO_addTypesToDict(d, CAPSLOCKKEY, SCA_IInputDevice::KX_CAPSLOCKKEY); - - KX_MACRO_addTypesToDict(d, LEFTCTRLKEY, SCA_IInputDevice::KX_LEFTCTRLKEY); - KX_MACRO_addTypesToDict(d, LEFTALTKEY, SCA_IInputDevice::KX_LEFTALTKEY); - KX_MACRO_addTypesToDict(d, RIGHTALTKEY, SCA_IInputDevice::KX_RIGHTALTKEY); - KX_MACRO_addTypesToDict(d, RIGHTCTRLKEY, SCA_IInputDevice::KX_RIGHTCTRLKEY); - KX_MACRO_addTypesToDict(d, RIGHTSHIFTKEY, SCA_IInputDevice::KX_RIGHTSHIFTKEY); - KX_MACRO_addTypesToDict(d, LEFTSHIFTKEY, SCA_IInputDevice::KX_LEFTSHIFTKEY); - - KX_MACRO_addTypesToDict(d, ESCKEY, SCA_IInputDevice::KX_ESCKEY); - KX_MACRO_addTypesToDict(d, TABKEY, SCA_IInputDevice::KX_TABKEY); - KX_MACRO_addTypesToDict(d, RETKEY, SCA_IInputDevice::KX_RETKEY); - KX_MACRO_addTypesToDict(d, ENTERKEY, SCA_IInputDevice::KX_RETKEY); - KX_MACRO_addTypesToDict(d, SPACEKEY, SCA_IInputDevice::KX_SPACEKEY); - KX_MACRO_addTypesToDict(d, LINEFEEDKEY, SCA_IInputDevice::KX_LINEFEEDKEY); - KX_MACRO_addTypesToDict(d, BACKSPACEKEY, SCA_IInputDevice::KX_BACKSPACEKEY); - KX_MACRO_addTypesToDict(d, DELKEY, SCA_IInputDevice::KX_DELKEY); - KX_MACRO_addTypesToDict(d, SEMICOLONKEY, SCA_IInputDevice::KX_SEMICOLONKEY); - KX_MACRO_addTypesToDict(d, PERIODKEY, SCA_IInputDevice::KX_PERIODKEY); - KX_MACRO_addTypesToDict(d, COMMAKEY, SCA_IInputDevice::KX_COMMAKEY); - KX_MACRO_addTypesToDict(d, QUOTEKEY, SCA_IInputDevice::KX_QUOTEKEY); - KX_MACRO_addTypesToDict(d, ACCENTGRAVEKEY, SCA_IInputDevice::KX_ACCENTGRAVEKEY); - KX_MACRO_addTypesToDict(d, MINUSKEY, SCA_IInputDevice::KX_MINUSKEY); - KX_MACRO_addTypesToDict(d, SLASHKEY, SCA_IInputDevice::KX_SLASHKEY); - KX_MACRO_addTypesToDict(d, BACKSLASHKEY, SCA_IInputDevice::KX_BACKSLASHKEY); - KX_MACRO_addTypesToDict(d, EQUALKEY, SCA_IInputDevice::KX_EQUALKEY); - KX_MACRO_addTypesToDict(d, LEFTBRACKETKEY, SCA_IInputDevice::KX_LEFTBRACKETKEY); - KX_MACRO_addTypesToDict(d, RIGHTBRACKETKEY, SCA_IInputDevice::KX_RIGHTBRACKETKEY); - - KX_MACRO_addTypesToDict(d, LEFTARROWKEY, SCA_IInputDevice::KX_LEFTARROWKEY); - KX_MACRO_addTypesToDict(d, DOWNARROWKEY, SCA_IInputDevice::KX_DOWNARROWKEY); - KX_MACRO_addTypesToDict(d, RIGHTARROWKEY, SCA_IInputDevice::KX_RIGHTARROWKEY); - KX_MACRO_addTypesToDict(d, UPARROWKEY, SCA_IInputDevice::KX_UPARROWKEY); - - KX_MACRO_addTypesToDict(d, PAD2 , SCA_IInputDevice::KX_PAD2); - KX_MACRO_addTypesToDict(d, PAD4 , SCA_IInputDevice::KX_PAD4); - KX_MACRO_addTypesToDict(d, PAD6 , SCA_IInputDevice::KX_PAD6); - KX_MACRO_addTypesToDict(d, PAD8 , SCA_IInputDevice::KX_PAD8); - - KX_MACRO_addTypesToDict(d, PAD1 , SCA_IInputDevice::KX_PAD1); - KX_MACRO_addTypesToDict(d, PAD3 , SCA_IInputDevice::KX_PAD3); - KX_MACRO_addTypesToDict(d, PAD5 , SCA_IInputDevice::KX_PAD5); - KX_MACRO_addTypesToDict(d, PAD7 , SCA_IInputDevice::KX_PAD7); - KX_MACRO_addTypesToDict(d, PAD9 , SCA_IInputDevice::KX_PAD9); - - KX_MACRO_addTypesToDict(d, PADPERIOD, SCA_IInputDevice::KX_PADPERIOD); - KX_MACRO_addTypesToDict(d, PADSLASHKEY, SCA_IInputDevice::KX_PADSLASHKEY); - KX_MACRO_addTypesToDict(d, PADASTERKEY, SCA_IInputDevice::KX_PADASTERKEY); - - - KX_MACRO_addTypesToDict(d, PAD0, SCA_IInputDevice::KX_PAD0); - KX_MACRO_addTypesToDict(d, PADMINUS, SCA_IInputDevice::KX_PADMINUS); - KX_MACRO_addTypesToDict(d, PADENTER, SCA_IInputDevice::KX_PADENTER); - KX_MACRO_addTypesToDict(d, PADPLUSKEY, SCA_IInputDevice::KX_PADPLUSKEY); - - - KX_MACRO_addTypesToDict(d, F1KEY, SCA_IInputDevice::KX_F1KEY); - KX_MACRO_addTypesToDict(d, F2KEY, SCA_IInputDevice::KX_F2KEY); - KX_MACRO_addTypesToDict(d, F3KEY, SCA_IInputDevice::KX_F3KEY); - KX_MACRO_addTypesToDict(d, F4KEY, SCA_IInputDevice::KX_F4KEY); - KX_MACRO_addTypesToDict(d, F5KEY, SCA_IInputDevice::KX_F5KEY); - KX_MACRO_addTypesToDict(d, F6KEY, SCA_IInputDevice::KX_F6KEY); - KX_MACRO_addTypesToDict(d, F7KEY, SCA_IInputDevice::KX_F7KEY); - KX_MACRO_addTypesToDict(d, F8KEY, SCA_IInputDevice::KX_F8KEY); - KX_MACRO_addTypesToDict(d, F9KEY, SCA_IInputDevice::KX_F9KEY); - KX_MACRO_addTypesToDict(d, F10KEY, SCA_IInputDevice::KX_F10KEY); - KX_MACRO_addTypesToDict(d, F11KEY, SCA_IInputDevice::KX_F11KEY); - KX_MACRO_addTypesToDict(d, F12KEY, SCA_IInputDevice::KX_F12KEY); - KX_MACRO_addTypesToDict(d, F13KEY, SCA_IInputDevice::KX_F13KEY); - KX_MACRO_addTypesToDict(d, F14KEY, SCA_IInputDevice::KX_F14KEY); - KX_MACRO_addTypesToDict(d, F15KEY, SCA_IInputDevice::KX_F15KEY); - KX_MACRO_addTypesToDict(d, F16KEY, SCA_IInputDevice::KX_F16KEY); - KX_MACRO_addTypesToDict(d, F17KEY, SCA_IInputDevice::KX_F17KEY); - KX_MACRO_addTypesToDict(d, F18KEY, SCA_IInputDevice::KX_F18KEY); - KX_MACRO_addTypesToDict(d, F19KEY, SCA_IInputDevice::KX_F19KEY); - - KX_MACRO_addTypesToDict(d, OSKEY, SCA_IInputDevice::KX_OSKEY); - - KX_MACRO_addTypesToDict(d, PAUSEKEY, SCA_IInputDevice::KX_PAUSEKEY); - KX_MACRO_addTypesToDict(d, INSERTKEY, SCA_IInputDevice::KX_INSERTKEY); - KX_MACRO_addTypesToDict(d, HOMEKEY, SCA_IInputDevice::KX_HOMEKEY); - KX_MACRO_addTypesToDict(d, PAGEUPKEY, SCA_IInputDevice::KX_PAGEUPKEY); - KX_MACRO_addTypesToDict(d, PAGEDOWNKEY, SCA_IInputDevice::KX_PAGEDOWNKEY); - KX_MACRO_addTypesToDict(d, ENDKEY, SCA_IInputDevice::KX_ENDKEY); - - // MOUSE - KX_MACRO_addTypesToDict(d, LEFTMOUSE, SCA_IInputDevice::KX_LEFTMOUSE); - KX_MACRO_addTypesToDict(d, MIDDLEMOUSE, SCA_IInputDevice::KX_MIDDLEMOUSE); - KX_MACRO_addTypesToDict(d, RIGHTMOUSE, SCA_IInputDevice::KX_RIGHTMOUSE); - KX_MACRO_addTypesToDict(d, WHEELUPMOUSE, SCA_IInputDevice::KX_WHEELUPMOUSE); - KX_MACRO_addTypesToDict(d, WHEELDOWNMOUSE, SCA_IInputDevice::KX_WHEELDOWNMOUSE); - KX_MACRO_addTypesToDict(d, MOUSEX, SCA_IInputDevice::KX_MOUSEX); - KX_MACRO_addTypesToDict(d, MOUSEY, SCA_IInputDevice::KX_MOUSEY); - - // Check for errors - if (PyErr_Occurred()) - { - Py_FatalError("can't initialize module GameKeys"); - } - - return m; -} - - - -/* ------------------------------------------------------------------------- */ -/* Application: application values that remain unchanged during runtime */ -/* ------------------------------------------------------------------------- */ - -PyDoc_STRVAR(Application_module_documentation, - "This module contains application values that remain unchanged during runtime." - ); - -static struct PyModuleDef Application_module_def = { - PyModuleDef_HEAD_INIT, - "bge.app", /* m_name */ - Application_module_documentation, /* m_doc */ - 0, /* m_size */ - NULL, /* m_methods */ - 0, /* m_reload */ - 0, /* m_traverse */ - 0, /* m_clear */ - 0, /* m_free */ -}; - -PyMODINIT_FUNC initApplicationPythonBinding() -{ - PyObject *m; - PyObject *d; - - m = PyModule_Create(&Application_module_def); - - // Add some symbolic constants to the module - d = PyModule_GetDict(m); - - PyDict_SetItemString(d, "version", Py_BuildValue("(iii)", - BLENDER_VERSION / 100, BLENDER_VERSION % 100, BLENDER_SUBVERSION)); - PyDict_SetItemString(d, "version_string", PyUnicode_FromFormat("%d.%02d (sub %d)", - BLENDER_VERSION / 100, BLENDER_VERSION % 100, BLENDER_SUBVERSION)); - PyDict_SetItemString(d, "version_char", PyUnicode_FromString( - STRINGIFY(BLENDER_VERSION_CHAR))); - - PyDict_SetItemString(d, "has_texture_ffmpeg", -#ifdef WITH_FFMPEG - Py_True -#else - Py_False -#endif - ); - PyDict_SetItemString(d, "has_joystick", -#ifdef WITH_SDL - Py_True -#else - Py_False -#endif - ); - PyDict_SetItemString(d, "has_physics", -#ifdef WITH_BULLET - Py_True -#else - Py_False -#endif - ); - - // Check for errors - if (PyErr_Occurred()) { - PyErr_Print(); - PyErr_Clear(); - } - - return m; -} - - -// utility function for loading and saving the globalDict -int saveGamePythonConfig( char **marshal_buffer) -{ - int marshal_length = 0; - PyObject *gameLogic = PyImport_ImportModule("GameLogic"); - if (gameLogic) { - PyObject *pyGlobalDict = PyDict_GetItemString(PyModule_GetDict(gameLogic), "globalDict"); // Same as importing the module - if (pyGlobalDict) { -#ifdef Py_MARSHAL_VERSION - PyObject *pyGlobalDictMarshal = PyMarshal_WriteObjectToString( pyGlobalDict, 2); // Py_MARSHAL_VERSION == 2 as of Py2.5 -#else - PyObject *pyGlobalDictMarshal = PyMarshal_WriteObjectToString( pyGlobalDict ); -#endif - if (pyGlobalDictMarshal) { - // for testing only - // PyObject_Print(pyGlobalDictMarshal, stderr, 0); - char *marshal_cstring; - - marshal_cstring = PyBytes_AsString(pyGlobalDictMarshal); // py3 uses byte arrays - marshal_length= PyBytes_Size(pyGlobalDictMarshal); - *marshal_buffer = new char[marshal_length + 1]; - memcpy(*marshal_buffer, marshal_cstring, marshal_length); - Py_DECREF(pyGlobalDictMarshal); - } else { - printf("Error, bge.logic.globalDict could not be marshal'd\n"); - } - } else { - printf("Error, bge.logic.globalDict was removed\n"); - } - Py_DECREF(gameLogic); - } else { - PyErr_Clear(); - printf("Error, bge.logic failed to import bge.logic.globalDict will be lost\n"); - } - return marshal_length; -} - -int loadGamePythonConfig(char *marshal_buffer, int marshal_length) -{ - /* Restore the dict */ - if (marshal_buffer) { - PyObject *gameLogic = PyImport_ImportModule("GameLogic"); - - if (gameLogic) { - PyObject *pyGlobalDict = PyMarshal_ReadObjectFromString(marshal_buffer, marshal_length); - if (pyGlobalDict) { - PyObject *pyGlobalDict_orig = PyDict_GetItemString(PyModule_GetDict(gameLogic), "globalDict"); // Same as importing the module. - if (pyGlobalDict_orig) { - PyDict_Clear(pyGlobalDict_orig); - PyDict_Update(pyGlobalDict_orig, pyGlobalDict); - } else { - /* this should not happen, but cant find the original globalDict, just assign it then */ - PyDict_SetItemString(PyModule_GetDict(gameLogic), "globalDict", pyGlobalDict); // Same as importing the module. - } - Py_DECREF(gameLogic); - Py_DECREF(pyGlobalDict); - return 1; - } else { - Py_DECREF(gameLogic); - PyErr_Clear(); - printf("Error could not marshall string\n"); - } - } - else { - PyErr_Clear(); - printf("Error, bge.logic failed to import bge.logic.globalDict will be lost\n"); - } - } - return 0; -} - -void pathGamePythonConfig(char *path) -{ - int len = strlen(gp_GamePythonPathOrig); // Always use the first loaded blend filename - - BLI_strncpy(path, gp_GamePythonPathOrig, sizeof(gp_GamePythonPathOrig)); - - /* replace extension */ - if (BLI_testextensie(path, ".blend")) { - strcpy(path+(len-6), ".bgeconf"); - } else { - strcpy(path+len, ".bgeconf"); - } -} - -void setGamePythonPath(const char *path) -{ - BLI_strncpy(gp_GamePythonPath, path, sizeof(gp_GamePythonPath)); - BLI_cleanup_file(NULL, gp_GamePythonPath); /* not absolutely needed but makes resolving path problems less confusing later */ - - if (gp_GamePythonPathOrig[0] == '\0') - BLI_strncpy(gp_GamePythonPathOrig, path, sizeof(gp_GamePythonPathOrig)); -} - -// we need this so while blender is open (not blenderplayer) -// loading new blendfiles will reset this on starting the -// engine but loading blend files within the BGE wont overwrite gp_GamePythonPathOrig -void resetGamePythonPath() -{ - gp_GamePythonPathOrig[0] = '\0'; -} - -#endif // WITH_PYTHON diff --git a/source/gameengine/Ketsji/KX_PythonInit.h b/source/gameengine/Ketsji/KX_PythonInit.h deleted file mode 100644 index 6550934a916..00000000000 --- a/source/gameengine/Ketsji/KX_PythonInit.h +++ /dev/null @@ -1,95 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_PythonInit.h - * \ingroup ketsji - */ - -#ifndef __KX_PYTHONINIT_H__ -#define __KX_PYTHONINIT_H__ - -#include "EXP_Python.h" -#include "STR_String.h" -#include "MT_Vector3.h" - -class KX_KetsjiEngine; -class KX_Scene; - -typedef enum { - psl_Lowest = 0, - psl_Highest, -} TPythonSecurityLevel; - -extern bool gUseVisibilityTemp; - -#ifdef WITH_PYTHON -PyMODINIT_FUNC initBGE(void); -PyMODINIT_FUNC initApplicationPythonBinding(void); -PyMODINIT_FUNC initGameLogicPythonBinding(void); -PyMODINIT_FUNC initGameKeysPythonBinding(void); -PyMODINIT_FUNC initRasterizerPythonBinding(void); -PyMODINIT_FUNC initVideoTexturePythonBinding(void); -PyObject *initGamePlayerPythonScripting(struct Main *maggie, int argc, char **argv); -PyObject *initGamePythonScripting(struct Main *maggie); - -void exitGamePlayerPythonScripting(); -void exitGamePythonScripting(); -void setupGamePython(KX_KetsjiEngine *ketsjiengine, KX_Scene *startscene, Main *blenderdata, - PyObject *pyGlobalDict, PyObject **gameLogic, PyObject **gameLogic_keys, int argc, char **argv); -void setGamePythonPath(const char *path); -void resetGamePythonPath(); -void pathGamePythonConfig(char *path); -int saveGamePythonConfig(char **marshal_buffer); -int loadGamePythonConfig(char *marshal_buffer, int marshal_length); -#endif - -void addImportMain(struct Main *maggie); -void removeImportMain(struct Main *maggie); - -class KX_KetsjiEngine; -class KX_Scene; - -void KX_SetActiveScene(KX_Scene *scene); -KX_Scene *KX_GetActiveScene(); -KX_KetsjiEngine *KX_GetActiveEngine(); - -typedef int (*PyNextFrameFunc)(void *); - -struct PyNextFrameState { - /** can be either a GPG_NextFrameState or a BL_KetsjiNextFrameState */ - void *state; - /** can be either GPG_PyNextFrame or BL_KetsjiPyNextFrame */ - PyNextFrameFunc func; -}; -extern struct PyNextFrameState pynextframestate; - -void KX_RasterizerDrawDebugLine(const MT_Vector3 &from,const MT_Vector3 &to,const MT_Vector3 &color); -void KX_RasterizerDrawDebugCircle(const MT_Vector3 ¢er, const MT_Scalar radius, const MT_Vector3 &color, - const MT_Vector3 &normal, int nsector); - - -#endif /* __KX_PYTHONINIT_H__ */ diff --git a/source/gameengine/Ketsji/KX_PythonInitTypes.cpp b/source/gameengine/Ketsji/KX_PythonInitTypes.cpp deleted file mode 100644 index 4a999e37f2b..00000000000 --- a/source/gameengine/Ketsji/KX_PythonInitTypes.cpp +++ /dev/null @@ -1,286 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): Campbell Barton - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_PythonInitTypes.cpp - * \ingroup ketsji - */ - -#ifdef WITH_PYTHON - -#include "KX_PythonInitTypes.h" - -/* Only for Class::Parents */ -#include "BL_BlenderShader.h" -#include "BL_ShapeActionActuator.h" -#include "BL_ArmatureActuator.h" -#include "BL_ArmatureConstraint.h" -#include "BL_ArmatureObject.h" -#include "BL_ArmatureChannel.h" -#include "KX_WorldInfo.h" -#include "KX_ArmatureSensor.h" -#include "KX_BlenderMaterial.h" -#include "KX_CameraActuator.h" -#include "KX_CharacterWrapper.h" -#include "KX_ConstraintActuator.h" -#include "KX_ConstraintWrapper.h" -#include "KX_GameActuator.h" -#include "KX_LibLoadStatus.h" -#include "KX_Light.h" -#include "KX_FontObject.h" -#include "KX_MeshProxy.h" -#include "KX_MouseFocusSensor.h" -#include "KX_NetworkMessageActuator.h" -#include "KX_NetworkMessageSensor.h" -#include "KX_ObjectActuator.h" -#include "KX_ParentActuator.h" -#include "KX_PolyProxy.h" -#include "KX_SCA_AddObjectActuator.h" -#include "KX_SCA_EndObjectActuator.h" -#include "KX_SCA_ReplaceMeshActuator.h" -#include "KX_SceneActuator.h" -#include "KX_StateActuator.h" -#include "KX_SteeringActuator.h" -#include "KX_TrackToActuator.h" -#include "KX_VehicleWrapper.h" -#include "KX_VertexProxy.h" -#include "SCA_2DFilterActuator.h" -#include "SCA_ANDController.h" -#include "SCA_ActuatorSensor.h" -#include "SCA_AlwaysSensor.h" -#include "SCA_DelaySensor.h" -#include "SCA_JoystickSensor.h" -#include "SCA_KeyboardSensor.h" -#include "SCA_MouseSensor.h" -#include "SCA_NANDController.h" -#include "SCA_NORController.h" -#include "SCA_ORController.h" -#include "SCA_RandomSensor.h" -#include "SCA_XNORController.h" -#include "SCA_XORController.h" -#include "SCA_PythonJoystick.h" -#include "SCA_PythonKeyboard.h" -#include "SCA_PythonMouse.h" -#include "KX_NearSensor.h" -#include "KX_RadarSensor.h" -#include "KX_RaySensor.h" -#include "KX_SCA_DynamicActuator.h" -#include "KX_SoundActuator.h" -#include "KX_TouchSensor.h" -#include "KX_VisibilityActuator.h" -#include "SCA_PropertySensor.h" -#include "SCA_PythonController.h" -#include "SCA_RandomActuator.h" -#include "SCA_IController.h" -#include "KX_NavMeshObject.h" -#include "KX_MouseActuator.h" -#include "EXP_ListWrapper.h" - -static void PyType_Attr_Set(PyGetSetDef *attr_getset, PyAttributeDef *attr) -{ - attr_getset->name= (char *)attr->m_name; - attr_getset->doc= NULL; - - attr_getset->get= reinterpret_cast(PyObjectPlus::py_get_attrdef); - - if (attr->m_access==KX_PYATTRIBUTE_RO) - attr_getset->set= NULL; - else - attr_getset->set= reinterpret_cast(PyObjectPlus::py_set_attrdef); - - attr_getset->closure= reinterpret_cast(attr); -} - -static void PyType_Ready_ADD(PyObject *dict, PyTypeObject *tp, PyAttributeDef *attributes, PyAttributeDef *attributesPtr, int init_getset) -{ - PyAttributeDef *attr; - - if (init_getset) { - /* we need to do this for all types before calling PyType_Ready - * since they will call the parents PyType_Ready and those might not have initialized vars yet */ - - //if (tp->tp_base==NULL) - // printf("Debug: No Parents - '%s'\n" , tp->tp_name); - - if (tp->tp_getset==NULL && ((attributes && attributes->m_name) || (attributesPtr && attributesPtr->m_name))) { - PyGetSetDef *attr_getset; - int attr_tot= 0; - - if (attributes) { - for (attr= attributes; attr->m_name; attr++, attr_tot++) - attr->m_usePtr = false; - } - if (attributesPtr) { - for (attr= attributesPtr; attr->m_name; attr++, attr_tot++) - attr->m_usePtr = true; - } - - tp->tp_getset = attr_getset = reinterpret_cast(PyMem_Malloc((attr_tot+1) * sizeof(PyGetSetDef))); // XXX - Todo, free - - if (attributes) { - for (attr= attributes; attr->m_name; attr++, attr_getset++) { - PyType_Attr_Set(attr_getset, attr); - } - } - if (attributesPtr) { - for (attr= attributesPtr; attr->m_name; attr++, attr_getset++) { - PyType_Attr_Set(attr_getset, attr); - } - } - memset(attr_getset, 0, sizeof(PyGetSetDef)); - } - } else { - PyType_Ready(tp); - PyDict_SetItemString(dict, tp->tp_name, reinterpret_cast(tp)); - } - -} - - -#define PyType_Ready_Attr(d, n, i) PyType_Ready_ADD(d, &n::Type, n::Attributes, NULL, i) -#define PyType_Ready_AttrPtr(d, n, i) PyType_Ready_ADD(d, &n::Type, n::Attributes, n::AttributesPtr, i) - - - -PyDoc_STRVAR(GameTypes_module_documentation, -"This module provides access to the game engine data types." -); -static struct PyModuleDef GameTypes_module_def = { - PyModuleDef_HEAD_INIT, - "GameTypes", /* m_name */ - GameTypes_module_documentation, /* m_doc */ - 0, /* m_size */ - NULL, /* m_methods */ - NULL, /* m_reload */ - NULL, /* m_traverse */ - NULL, /* m_clear */ - NULL, /* m_free */ -}; - - -PyMODINIT_FUNC initGameTypesPythonBinding(void) -{ - PyObject *m; - PyObject *dict; - - m = PyModule_Create(&GameTypes_module_def); - PyDict_SetItemString(PySys_GetObject("modules"), GameTypes_module_def.m_name, m); - - dict = PyModule_GetDict(m); - - for (int init_getset= 1; init_getset > -1; init_getset--) { /* run twice, once to init the getsets another to run PyType_Ready */ - PyType_Ready_Attr(dict, BL_ActionActuator, init_getset); - PyType_Ready_Attr(dict, BL_Shader, init_getset); - PyType_Ready_Attr(dict, BL_ShapeActionActuator, init_getset); - PyType_Ready_Attr(dict, BL_ArmatureObject, init_getset); - PyType_Ready_Attr(dict, BL_ArmatureActuator, init_getset); - PyType_Ready_Attr(dict, BL_ArmatureConstraint, init_getset); - PyType_Ready_AttrPtr(dict, BL_ArmatureBone, init_getset); - PyType_Ready_AttrPtr(dict, BL_ArmatureChannel, init_getset); - // PyType_Ready_Attr(dict, CPropValue, init_getset); // doesn't use Py_Header - PyType_Ready_Attr(dict, CListValue, init_getset); - PyType_Ready_Attr(dict, CListWrapper, init_getset); - PyType_Ready_Attr(dict, CValue, init_getset); - PyType_Ready_Attr(dict, KX_ArmatureSensor, init_getset); - PyType_Ready_Attr(dict, KX_BlenderMaterial, init_getset); - PyType_Ready_Attr(dict, KX_Camera, init_getset); - PyType_Ready_Attr(dict, KX_CameraActuator, init_getset); - PyType_Ready_Attr(dict, KX_CharacterWrapper, init_getset); - PyType_Ready_Attr(dict, KX_ConstraintActuator, init_getset); - PyType_Ready_Attr(dict, KX_ConstraintWrapper, init_getset); - PyType_Ready_Attr(dict, KX_GameActuator, init_getset); - PyType_Ready_Attr(dict, KX_GameObject, init_getset); - PyType_Ready_Attr(dict, KX_LibLoadStatus, init_getset); - PyType_Ready_Attr(dict, KX_LightObject, init_getset); - PyType_Ready_Attr(dict, KX_FontObject, init_getset); - PyType_Ready_Attr(dict, KX_MeshProxy, init_getset); - PyType_Ready_Attr(dict, KX_MouseFocusSensor, init_getset); - PyType_Ready_Attr(dict, KX_NearSensor, init_getset); - PyType_Ready_Attr(dict, KX_NetworkMessageActuator, init_getset); - PyType_Ready_Attr(dict, KX_NetworkMessageSensor, init_getset); - PyType_Ready_Attr(dict, KX_ObjectActuator, init_getset); - PyType_Ready_Attr(dict, KX_ParentActuator, init_getset); - PyType_Ready_Attr(dict, KX_PolyProxy, init_getset); - PyType_Ready_Attr(dict, KX_RadarSensor, init_getset); - PyType_Ready_Attr(dict, KX_RaySensor, init_getset); - PyType_Ready_Attr(dict, KX_SCA_AddObjectActuator, init_getset); - PyType_Ready_Attr(dict, KX_SCA_DynamicActuator, init_getset); - PyType_Ready_Attr(dict, KX_SCA_EndObjectActuator, init_getset); - PyType_Ready_Attr(dict, KX_SCA_ReplaceMeshActuator, init_getset); - PyType_Ready_Attr(dict, KX_Scene, init_getset); - PyType_Ready_Attr(dict, KX_WorldInfo, init_getset); - PyType_Ready_Attr(dict, KX_NavMeshObject, init_getset); - PyType_Ready_Attr(dict, KX_SceneActuator, init_getset); - PyType_Ready_Attr(dict, KX_SoundActuator, init_getset); - PyType_Ready_Attr(dict, KX_StateActuator, init_getset); - PyType_Ready_Attr(dict, KX_SteeringActuator, init_getset); - PyType_Ready_Attr(dict, KX_TouchSensor, init_getset); - PyType_Ready_Attr(dict, KX_TrackToActuator, init_getset); - PyType_Ready_Attr(dict, KX_VehicleWrapper, init_getset); - PyType_Ready_Attr(dict, KX_VertexProxy, init_getset); - PyType_Ready_Attr(dict, KX_VisibilityActuator, init_getset); - PyType_Ready_Attr(dict, KX_MouseActuator, init_getset); - PyType_Ready_Attr(dict, PyObjectPlus, init_getset); - PyType_Ready_Attr(dict, SCA_2DFilterActuator, init_getset); - PyType_Ready_Attr(dict, SCA_ANDController, init_getset); - // PyType_Ready_Attr(dict, SCA_Actuator, init_getset); // doesn't use Py_Header - PyType_Ready_Attr(dict, SCA_ActuatorSensor, init_getset); - PyType_Ready_Attr(dict, SCA_AlwaysSensor, init_getset); - PyType_Ready_Attr(dict, SCA_DelaySensor, init_getset); - PyType_Ready_Attr(dict, SCA_ILogicBrick, init_getset); - PyType_Ready_Attr(dict, SCA_IObject, init_getset); - PyType_Ready_Attr(dict, SCA_ISensor, init_getset); - PyType_Ready_Attr(dict, SCA_JoystickSensor, init_getset); - PyType_Ready_Attr(dict, SCA_KeyboardSensor, init_getset); - PyType_Ready_Attr(dict, SCA_MouseSensor, init_getset); - PyType_Ready_Attr(dict, SCA_NANDController, init_getset); - PyType_Ready_Attr(dict, SCA_NORController, init_getset); - PyType_Ready_Attr(dict, SCA_ORController, init_getset); - PyType_Ready_Attr(dict, SCA_PropertyActuator, init_getset); - PyType_Ready_Attr(dict, SCA_PropertySensor, init_getset); - PyType_Ready_Attr(dict, SCA_PythonController, init_getset); - PyType_Ready_Attr(dict, SCA_RandomActuator, init_getset); - PyType_Ready_Attr(dict, SCA_RandomSensor, init_getset); - PyType_Ready_Attr(dict, SCA_XNORController, init_getset); - PyType_Ready_Attr(dict, SCA_XORController, init_getset); - PyType_Ready_Attr(dict, SCA_IController, init_getset); - PyType_Ready_Attr(dict, SCA_PythonJoystick, init_getset); - PyType_Ready_Attr(dict, SCA_PythonKeyboard, init_getset); - PyType_Ready_Attr(dict, SCA_PythonMouse, init_getset); - } - -#ifdef USE_MATHUTILS - /* Init mathutils callbacks */ - KX_GameObject_Mathutils_Callback_Init(); - KX_ObjectActuator_Mathutils_Callback_Init(); - KX_WorldInfo_Mathutils_Callback_Init(); - KX_BlenderMaterial_Mathutils_Callback_Init(); -#endif - - return m; -} - -#endif // WITH_PYTHON diff --git a/source/gameengine/Ketsji/KX_PythonInitTypes.h b/source/gameengine/Ketsji/KX_PythonInitTypes.h deleted file mode 100644 index cfc49a1dc93..00000000000 --- a/source/gameengine/Ketsji/KX_PythonInitTypes.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): Campbell Barton - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_PythonInitTypes.h - * \ingroup ketsji - */ - -#ifndef __KX_PYTHON_INIT_TYPES__ -#define __KX_PYTHON_INIT_TYPES__ - -#ifdef WITH_PYTHON -#include -PyMODINIT_FUNC initGameTypesPythonBinding(void); -#endif - -#endif /* __KX_PYTHON_INIT_TYPES__ */ diff --git a/source/gameengine/Ketsji/KX_PythonMain.cpp b/source/gameengine/Ketsji/KX_PythonMain.cpp deleted file mode 100644 index 740bb102fd9..00000000000 --- a/source/gameengine/Ketsji/KX_PythonMain.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * Contributor(s): Benoit Bolsee - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_PythonMain.cpp - * \ingroup ketsji - */ - -#include "KX_PythonMain.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#include - -#include "MEM_guardedalloc.h" - -#include "BLI_string.h" -#include "BLI_listbase.h" - -#include "BKE_text.h" -#include "BKE_main.h" -#include "BKE_idprop.h" - - -#ifdef __cplusplus -} -#endif - -extern "C" char *KX_GetPythonMain(struct Scene *scene) -{ - /* examine custom scene properties */ - if (scene->id.properties) { - IDProperty *item = IDP_GetPropertyTypeFromGroup(scene->id.properties, "__main__", IDP_STRING); - if (item) { - return BLI_strdup(IDP_String(item)); - } - } - - return NULL; -} - -extern "C" char *KX_GetPythonCode(Main *bmain, char *python_main) -{ - Text *text; - - if ((text = (Text *)BLI_findstring(&bmain->text, python_main, offsetof(ID, name) + 2))) { - return txt_to_buf(text); - } - - return NULL; -} diff --git a/source/gameengine/Ketsji/KX_PythonMain.h b/source/gameengine/Ketsji/KX_PythonMain.h deleted file mode 100644 index c627a4a147a..00000000000 --- a/source/gameengine/Ketsji/KX_PythonMain.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_PythonMain.h - * \ingroup ketsji - */ - -#ifndef __KX_PYTHON_MAIN__ -#define __KX_PYTHON_MAIN__ - -#include "BLI_sys_types.h" -#include "BKE_main.h" -#include "DNA_scene_types.h" -extern "C" char *KX_GetPythonMain(struct Scene* scene); -extern "C" char *KX_GetPythonCode(struct Main *main, char *python_main); - -#endif /* __KX_PYTHON_MAIN__ */ diff --git a/source/gameengine/Ketsji/KX_RadarSensor.cpp b/source/gameengine/Ketsji/KX_RadarSensor.cpp deleted file mode 100644 index 861e3f70296..00000000000 --- a/source/gameengine/Ketsji/KX_RadarSensor.cpp +++ /dev/null @@ -1,230 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_RadarSensor.cpp - * \ingroup ketsji - */ - - -#include "KX_RadarSensor.h" -#include "KX_GameObject.h" -#include "KX_PyMath.h" -#include "PHY_IPhysicsController.h" -#include "PHY_IMotionState.h" -#include "DNA_sensor_types.h" - -/** - * RadarSensor constructor. Creates a near-sensor derived class, with a cone collision shape. - */ -KX_RadarSensor::KX_RadarSensor(SCA_EventManager* eventmgr, - KX_GameObject* gameobj, - PHY_IPhysicsController* physCtrl, - double coneradius, - double coneheight, - int axis, - double margin, - double resetmargin, - bool bFindMaterial, - const STR_String& touchedpropname) - - : KX_NearSensor( - eventmgr, - gameobj, - //DT_NewCone(coneradius,coneheight), - margin, - resetmargin, - bFindMaterial, - touchedpropname, - physCtrl), - - m_coneradius(coneradius), - m_coneheight(coneheight), - m_axis(axis) -{ - m_client_info->m_type = KX_ClientObjectInfo::SENSOR; - //m_client_info->m_clientobject = gameobj; - //m_client_info->m_auxilary_info = NULL; - //sumoObj->setClientObject(&m_client_info); -} - -KX_RadarSensor::~KX_RadarSensor() -{ - -} - -CValue* KX_RadarSensor::GetReplica() -{ - KX_RadarSensor* replica = new KX_RadarSensor(*this); - replica->ProcessReplica(); - return replica; -} - -/** - * Transforms the collision object. A cone is not correctly centered - * for usage. */ -void KX_RadarSensor::SynchronizeTransform() -{ - // Getting the parent location was commented out. Why? - MT_Transform trans; - trans.setOrigin(((KX_GameObject*)GetParent())->NodeGetWorldPosition()); - trans.setBasis(((KX_GameObject*)GetParent())->NodeGetWorldOrientation()); - // What is the default orientation? pointing in the -y direction? - // is the geometry correctly converted? - - // a collision cone is oriented - // center the cone correctly - // depends on the radar 'axis' - switch (m_axis) - { - case SENS_RADAR_X_AXIS: // +X Axis - { - MT_Quaternion rotquatje(MT_Vector3(0,0,1),MT_radians(90)); - trans.rotate(rotquatje); - trans.translate(MT_Vector3 (0, -m_coneheight/2.0f, 0)); - break; - }; - case SENS_RADAR_Y_AXIS: // +Y Axis - { - MT_Quaternion rotquatje(MT_Vector3(1,0,0),MT_radians(-180)); - trans.rotate(rotquatje); - trans.translate(MT_Vector3 (0, -m_coneheight/2.0f, 0)); - break; - }; - case SENS_RADAR_Z_AXIS: // +Z Axis - { - MT_Quaternion rotquatje(MT_Vector3(1,0,0),MT_radians(-90)); - trans.rotate(rotquatje); - trans.translate(MT_Vector3 (0, -m_coneheight/2.0f, 0)); - break; - }; - case SENS_RADAR_NEG_X_AXIS: // -X Axis - { - MT_Quaternion rotquatje(MT_Vector3(0,0,1),MT_radians(-90)); - trans.rotate(rotquatje); - trans.translate(MT_Vector3 (0, -m_coneheight/2.0f, 0)); - break; - }; - case SENS_RADAR_NEG_Y_AXIS: // -Y Axis - { - //MT_Quaternion rotquatje(MT_Vector3(1,0,0),MT_radians(-180)); - //trans.rotate(rotquatje); - trans.translate(MT_Vector3 (0, -m_coneheight/2.0f, 0)); - break; - }; - case SENS_RADAR_NEG_Z_AXIS: // -Z Axis - { - MT_Quaternion rotquatje(MT_Vector3(1,0,0),MT_radians(90)); - trans.rotate(rotquatje); - trans.translate(MT_Vector3 (0, -m_coneheight/2.0f, 0)); - break; - }; - default: - { - } - } - - //Using a temp variable to translate MT_Point3 to float[3]. - //float[3] works better for the Python interface. - MT_Point3 temp = trans.getOrigin(); - m_cone_origin[0] = temp[0]; - m_cone_origin[1] = temp[1]; - m_cone_origin[2] = temp[2]; - - temp = trans(MT_Point3(0, -m_coneheight/2.0f, 0)); - m_cone_target[0] = temp[0]; - m_cone_target[1] = temp[1]; - m_cone_target[2] = temp[2]; - - - if (m_physCtrl) - { - PHY_IMotionState* motionState = m_physCtrl->GetMotionState(); - const MT_Point3& pos = trans.getOrigin(); - float ori[12]; - trans.getBasis().getValue(ori); - motionState->SetWorldPosition(pos[0], pos[1], pos[2]); - motionState->SetWorldOrientation(ori); - m_physCtrl->WriteMotionStateToDynamics(true); - } - -} - -/* ------------------------------------------------------------------------- */ -/* Python Functions */ -/* ------------------------------------------------------------------------- */ - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python Integration Hooks */ -/* ------------------------------------------------------------------------- */ -PyTypeObject KX_RadarSensor::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_RadarSensor", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &KX_NearSensor::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_RadarSensor::Methods[] = { - {NULL} //Sentinel -}; - -PyAttributeDef KX_RadarSensor::Attributes[] = { - KX_PYATTRIBUTE_FLOAT_ARRAY_RO("coneOrigin", KX_RadarSensor, m_cone_origin, 3), - KX_PYATTRIBUTE_FLOAT_ARRAY_RO("coneTarget", KX_RadarSensor, m_cone_target, 3), - KX_PYATTRIBUTE_FLOAT_RO("distance", KX_RadarSensor, m_coneheight), - KX_PYATTRIBUTE_RO_FUNCTION("angle", KX_RadarSensor, pyattr_get_angle), - KX_PYATTRIBUTE_INT_RW("axis", 0, 5, true, KX_RadarSensor, m_axis), - {NULL} //Sentinel -}; - -PyObject *KX_RadarSensor::pyattr_get_angle(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_RadarSensor* self = static_cast(self_v); - - // The original angle from the gui was converted, so we recalculate the value here to maintain - // consistency between Python and the gui - return PyFloat_FromDouble(MT_degrees(atan(self->m_coneradius / self->m_coneheight)) * 2); - -} - -#endif // WITH_PYTHON diff --git a/source/gameengine/Ketsji/KX_RadarSensor.h b/source/gameengine/Ketsji/KX_RadarSensor.h deleted file mode 100644 index 6a2d50ffa3a..00000000000 --- a/source/gameengine/Ketsji/KX_RadarSensor.h +++ /dev/null @@ -1,100 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_RadarSensor.h - * \ingroup ketsji - */ - -#ifndef __KX_RADARSENSOR_H__ -#define __KX_RADARSENSOR_H__ - -#include "KX_NearSensor.h" -#include "MT_Point3.h" - -/** - * Radar 'cone' sensor. Very similar to a near-sensor, but instead of a sphere, a cone is used. - */ -class KX_RadarSensor : public KX_NearSensor -{ - protected: - Py_Header - - float m_coneradius; - - /** - * Height of the cone. - */ - float m_coneheight; - int m_axis; - - /** - * The previous position of the origin of the cone. - */ - float m_cone_origin[3]; - - /** - * The previous direction of the cone (origin to bottom plane). - */ - float m_cone_target[3]; - -public: - - KX_RadarSensor(SCA_EventManager* eventmgr, - KX_GameObject* gameobj, - PHY_IPhysicsController* physCtrl, - double coneradius, - double coneheight, - int axis, - double margin, - double resetmargin, - bool bFindMaterial, - const STR_String& touchedpropname); - KX_RadarSensor(); - virtual ~KX_RadarSensor(); - virtual void SynchronizeTransform(); - virtual CValue* GetReplica(); - - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - enum RadarAxis { - KX_RADAR_AXIS_POS_X = 0, - KX_RADAR_AXIS_POS_Y, - KX_RADAR_AXIS_POS_Z, - KX_RADAR_AXIS_NEG_X, - KX_RADAR_AXIS_NEG_Y, - KX_RADAR_AXIS_NEG_Z - }; - - virtual sensortype GetSensorType() { return ST_RADAR; } - /* python */ -#ifdef WITH_PYTHON - static PyObject* pyattr_get_angle(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); -#endif -}; - -#endif /* __KX_RADARSENSOR_H__ */ diff --git a/source/gameengine/Ketsji/KX_RayCast.cpp b/source/gameengine/Ketsji/KX_RayCast.cpp deleted file mode 100644 index 478019c6304..00000000000 --- a/source/gameengine/Ketsji/KX_RayCast.cpp +++ /dev/null @@ -1,121 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - * KX_MouseFocusSensor determines mouse in/out/over events. - */ - -/** \file gameengine/Ketsji/KX_RayCast.cpp - * \ingroup ketsji - */ - - -#include -#include - -#include "KX_RayCast.h" - -#include "MT_Point3.h" -#include "MT_Vector3.h" - -#include "PHY_IPhysicsEnvironment.h" -#include "PHY_IPhysicsController.h" - -KX_RayCast::KX_RayCast(PHY_IPhysicsController* ignoreController, bool faceNormal, bool faceUV) - :PHY_IRayCastFilterCallback(ignoreController, faceNormal, faceUV) -{ -} - -void KX_RayCast::reportHit(PHY_RayCastResult* result) -{ - m_hitFound = true; - m_hitPoint = MT_Vector3(result->m_hitPoint); - m_hitNormal = MT_Vector3(result->m_hitNormal); - m_hitUVOK = result->m_hitUVOK; - m_hitUV = MT_Vector2(result->m_hitUV); - m_hitMesh = result->m_meshObject; - m_hitPolygon = result->m_polygon; -} - -bool KX_RayCast::RayTest(PHY_IPhysicsEnvironment* physics_environment, const MT_Point3& _frompoint, const MT_Point3& topoint, KX_RayCast& callback) -{ - if (physics_environment==NULL) return false; /* prevents crashing in some cases */ - - // Loops over all physics objects between frompoint and topoint, - // calling callback.RayHit for each one. - // - // callback.RayHit should return true to stop looking, or false to continue. - // - // returns true if an object was found, false if not. - - MT_Point3 frompoint(_frompoint); - const MT_Vector3 todir( (topoint - frompoint).safe_normalized() ); - MT_Point3 prevpoint(_frompoint+todir*(-1.f)); - - PHY_IPhysicsController* hit_controller; - - while ((hit_controller = physics_environment->RayTest(callback, - frompoint.x(),frompoint.y(),frompoint.z(), - topoint.x(),topoint.y(),topoint.z())) != NULL) - { - KX_ClientObjectInfo *info = static_cast(hit_controller->GetNewClientInfo()); - - if (!info) - { - printf("no info!\n"); - MT_assert(info && "Physics controller with no client object info"); - break; - } - - // The biggest danger to endless loop, prevent this by checking that the - // hit point always progresses along the ray direction.. - prevpoint -= callback.m_hitPoint; - if (prevpoint.length2() < MT_EPSILON) - break; - - if (callback.RayHit(info)) - // caller may decide to stop the loop and still cancel the hit - return callback.m_hitFound; - - // Skip past the object and keep tracing. - // Note that retrieving in a single shot multiple hit points would be possible - // but it would require some change in Bullet. - prevpoint = callback.m_hitPoint; - /* We add 0.001 of fudge, so that if the margin && radius == 0.0, we don't endless loop. */ - MT_Scalar marg = 0.001f + hit_controller->GetMargin(); - marg *= 2.f; - /* Calculate the other side of this object */ - MT_Scalar h = MT_abs(todir.dot(callback.m_hitNormal)); - if (h <= 0.01f) - // the normal is almost orthogonal to the ray direction, cannot compute the other side - break; - marg /= h; - frompoint = callback.m_hitPoint + marg * todir; - // verify that we are not passed the to point - if ((topoint - frompoint).dot(todir) < 0.f) - break; - } - return false; -} - diff --git a/source/gameengine/Ketsji/KX_RayCast.h b/source/gameengine/Ketsji/KX_RayCast.h deleted file mode 100644 index c977fb8f385..00000000000 --- a/source/gameengine/Ketsji/KX_RayCast.h +++ /dev/null @@ -1,149 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_RayCast.h - * \ingroup ketsji - */ - -#ifndef __KX_RAYCAST_H__ -#define __KX_RAYCAST_H__ - -#include "PHY_IPhysicsEnvironment.h" -#include "PHY_IPhysicsController.h" -#include "MT_Vector2.h" -#include "MT_Point3.h" -#include "MT_Vector3.h" - -class RAS_MeshObject; -struct KX_ClientObjectInfo; - -/** - * Defines a function for doing a ray cast. - * - * eg KX_RayCast::RayTest(ignore_physics_controller, physics_environment, frompoint, topoint, result_point, result_normal, KX_RayCast::Callback(this, data) - * - * Calls myclass->NeedRayCast(client, data) for all client in environment - * and myclass->RayHit(client, hit_point, hit_normal, data) for all client - * between frompoint and topoint - * - * myclass->NeedRayCast should return true to ray test the current client. - * - * myclass->RayHit should return true to end the raycast, false to ignore the current client and to continue. - * - * Returns true if a client was accepted, false if nothing found. - */ -class KX_RayCast : public PHY_IRayCastFilterCallback -{ -public: - bool m_hitFound; - MT_Point3 m_hitPoint; - MT_Vector3 m_hitNormal; - const RAS_MeshObject* m_hitMesh; - int m_hitPolygon; - int m_hitUVOK; // !=0 if UV coordinate in m_hitUV is valid - MT_Vector2 m_hitUV; - - KX_RayCast(PHY_IPhysicsController* ignoreController, bool faceNormal, bool faceUV); - virtual ~KX_RayCast() {} - - /** - * The physic environment returns the ray casting result through this function - */ - virtual void reportHit(PHY_RayCastResult* result); - - /** ray test callback. - * either override this in your class, or use a callback wrapper. - */ - virtual bool RayHit(KX_ClientObjectInfo* client) = 0; - - /** - * Callback wrapper. - * - * Construct with KX_RayCast::Callback(this, data) - * and pass to KX_RayCast::RayTest - */ - template class Callback; - - /// Public interface. - /// Implement bool RayHit in your class to receive ray callbacks. - static bool RayTest( - PHY_IPhysicsEnvironment* physics_environment, - const MT_Point3& frompoint, - const MT_Point3& topoint, - KX_RayCast& callback); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_RayCast") -#endif -}; - -template -class KX_RayCast::Callback : public KX_RayCast -{ - T *self; - /** - * Some user info passed as argument in constructor. - * It contains all info needed to check client in NeedRayCast - * and RayHit. - */ - dataT *data; -public: - Callback(T *_self, PHY_IPhysicsController *controller = NULL, dataT *_data = NULL, bool faceNormal = false, bool faceUV = false) - : KX_RayCast(controller, faceNormal, faceUV), - self(_self), - data(_data) - { - } - - ~Callback() {} - - virtual bool RayHit(KX_ClientObjectInfo* client) - { - return self->RayHit(client, this, data); - } - - virtual bool needBroadphaseRayCast(PHY_IPhysicsController* controller) - { - KX_ClientObjectInfo* info = static_cast(controller->GetNewClientInfo()); - - if (!info) - { - MT_assert(info && "Physics controller with no client object info"); - return false; - } - return self->NeedRayCast(info, data); - } - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_RayCast::Callback") -#endif -}; - - -#endif diff --git a/source/gameengine/Ketsji/KX_RayEventManager.cpp b/source/gameengine/Ketsji/KX_RayEventManager.cpp deleted file mode 100644 index 661c7eb6f64..00000000000 --- a/source/gameengine/Ketsji/KX_RayEventManager.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Manager for ray events - * - * - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_RayEventManager.cpp - * \ingroup ketsji - */ - -#include "KX_RayEventManager.h" -#include "SCA_LogicManager.h" -#include "SCA_ISensor.h" -#include - -using namespace std; - -#include -#include - -void KX_RayEventManager::NextFrame() -{ - SG_DList::iterator it(m_sensors); - for (it.begin();!it.end();++it) - { - (*it)->Activate(m_logicmgr); - } -} - diff --git a/source/gameengine/Ketsji/KX_RayEventManager.h b/source/gameengine/Ketsji/KX_RayEventManager.h deleted file mode 100644 index 07506b9e32b..00000000000 --- a/source/gameengine/Ketsji/KX_RayEventManager.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_RayEventManager.h - * \ingroup ketsji - * \brief Manager for ray events - */ - -#ifndef __KX_RAYEVENTMANAGER_H__ -#define __KX_RAYEVENTMANAGER_H__ -#include "SCA_EventManager.h" -#include -using namespace std; - -class KX_RayEventManager : public SCA_EventManager -{ -public: - KX_RayEventManager(class SCA_LogicManager* logicmgr) - : SCA_EventManager(logicmgr, RAY_EVENTMGR) - {} - virtual void NextFrame(); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_RayEventManager") -#endif -}; - -#endif /* __KX_RAYEVENTMANAGER_H__ */ diff --git a/source/gameengine/Ketsji/KX_RaySensor.cpp b/source/gameengine/Ketsji/KX_RaySensor.cpp deleted file mode 100644 index 4ffb5f332db..00000000000 --- a/source/gameengine/Ketsji/KX_RaySensor.cpp +++ /dev/null @@ -1,383 +0,0 @@ -/* - * Cast a ray and feel for objects - * - * - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_RaySensor.cpp - * \ingroup ketsji - */ - - -#include "KX_RaySensor.h" -#include "SCA_EventManager.h" -#include "SCA_RandomEventManager.h" -#include "SCA_LogicManager.h" -#include "SCA_IObject.h" -#include "KX_ClientObjectInfo.h" -#include "KX_GameObject.h" -#include "KX_Scene.h" -#include "KX_RayCast.h" -#include "KX_PyMath.h" -#include "PHY_IPhysicsEnvironment.h" -#include "PHY_IPhysicsController.h" -#include "DNA_sensor_types.h" -#include "RAS_MeshObject.h" - -#include - - -KX_RaySensor::KX_RaySensor(class SCA_EventManager* eventmgr, - SCA_IObject* gameobj, - const STR_String& propname, - bool bFindMaterial, - bool bXRay, - double distance, - int axis, - KX_Scene* ketsjiScene) - : SCA_ISensor(gameobj,eventmgr), - m_propertyname(propname), - m_bFindMaterial(bFindMaterial), - m_bXRay(bXRay), - m_distance(distance), - m_scene(ketsjiScene), - m_axis(axis), - m_hitMaterial("") -{ - Init(); -} - -void KX_RaySensor::Init() -{ - m_bTriggered = (m_invert)?true:false; - m_rayHit = false; - m_hitObject = NULL; - m_reset = true; -} - -KX_RaySensor::~KX_RaySensor() -{ - /* Nothing to be done here. */ -} - - - -CValue* KX_RaySensor::GetReplica() -{ - KX_RaySensor* replica = new KX_RaySensor(*this); - replica->ProcessReplica(); - replica->Init(); - - return replica; -} - - - -bool KX_RaySensor::IsPositiveTrigger() -{ - bool result = m_rayHit; - - if (m_invert) - result = !result; - - return result; -} - -bool KX_RaySensor::RayHit(KX_ClientObjectInfo *client, KX_RayCast *result, void *UNUSED(data)) -{ - - KX_GameObject* hitKXObj = client->m_gameobject; - bool bFound = false; - bool hitMaterial = false; - - if (m_propertyname.Length() == 0) - { - bFound = true; - } - else - { - if (m_bFindMaterial) { - for (unsigned int i = 0; i < hitKXObj->GetMeshCount(); ++i) { - RAS_MeshObject *meshObj = hitKXObj->GetMesh(i); - for (unsigned int j = 0; j < meshObj->NumMaterials(); ++j) { - bFound = strcmp(m_propertyname.ReadPtr(), meshObj->GetMaterialName(j).ReadPtr() + 2) == 0; - if (bFound) { - hitMaterial = true; - break; - } - } - } - } - else { - bFound = hitKXObj->GetProperty(m_propertyname) != NULL; - } - } - - if (bFound) - { - m_rayHit = true; - m_hitObject = hitKXObj; - m_hitPosition[0] = result->m_hitPoint[0]; - m_hitPosition[1] = result->m_hitPoint[1]; - m_hitPosition[2] = result->m_hitPoint[2]; - - m_hitNormal[0] = result->m_hitNormal[0]; - m_hitNormal[1] = result->m_hitNormal[1]; - m_hitNormal[2] = result->m_hitNormal[2]; - - m_hitMaterial = hitMaterial; - } - // no multi-hit search yet - return true; -} - -/* this function is used to pre-filter the object before casting the ray on them. - * This is useful for "X-Ray" option when we want to see "through" unwanted object. - */ -bool KX_RaySensor::NeedRayCast(KX_ClientObjectInfo *client, void *UNUSED(data)) -{ - KX_GameObject *hitKXObj = client->m_gameobject; - - if (client->m_type > KX_ClientObjectInfo::ACTOR) - { - // Unknown type of object, skip it. - // Should not occur as the sensor objects are filtered in RayTest() - printf("Invalid client type %d found ray casting\n", client->m_type); - return false; - } - if (m_bXRay && m_propertyname.Length() != 0) - { - if (m_bFindMaterial) { - bool found = false; - for (unsigned int i = 0; i < hitKXObj->GetMeshCount(); ++i) { - RAS_MeshObject *meshObj = hitKXObj->GetMesh(i); - for (unsigned int j = 0; j < meshObj->NumMaterials(); ++j) { - found = strcmp(m_propertyname.ReadPtr(), meshObj->GetMaterialName(j).ReadPtr() + 2) == 0; - if (found) - break; - } - } - if (!found) - return false; - } - else { - if (hitKXObj->GetProperty(m_propertyname) == NULL) - return false; - } - } - return true; -} - -bool KX_RaySensor::Evaluate() -{ - bool result = false; - bool reset = m_reset && m_level; - m_rayHit = false; - m_hitObject = NULL; - m_hitPosition[0] = 0; - m_hitPosition[1] = 0; - m_hitPosition[2] = 0; - - m_hitNormal[0] = 1; - m_hitNormal[1] = 0; - m_hitNormal[2] = 0; - - KX_GameObject* obj = (KX_GameObject*)GetParent(); - MT_Point3 frompoint = obj->NodeGetWorldPosition(); - MT_Matrix3x3 matje = obj->NodeGetWorldOrientation(); - MT_Matrix3x3 invmat = matje.inverse(); - - MT_Vector3 todir; - m_reset = false; - switch (m_axis) - { - case SENS_RAY_X_AXIS: // X - { - todir[0] = invmat[0][0]; - todir[1] = invmat[0][1]; - todir[2] = invmat[0][2]; - break; - } - case SENS_RAY_Y_AXIS: // Y - { - todir[0] = invmat[1][0]; - todir[1] = invmat[1][1]; - todir[2] = invmat[1][2]; - break; - } - case SENS_RAY_Z_AXIS: // Z - { - todir[0] = invmat[2][0]; - todir[1] = invmat[2][1]; - todir[2] = invmat[2][2]; - break; - } - case SENS_RAY_NEG_X_AXIS: // -X - { - todir[0] = -invmat[0][0]; - todir[1] = -invmat[0][1]; - todir[2] = -invmat[0][2]; - break; - } - case SENS_RAY_NEG_Y_AXIS: // -Y - { - todir[0] = -invmat[1][0]; - todir[1] = -invmat[1][1]; - todir[2] = -invmat[1][2]; - break; - } - case SENS_RAY_NEG_Z_AXIS: // -Z - { - todir[0] = -invmat[2][0]; - todir[1] = -invmat[2][1]; - todir[2] = -invmat[2][2]; - break; - } - } - todir.normalize(); - m_rayDirection[0] = todir[0]; - m_rayDirection[1] = todir[1]; - m_rayDirection[2] = todir[2]; - - MT_Point3 topoint = frompoint + (m_distance) * todir; - PHY_IPhysicsEnvironment* pe = m_scene->GetPhysicsEnvironment(); - - if (!pe) - { - std::cout << "WARNING: Ray sensor " << GetName() << ": There is no physics environment!" << std::endl; - std::cout << " Check universe for malfunction." << std::endl; - return false; - } - - PHY_IPhysicsController *spc = obj->GetPhysicsController(); - KX_GameObject *parent = obj->GetParent(); - if (!spc && parent) - spc = parent->GetPhysicsController(); - - - PHY_IPhysicsEnvironment* physics_environment = this->m_scene->GetPhysicsEnvironment(); - - - KX_RayCast::Callback callback(this, spc); - KX_RayCast::RayTest(physics_environment, frompoint, topoint, callback); - - /* now pass this result to some controller */ - - if (m_rayHit) - { - if (!m_bTriggered) - { - // notify logicsystem that ray is now hitting - result = true; - m_bTriggered = true; - } - else - { - // notify logicsystem that ray is STILL hitting ... - result = false; - - } - } - else - { - if (m_bTriggered) - { - m_bTriggered = false; - // notify logicsystem that ray JUST left the Object - result = true; - } - else - { - result = false; - } - - } - if (reset) - // force an event - result = true; - - return result; -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject KX_RaySensor::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_RaySensor", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &SCA_ISensor::Type, - 0,0,0,0,0,0, - py_base_new - -}; - -PyMethodDef KX_RaySensor::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_RaySensor::Attributes[] = { - KX_PYATTRIBUTE_BOOL_RW("useMaterial", KX_RaySensor, m_bFindMaterial), - KX_PYATTRIBUTE_BOOL_RW("useXRay", KX_RaySensor, m_bXRay), - KX_PYATTRIBUTE_FLOAT_RW("range", 0, 10000, KX_RaySensor, m_distance), - KX_PYATTRIBUTE_STRING_RW("propName", 0, MAX_PROP_NAME, false, KX_RaySensor, m_propertyname), - KX_PYATTRIBUTE_INT_RW("axis", 0, 5, true, KX_RaySensor, m_axis), - KX_PYATTRIBUTE_FLOAT_ARRAY_RO("hitPosition", KX_RaySensor, m_hitPosition, 3), - KX_PYATTRIBUTE_FLOAT_ARRAY_RO("rayDirection", KX_RaySensor, m_rayDirection, 3), - KX_PYATTRIBUTE_FLOAT_ARRAY_RO("hitNormal", KX_RaySensor, m_hitNormal, 3), - KX_PYATTRIBUTE_STRING_RO("hitMaterial", KX_RaySensor, m_hitMaterial), - KX_PYATTRIBUTE_RO_FUNCTION("hitObject", KX_RaySensor, pyattr_get_hitobject), - { NULL } //Sentinel -}; - -PyObject *KX_RaySensor::pyattr_get_hitobject(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_RaySensor* self = static_cast(self_v); - if (self->m_hitObject) - return self->m_hitObject->GetProxy(); - - Py_RETURN_NONE; -} - -#endif // WITH_PYTHON diff --git a/source/gameengine/Ketsji/KX_RaySensor.h b/source/gameengine/Ketsji/KX_RaySensor.h deleted file mode 100644 index 1901bb04f86..00000000000 --- a/source/gameengine/Ketsji/KX_RaySensor.h +++ /dev/null @@ -1,109 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_RaySensor.h - * \ingroup ketsji - * \brief Cast a ray and feel for objects - */ - -#ifndef __KX_RAYSENSOR_H__ -#define __KX_RAYSENSOR_H__ - -#include "SCA_ISensor.h" -#include "MT_Point3.h" -#include "SCA_IScene.h" /* only for scene replace */ -#include "KX_Scene.h" /* only for scene replace */ - -#include "BLI_utildefines.h" - -struct KX_ClientObjectInfo; -class KX_RayCast; - -class KX_RaySensor : public SCA_ISensor -{ - Py_Header - STR_String m_propertyname; - bool m_bFindMaterial; - bool m_bXRay; - float m_distance; - class KX_Scene* m_scene; - bool m_bTriggered; - int m_axis; - bool m_rayHit; - float m_hitPosition[3]; - SCA_IObject* m_hitObject; - float m_hitNormal[3]; - float m_rayDirection[3]; - STR_String m_hitMaterial; - -public: - KX_RaySensor(class SCA_EventManager* eventmgr, - SCA_IObject* gameobj, - const STR_String& propname, - bool bFindMaterial, - bool bXRay, - double distance, - int axis, - class KX_Scene* ketsjiScene); - virtual ~KX_RaySensor(); - virtual CValue* GetReplica(); - - virtual bool Evaluate(); - virtual bool IsPositiveTrigger(); - virtual void Init(); - - /// \see KX_RayCast - bool RayHit(KX_ClientObjectInfo *client, KX_RayCast *result, void *UNUSED(data)); - /// \see KX_RayCast - bool NeedRayCast(KX_ClientObjectInfo *client, void *UNUSED(data)); - - virtual void Replace_IScene(SCA_IScene *val) - { - m_scene= static_cast(val); - } - - //Python Interface - // odd order, see: SENS_RAY_X_AXIS - enum RayAxis { - KX_RAY_AXIS_POS_X = 1, - KX_RAY_AXIS_POS_Y = 0, - KX_RAY_AXIS_POS_Z = 2, - KX_RAY_AXIS_NEG_X = 3, - KX_RAY_AXIS_NEG_Y = 4, - KX_RAY_AXIS_NEG_Z = 5, - }; - -#ifdef WITH_PYTHON - - /* Attributes */ - static PyObject *pyattr_get_hitobject(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - -#endif /* WITH_PYTHON */ - -}; - -#endif /* __KX_RAYSENSOR_H__ */ diff --git a/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.cpp b/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.cpp deleted file mode 100644 index bb38d8269b7..00000000000 --- a/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.cpp +++ /dev/null @@ -1,284 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_SCA_AddObjectActuator.cpp - * \ingroup ketsji - * - * Add an object when this actuator is triggered - */ - -/* Previously existed as: - * \source\gameengine\GameLogic\SCA_AddObjectActuator.cpp - * Please look here for revision history. */ - -#include "KX_SCA_AddObjectActuator.h" -#include "SCA_IScene.h" -#include "KX_GameObject.h" -#include "EXP_PyObjectPlus.h" - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -KX_SCA_AddObjectActuator::KX_SCA_AddObjectActuator(SCA_IObject *gameobj, - SCA_IObject *original, - int time, - SCA_IScene* scene, - const float *linvel, - bool linv_local, - const float *angvel, - bool angv_local) - : - SCA_IActuator(gameobj, KX_ACT_ADD_OBJECT), - m_OriginalObject(original), - m_scene(scene), - - m_localLinvFlag(linv_local), - m_localAngvFlag(angv_local) -{ - m_linear_velocity[0] = linvel[0]; - m_linear_velocity[1] = linvel[1]; - m_linear_velocity[2] = linvel[2]; - m_angular_velocity[0] = angvel[0]; - m_angular_velocity[1] = angvel[1]; - m_angular_velocity[2] = angvel[2]; - - if (m_OriginalObject) - m_OriginalObject->RegisterActuator(this); - - m_lastCreatedObject = NULL; - m_timeProp = time; -} - - - -KX_SCA_AddObjectActuator::~KX_SCA_AddObjectActuator() -{ - if (m_OriginalObject) - m_OriginalObject->UnregisterActuator(this); - if (m_lastCreatedObject) - m_lastCreatedObject->UnregisterActuator(this); -} - - - -bool KX_SCA_AddObjectActuator::Update() -{ - //bool result = false; /*unused*/ - bool bNegativeEvent = IsNegativeEvent(); - RemoveAllEvents(); - - if (bNegativeEvent) return false; // do nothing on negative events - - InstantAddObject(); - - - return false; -} - - - - -SCA_IObject* KX_SCA_AddObjectActuator::GetLastCreatedObject() const -{ - return m_lastCreatedObject; -} - - - -CValue* KX_SCA_AddObjectActuator::GetReplica() -{ - KX_SCA_AddObjectActuator* replica = new KX_SCA_AddObjectActuator(*this); - - if (replica == NULL) - return NULL; - - // this will copy properties and so on... - replica->ProcessReplica(); - - return replica; -} - -void KX_SCA_AddObjectActuator::ProcessReplica() -{ - if (m_OriginalObject) - m_OriginalObject->RegisterActuator(this); - m_lastCreatedObject=NULL; - SCA_IActuator::ProcessReplica(); -} - -bool KX_SCA_AddObjectActuator::UnlinkObject(SCA_IObject* clientobj) -{ - if (clientobj == m_OriginalObject) - { - // this object is being deleted, we cannot continue to track it. - m_OriginalObject = NULL; - return true; - } - if (clientobj == m_lastCreatedObject) - { - // this object is being deleted, we cannot continue to track it. - m_lastCreatedObject = NULL; - return true; - } - return false; -} - -void KX_SCA_AddObjectActuator::Relink(CTR_Map *obj_map) -{ - void **h_obj = (*obj_map)[m_OriginalObject]; - if (h_obj) { - if (m_OriginalObject) - m_OriginalObject->UnregisterActuator(this); - m_OriginalObject = (SCA_IObject*)(*h_obj); - m_OriginalObject->RegisterActuator(this); - } -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject KX_SCA_AddObjectActuator::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_SCA_AddObjectActuator", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &SCA_IActuator::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_SCA_AddObjectActuator::Methods[] = { - {"instantAddObject", (PyCFunction) KX_SCA_AddObjectActuator::sPyInstantAddObject, METH_NOARGS, NULL}, - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_SCA_AddObjectActuator::Attributes[] = { - KX_PYATTRIBUTE_RW_FUNCTION("object",KX_SCA_AddObjectActuator,pyattr_get_object,pyattr_set_object), - KX_PYATTRIBUTE_RO_FUNCTION("objectLastCreated",KX_SCA_AddObjectActuator,pyattr_get_objectLastCreated), - KX_PYATTRIBUTE_INT_RW("time",0,2000,true,KX_SCA_AddObjectActuator,m_timeProp), - KX_PYATTRIBUTE_FLOAT_ARRAY_RW("linearVelocity",-FLT_MAX,FLT_MAX,KX_SCA_AddObjectActuator,m_linear_velocity,3), - KX_PYATTRIBUTE_FLOAT_ARRAY_RW("angularVelocity",-FLT_MAX,FLT_MAX,KX_SCA_AddObjectActuator,m_angular_velocity,3), - { NULL } //Sentinel -}; - -PyObject *KX_SCA_AddObjectActuator::pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_SCA_AddObjectActuator* actuator = static_cast(self); - if (!actuator->m_OriginalObject) - Py_RETURN_NONE; - else - return actuator->m_OriginalObject->GetProxy(); -} - -int KX_SCA_AddObjectActuator::pyattr_set_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_SCA_AddObjectActuator* actuator = static_cast(self); - KX_GameObject *gameobj; - - if (!ConvertPythonToGameObject(actuator->GetLogicManager(), value, &gameobj, true, "actuator.object = value: KX_SCA_AddObjectActuator")) - return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error - - if (actuator->m_OriginalObject != NULL) - actuator->m_OriginalObject->UnregisterActuator(actuator); - - actuator->m_OriginalObject = (SCA_IObject*)gameobj; - - if (actuator->m_OriginalObject) - actuator->m_OriginalObject->RegisterActuator(actuator); - - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_SCA_AddObjectActuator::pyattr_get_objectLastCreated(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_SCA_AddObjectActuator* actuator = static_cast(self); - if (!actuator->m_lastCreatedObject) - Py_RETURN_NONE; - else - return actuator->m_lastCreatedObject->GetProxy(); -} - -PyObject *KX_SCA_AddObjectActuator::PyInstantAddObject() -{ - InstantAddObject(); - - Py_RETURN_NONE; -} - -#endif // WITH_PYTHON - -void KX_SCA_AddObjectActuator::InstantAddObject() -{ - if (m_OriginalObject) - { - // Add an identical object, with properties inherited from the original object - // Now it needs to be added to the current scene. - SCA_IObject* replica = m_scene->AddReplicaObject(m_OriginalObject,GetParent(),m_timeProp ); - KX_GameObject * game_obj = static_cast(replica); - game_obj->setLinearVelocity(m_linear_velocity, m_localLinvFlag); - game_obj->setAngularVelocity(m_angular_velocity,m_localAngvFlag); - game_obj->ResolveCombinedVelocities(m_linear_velocity, m_angular_velocity, m_localLinvFlag, m_localAngvFlag); - - // keep a copy of the last object, to allow python scripters to change it - if (m_lastCreatedObject) - { - //Let's not keep a reference to the object: it's bad, if the object is deleted - //this will force to keep a "zombie" in the game for no good reason. - //m_scene->DelayedReleaseObject(m_lastCreatedObject); - //m_lastCreatedObject->Release(); - - //Instead we use the registration mechanism - m_lastCreatedObject->UnregisterActuator(this); - m_lastCreatedObject = NULL; - } - - m_lastCreatedObject = replica; - // no reference - //m_lastCreatedObject->AddRef(); - // but registration - m_lastCreatedObject->RegisterActuator(this); - // finished using replica? then release it - replica->Release(); - } -} diff --git a/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.h b/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.h deleted file mode 100644 index 976f3c58d68..00000000000 --- a/source/gameengine/Ketsji/KX_SCA_AddObjectActuator.h +++ /dev/null @@ -1,133 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_SCA_AddObjectActuator.h - * \ingroup ketsji - * \attention Previously existed as: source/gameengine/GameLogic/SCA_AddObjectActuator.h - * Please look here for revision history. - */ - -#ifndef __KX_SCA_ADDOBJECTACTUATOR_H__ -#define __KX_SCA_ADDOBJECTACTUATOR_H__ - -/* Actuator tree */ -#include "SCA_IActuator.h" -#include "SCA_LogicManager.h" - -#include "MT_Vector3.h" - - -class SCA_IScene; - -class KX_SCA_AddObjectActuator : public SCA_IActuator -{ - Py_Header - - /// Time field: lifetime of the new object - int m_timeProp; - - /// Original object reference (object to replicate) - SCA_IObject* m_OriginalObject; - - /// Object will be added to the following scene - SCA_IScene* m_scene; - - /// Linear velocity upon creation of the object. - float m_linear_velocity[3]; - /// Apply the velocity locally - bool m_localLinvFlag; - - /// Angular velocity upon creation of the object. - float m_angular_velocity[3]; - /// Apply the velocity locally - bool m_localAngvFlag; - - - - - SCA_IObject* m_lastCreatedObject; - -public: - - /** - * This class also has the default constructors - * available. Use with care! - */ - - KX_SCA_AddObjectActuator( - SCA_IObject *gameobj, - SCA_IObject *original, - int time, - SCA_IScene* scene, - const float *linvel, - bool linv_local, - const float *angvel, - bool angv_local - ); - - ~KX_SCA_AddObjectActuator(void); - - CValue* - GetReplica( - ); - - virtual void - ProcessReplica(); - - virtual void Replace_IScene(SCA_IScene *val) - { - m_scene= val; - }; - - virtual bool - UnlinkObject(SCA_IObject* clientobj); - - virtual void - Relink(CTR_Map *obj_map); - - virtual bool - Update(); - - SCA_IObject * - GetLastCreatedObject( - ) const; - - void InstantAddObject(); - -#ifdef WITH_PYTHON - - KX_PYMETHOD_DOC_NOARGS(KX_SCA_AddObjectActuator,InstantAddObject); - - static PyObject *pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject *pyattr_get_objectLastCreated(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - -#endif /* WITH_PYTHON */ - -}; /* end of class KX_SCA_AddObjectActuator : public KX_EditObjectActuator */ - -#endif /* __KX_SCA_ADDOBJECTACTUATOR_H__ */ diff --git a/source/gameengine/Ketsji/KX_SCA_DynamicActuator.cpp b/source/gameengine/Ketsji/KX_SCA_DynamicActuator.cpp deleted file mode 100644 index a4220424c6f..00000000000 --- a/source/gameengine/Ketsji/KX_SCA_DynamicActuator.cpp +++ /dev/null @@ -1,160 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_SCA_DynamicActuator.cpp - * \ingroup ketsji - * Adjust dynamics settings for this object - */ - -/* Previously existed as: - * \source\gameengine\GameLogic\SCA_DynamicActuator.cpp - * Please look here for revision history. */ - -#include "KX_SCA_DynamicActuator.h" -#include "PHY_IPhysicsController.h" - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ - -PyTypeObject KX_SCA_DynamicActuator::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_SCA_DynamicActuator", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &SCA_IActuator::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_SCA_DynamicActuator::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_SCA_DynamicActuator::Attributes[] = { - KX_PYATTRIBUTE_SHORT_RW("mode",0,4,false,KX_SCA_DynamicActuator,m_dyn_operation), - KX_PYATTRIBUTE_FLOAT_RW("mass",0.0f,FLT_MAX,KX_SCA_DynamicActuator,m_setmass), - { NULL } //Sentinel -}; - -#endif // WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -KX_SCA_DynamicActuator::KX_SCA_DynamicActuator(SCA_IObject *gameobj, - short dyn_operation, - float setmass) : - - SCA_IActuator(gameobj, KX_ACT_DYNAMIC), - m_dyn_operation(dyn_operation), - m_setmass(setmass) -{ -} /* End of constructor */ - - -KX_SCA_DynamicActuator::~KX_SCA_DynamicActuator() -{ - // there's nothing to be done here, really.... -} /* end of destructor */ - - - -bool KX_SCA_DynamicActuator::Update() -{ - // bool result = false; /*unused*/ - KX_GameObject *obj = (KX_GameObject*) GetParent(); - bool bNegativeEvent = IsNegativeEvent(); - PHY_IPhysicsController* controller; - RemoveAllEvents(); - - if (bNegativeEvent) - return false; // do nothing on negative events - - if (!obj) - return false; // object not accessible, shouldnt happen - controller = obj->GetPhysicsController(); - if (!controller) - return false; // no physic object - - switch (m_dyn_operation) - { - case 0: - // Child objects must be static, so we block changing to dynamic - if (!obj->GetParent()) - controller->RestoreDynamics(); - break; - case 1: - controller->SuspendDynamics(); - break; - case 2: - controller->SetRigidBody(true); - break; - case 3: - controller->SetRigidBody(false); - break; - case 4: - controller->SetMass(m_setmass); - break; - } - - return false; -} - - - -CValue* KX_SCA_DynamicActuator::GetReplica() -{ - KX_SCA_DynamicActuator* replica = - new KX_SCA_DynamicActuator(*this); - - if (replica == NULL) - return NULL; - - replica->ProcessReplica(); - return replica; -}; - - -/* eof */ diff --git a/source/gameengine/Ketsji/KX_SCA_DynamicActuator.h b/source/gameengine/Ketsji/KX_SCA_DynamicActuator.h deleted file mode 100644 index 4eb337c54f5..00000000000 --- a/source/gameengine/Ketsji/KX_SCA_DynamicActuator.h +++ /dev/null @@ -1,76 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): Campbell Barton - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_SCA_DynamicActuator.h - * \ingroup ketsji - * \brief Add object to the game world on action of this actuator - */ - -#ifndef __KX_SCA_DYNAMICACTUATOR_H__ -#define __KX_SCA_DYNAMICACTUATOR_H__ - -#include "SCA_IActuator.h" -#include "SCA_PropertyActuator.h" -#include "SCA_LogicManager.h" - -#include "KX_GameObject.h" - -class KX_SCA_DynamicActuator : public SCA_IActuator -{ - Py_Header - - // dynamics operation to apply to the game object - short m_dyn_operation; - float m_setmass; - public: - KX_SCA_DynamicActuator( - SCA_IObject* gameobj, - short dyn_operation, - float setmass - ); - - ~KX_SCA_DynamicActuator( - ); - - CValue* - GetReplica( - ); - - virtual bool - Update(); - - //Python Interface - enum DynamicOperation { - KX_DYN_RESTORE_DYNAMICS = 0, - KX_DYN_DISABLE_DYNAMICS, - KX_DYN_ENABLE_RIGID_BODY, - KX_DYN_DISABLE_RIGID_BODY, - KX_DYN_SET_MASS, - }; -}; - -#endif diff --git a/source/gameengine/Ketsji/KX_SCA_EndObjectActuator.cpp b/source/gameengine/Ketsji/KX_SCA_EndObjectActuator.cpp deleted file mode 100644 index 81c9dc91603..00000000000 --- a/source/gameengine/Ketsji/KX_SCA_EndObjectActuator.cpp +++ /dev/null @@ -1,125 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_SCA_EndObjectActuator.cpp - * \ingroup ketsji - */ - - -// - -// Remove the actuator's parent when triggered -// -// Previously existed as: -// \source\gameengine\GameLogic\SCA_EndObjectActuator.cpp -// Please look here for revision history. - -#include "SCA_IActuator.h" -#include "KX_SCA_EndObjectActuator.h" -#include "SCA_IScene.h" - -KX_SCA_EndObjectActuator::KX_SCA_EndObjectActuator(SCA_IObject *gameobj, - SCA_IScene* scene): - SCA_IActuator(gameobj, KX_ACT_END_OBJECT), - m_scene(scene) -{ - // intentionally empty -} /* End of constructor */ - - - -KX_SCA_EndObjectActuator::~KX_SCA_EndObjectActuator() -{ - // there's nothing to be done here, really.... -} /* end of destructor */ - - - -bool KX_SCA_EndObjectActuator::Update() -{ - // bool result = false; /*unused*/ - bool bNegativeEvent = IsNegativeEvent(); - RemoveAllEvents(); - - if (bNegativeEvent) - return false; // do nothing on negative events - m_scene->DelayedRemoveObject(GetParent()); - - return false; -} - - - -CValue* KX_SCA_EndObjectActuator::GetReplica() -{ - KX_SCA_EndObjectActuator* replica = - new KX_SCA_EndObjectActuator(*this); - if (replica == NULL) return NULL; - - replica->ProcessReplica(); - return replica; -}; - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions : integration hooks */ -/* ------------------------------------------------------------------------- */ - -PyTypeObject KX_SCA_EndObjectActuator::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_SCA_EndObjectActuator", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &SCA_IActuator::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_SCA_EndObjectActuator::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_SCA_EndObjectActuator::Attributes[] = { - { NULL } //Sentinel -}; - -#endif // WITH_PYTHON - -/* eof */ diff --git a/source/gameengine/Ketsji/KX_SCA_EndObjectActuator.h b/source/gameengine/Ketsji/KX_SCA_EndObjectActuator.h deleted file mode 100644 index 3399ed90667..00000000000 --- a/source/gameengine/Ketsji/KX_SCA_EndObjectActuator.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_SCA_EndObjectActuator.h - * \ingroup ketsji - * \brief Add object to the game world on action of this actuator - * \attention Previously existed as: source/gameengine/GameLogic/SCA_EndObjectActuator.h - * Please look here for revision history. - */ - -#ifndef __KX_SCA_ENDOBJECTACTUATOR_H__ -#define __KX_SCA_ENDOBJECTACTUATOR_H__ - -#include "SCA_IActuator.h" - -class SCA_IScene; - -class KX_SCA_EndObjectActuator : public SCA_IActuator -{ - Py_Header - SCA_IScene* m_scene; - - public: - KX_SCA_EndObjectActuator( - SCA_IObject* gameobj, - SCA_IScene* scene - ); - - ~KX_SCA_EndObjectActuator(); - - CValue* - GetReplica( - ); - - virtual bool - Update(); - - virtual void Replace_IScene(SCA_IScene *val) - { - m_scene= val; - }; - - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - -}; /* end of class KX_EditObjectActuator : public SCA_PropertyActuator */ - -#endif - diff --git a/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.cpp b/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.cpp deleted file mode 100644 index 1bf76de0b40..00000000000 --- a/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.cpp +++ /dev/null @@ -1,182 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.cpp - * \ingroup ketsji - * - * Replace the mesh for this actuator's parent - */ - -// -// Previously existed as: - -// \source\gameengine\GameLogic\SCA_ReplaceMeshActuator.cpp - -// Please look here for revision history. - -#include - -#include "KX_SCA_ReplaceMeshActuator.h" -#include "KX_MeshProxy.h" - -#include "EXP_PyObjectPlus.h" - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ - -PyTypeObject KX_SCA_ReplaceMeshActuator::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_SCA_ReplaceMeshActuator", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &SCA_IActuator::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_SCA_ReplaceMeshActuator::Methods[] = { - KX_PYMETHODTABLE(KX_SCA_ReplaceMeshActuator, instantReplaceMesh), - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_SCA_ReplaceMeshActuator::Attributes[] = { - KX_PYATTRIBUTE_RW_FUNCTION("mesh", KX_SCA_ReplaceMeshActuator, pyattr_get_mesh, pyattr_set_mesh), - KX_PYATTRIBUTE_BOOL_RW ("useDisplayMesh", KX_SCA_ReplaceMeshActuator, m_use_gfx), - KX_PYATTRIBUTE_BOOL_RW ("usePhysicsMesh", KX_SCA_ReplaceMeshActuator, m_use_phys), - { NULL } //Sentinel -}; - -PyObject *KX_SCA_ReplaceMeshActuator::pyattr_get_mesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_SCA_ReplaceMeshActuator* actuator = static_cast(self); - if (!actuator->m_mesh) - Py_RETURN_NONE; - KX_MeshProxy* meshproxy = new KX_MeshProxy(actuator->m_mesh); - return meshproxy->NewProxy(true); -} - -int KX_SCA_ReplaceMeshActuator::pyattr_set_mesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_SCA_ReplaceMeshActuator* actuator = static_cast(self); - RAS_MeshObject* new_mesh; - - if (!ConvertPythonToMesh(actuator->GetLogicManager(), value, &new_mesh, true, "actuator.mesh = value: KX_SCA_ReplaceMeshActuator")) - return PY_SET_ATTR_FAIL; - - actuator->m_mesh = new_mesh; - return PY_SET_ATTR_SUCCESS; -} - -KX_PYMETHODDEF_DOC(KX_SCA_ReplaceMeshActuator, instantReplaceMesh, -"instantReplaceMesh() : immediately replace mesh without delay\n") -{ - InstantReplaceMesh(); - Py_RETURN_NONE; -} - -#endif // WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -KX_SCA_ReplaceMeshActuator::KX_SCA_ReplaceMeshActuator(SCA_IObject *gameobj, - class RAS_MeshObject *mesh, - SCA_IScene* scene, - bool use_gfx, - bool use_phys) : - - SCA_IActuator(gameobj, KX_ACT_REPLACE_MESH), - m_mesh(mesh), - m_scene(scene), - m_use_gfx(use_gfx), - m_use_phys(use_phys) -{ -} /* End of constructor */ - - - -KX_SCA_ReplaceMeshActuator::~KX_SCA_ReplaceMeshActuator() -{ - // there's nothing to be done here, really.... -} /* end of destructor */ - - - -bool KX_SCA_ReplaceMeshActuator::Update() -{ - // bool result = false; /*unused*/ - bool bNegativeEvent = IsNegativeEvent(); - RemoveAllEvents(); - - if (bNegativeEvent) - return false; // do nothing on negative events - - if (m_mesh || m_use_phys) /* NULL mesh is ok if were updating physics */ - m_scene->ReplaceMesh(GetParent(),m_mesh, m_use_gfx, m_use_phys); - - return false; -} - - - -CValue* KX_SCA_ReplaceMeshActuator::GetReplica() -{ - KX_SCA_ReplaceMeshActuator* replica = - new KX_SCA_ReplaceMeshActuator(*this); - - if (replica == NULL) - return NULL; - - replica->ProcessReplica(); - - return replica; -}; - -void KX_SCA_ReplaceMeshActuator::InstantReplaceMesh() -{ - if (m_mesh) m_scene->ReplaceMesh(GetParent(),m_mesh, m_use_gfx, m_use_phys); -} - -/* eof */ diff --git a/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.h b/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.h deleted file mode 100644 index 4370b5d4a4f..00000000000 --- a/source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.h +++ /dev/null @@ -1,96 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_SCA_ReplaceMeshActuator.h - * \ingroup ketsji - * \brief Add object to the game world on action of this actuator - * \attention Previously existed as: source/gameengine/GameLogic/SCA_ReplaceMeshActuator.h - * Please look here for revision history. - */ - -#ifndef __KX_SCA_REPLACEMESHACTUATOR_H__ -#define __KX_SCA_REPLACEMESHACTUATOR_H__ - -#include "SCA_IActuator.h" -#include "SCA_PropertyActuator.h" -#include "SCA_LogicManager.h" -#include "SCA_IScene.h" - -#include "RAS_MeshObject.h" - -class KX_SCA_ReplaceMeshActuator : public SCA_IActuator -{ - Py_Header - - // mesh reference (mesh to replace) - RAS_MeshObject* m_mesh; - SCA_IScene* m_scene; - bool m_use_gfx; - bool m_use_phys; - - public: - KX_SCA_ReplaceMeshActuator( - SCA_IObject* gameobj, - RAS_MeshObject *mesh, - SCA_IScene* scene, - bool use_gfx, - bool use_phys - ); - - ~KX_SCA_ReplaceMeshActuator( - ); - - CValue* - GetReplica( - ); - - virtual bool - Update(); - - void InstantReplaceMesh(); - -#ifdef WITH_PYTHON - - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - - virtual void Replace_IScene(SCA_IScene *val) - { - m_scene= val; - }; - - static PyObject *pyattr_get_mesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_mesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - - KX_PYMETHOD_DOC(KX_SCA_ReplaceMeshActuator,instantReplaceMesh); - -#endif /* WITH_PYTHON */ - -}; - -#endif /* __KX_SCA_REPLACEMESHACTUATOR_H__ */ diff --git a/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp b/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp deleted file mode 100644 index 5a13cf5440d..00000000000 --- a/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp +++ /dev/null @@ -1,155 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp - * \ingroup ketsji - */ - - -#include - -#include "KX_SG_BoneParentNodeRelationship.h" - -#include "MT_Matrix4x4.h" -#include "BL_ArmatureObject.h" - - -/** - * Implementation of classes defined in KX_SG_BoneParentNodeRelationship.h - */ - -/** - * first of all KX_SG_BoneParentRelation - */ - - KX_BoneParentRelation * -KX_BoneParentRelation:: -New(Bone* bone -) { - return new KX_BoneParentRelation(bone); -} - - bool -KX_BoneParentRelation:: -UpdateChildCoordinates( - SG_Spatial * child, - const SG_Spatial * parent, - bool& parentUpdated -) { - MT_assert(child != NULL); - - // This way of accessing child coordinates is a bit cumbersome - // be nice to have non constant reference access to these values. - - const MT_Vector3 & child_scale = child->GetLocalScale(); - const MT_Point3 & child_pos = child->GetLocalPosition(); - const MT_Matrix3x3 & child_rotation = child->GetLocalOrientation(); - // we don't know if the armature has been updated or not, assume yes - parentUpdated = true; - - // the childs world locations which we will update. - - MT_Vector3 child_w_scale; - MT_Point3 child_w_pos; - MT_Matrix3x3 child_w_rotation; - - bool valid_parent_transform = false; - - if (parent) - { - BL_ArmatureObject *armature = (BL_ArmatureObject*)(parent->GetSGClientObject()); - if (armature) - { - MT_Matrix4x4 parent_matrix; - if (armature->GetBoneMatrix(m_bone, parent_matrix)) - { - // Get the child's transform, and the bone matrix. - MT_Matrix4x4 child_transform ( - MT_Transform(child_pos + MT_Vector3(0.0f, armature->GetBoneLength(m_bone), 0.0f), - child_rotation.scaled( - child_scale[0], - child_scale[1], - child_scale[2]))); - - // The child's world transform is parent * child - parent_matrix = parent->GetWorldTransform() * parent_matrix; - child_transform = parent_matrix * child_transform; - - // Recompute the child transform components from the transform. - child_w_scale.setValue( - MT_Vector3(child_transform[0][0], child_transform[0][1], child_transform[0][2]).length(), - MT_Vector3(child_transform[1][0], child_transform[1][1], child_transform[1][2]).length(), - MT_Vector3(child_transform[2][0], child_transform[2][1], child_transform[2][2]).length()); - child_w_rotation.setValue(child_transform[0][0], child_transform[0][1], child_transform[0][2], - child_transform[1][0], child_transform[1][1], child_transform[1][2], - child_transform[2][0], child_transform[2][1], child_transform[2][2]); - child_w_rotation.scale(1.0f/child_w_scale[0], 1.0f/child_w_scale[1], 1.0f/child_w_scale[2]); - - child_w_pos = MT_Point3(child_transform[0][3], child_transform[1][3], child_transform[2][3]); - - valid_parent_transform = true; - } - } - } - - if (valid_parent_transform) - { - child->SetWorldScale(child_w_scale); - child->SetWorldPosition(child_w_pos); - child->SetWorldOrientation(child_w_rotation); - } - else { - child->SetWorldFromLocalTransform(); - } - child->ClearModified(); - // this node must always be updated, so reschedule it for next time - child->ActivateRecheduleUpdateCallback(); - return valid_parent_transform; -} - - SG_ParentRelation * -KX_BoneParentRelation:: -NewCopy( -) { - KX_BoneParentRelation* bone_parent = new KX_BoneParentRelation(m_bone); - return bone_parent; -} - -KX_BoneParentRelation:: -~KX_BoneParentRelation( -) { - //nothing to do -} - - -KX_BoneParentRelation:: -KX_BoneParentRelation(Bone* bone -) -: m_bone(bone) -{ - // nothing to do -} diff --git a/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.h b/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.h deleted file mode 100644 index 6f4fd482198..00000000000 --- a/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.h +++ /dev/null @@ -1,96 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - * - */ - -/** \file KX_SG_BoneParentNodeRelationship.h - * \ingroup ketsji - */ - -#ifndef __KX_SG_BONEPARENTNODERELATIONSHIP_H__ -#define __KX_SG_BONEPARENTNODERELATIONSHIP_H__ - -#include "SG_Spatial.h" -#include "SG_ParentRelation.h" - -struct Bone; - -/** - * Bone parent relationship parents a child SG_Spatial frame to a - * bone in an armature object. - */ -class KX_BoneParentRelation : public SG_ParentRelation -{ - -public : - /** - * Allocate and construct a new KX_SG_BoneParentRelation - * on the heap. - * - * bone is the bone id to use. Currently it is a pointer - * to a Blender struct Bone - this should be fixed if - */ - - static - KX_BoneParentRelation * - New(Bone* bone - ); - - /** - * Updates the childs world coordinates relative to the parent's - * world coordinates. - * - * Parent should be a BL_ArmatureObject. - */ - bool - UpdateChildCoordinates( - SG_Spatial * child, - const SG_Spatial * parent, - bool& parentUpdated - ); - - /** - * Create a copy of this relationship - */ - SG_ParentRelation * - NewCopy( - ); - - ~KX_BoneParentRelation( - ); - -private : - Bone* m_bone; - KX_BoneParentRelation(Bone* bone - ); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_BoneParentRelation") -#endif -}; - -#endif diff --git a/source/gameengine/Ketsji/KX_SG_NodeRelationships.cpp b/source/gameengine/Ketsji/KX_SG_NodeRelationships.cpp deleted file mode 100644 index e80de76861e..00000000000 --- a/source/gameengine/Ketsji/KX_SG_NodeRelationships.cpp +++ /dev/null @@ -1,298 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_SG_NodeRelationships.cpp - * \ingroup ketsji - */ - - -#include "KX_SG_NodeRelationships.h" - -/** - * Implementation of classes defined in KX_SG_NodeRelationships.h - */ - -/** - * first of all KX_NormalParentRelation - */ - - KX_NormalParentRelation * -KX_NormalParentRelation:: -New( -) { - return new KX_NormalParentRelation(); -} - - bool -KX_NormalParentRelation:: -UpdateChildCoordinates( - SG_Spatial * child, - const SG_Spatial * parent, - bool& parentUpdated -) { - MT_assert(child != NULL); - - if (!parentUpdated && !child->IsModified()) - return false; - - parentUpdated = true; - - if (parent==NULL) { /* Simple case */ - child->SetWorldFromLocalTransform(); - child->ClearModified(); - return true; //false; - } - else { - // the childs world locations which we will update. - const MT_Vector3 & p_world_scale = parent->GetWorldScaling(); - const MT_Point3 & p_world_pos = parent->GetWorldPosition(); - const MT_Matrix3x3 & p_world_rotation = parent->GetWorldOrientation(); - - child->SetWorldScale(p_world_scale * child->GetLocalScale()); - child->SetWorldOrientation(p_world_rotation * child->GetLocalOrientation()); - child->SetWorldPosition(p_world_pos + p_world_scale * (p_world_rotation * child->GetLocalPosition())); - child->ClearModified(); - return true; - } -} - - SG_ParentRelation * -KX_NormalParentRelation:: -NewCopy( -) { - return new KX_NormalParentRelation(); -} - -KX_NormalParentRelation:: -~KX_NormalParentRelation( -) { - //nothing to do -} - - -KX_NormalParentRelation:: -KX_NormalParentRelation( -) { - // nothing to do -} - -/** - * Next KX_VertexParentRelation - */ - - - KX_VertexParentRelation * -KX_VertexParentRelation:: -New( -) { - return new KX_VertexParentRelation(); -} - -/** - * Method inherited from KX_ParentRelation - */ - - bool -KX_VertexParentRelation:: -UpdateChildCoordinates( - SG_Spatial * child, - const SG_Spatial * parent, - bool& parentUpdated -) { - - MT_assert(child != NULL); - - if (!parentUpdated && !child->IsModified()) - return false; - - child->SetWorldScale(child->GetLocalScale()); - - if (parent) - child->SetWorldPosition(child->GetLocalPosition()+parent->GetWorldPosition()); - else - child->SetWorldPosition(child->GetLocalPosition()); - - child->SetWorldOrientation(child->GetLocalOrientation()); - child->ClearModified(); - return true; //parent != NULL; -} - -/** - * Method inherited from KX_ParentRelation - */ - - SG_ParentRelation * -KX_VertexParentRelation:: -NewCopy( -) { - return new KX_VertexParentRelation(); -}; - -KX_VertexParentRelation:: -~KX_VertexParentRelation( -) { - //nothing to do -} - - -KX_VertexParentRelation:: -KX_VertexParentRelation( -) { - //nothing to do -} - - -/** - * Slow parent relationship - */ - - KX_SlowParentRelation * -KX_SlowParentRelation:: -New( - MT_Scalar relaxation -) { - return new KX_SlowParentRelation(relaxation); -} - -/** - * Method inherited from KX_ParentRelation - */ - - bool -KX_SlowParentRelation:: -UpdateChildCoordinates( - SG_Spatial * child, - const SG_Spatial * parent, - bool& parentUpdated -) { - MT_assert(child != NULL); - - // the child will move even if the parent is not - parentUpdated = true; - - const MT_Vector3 & child_scale = child->GetLocalScale(); - const MT_Point3 & child_pos = child->GetLocalPosition(); - const MT_Matrix3x3 & child_rotation = child->GetLocalOrientation(); - - // the childs world locations which we will update. - - MT_Vector3 child_w_scale; - MT_Point3 child_w_pos; - MT_Matrix3x3 child_w_rotation; - - if (parent) { - - // This is a slow parent relation - // first compute the normal child world coordinates. - - MT_Vector3 child_n_scale; - MT_Point3 child_n_pos; - MT_Matrix3x3 child_n_rotation; - - const MT_Vector3 & p_world_scale = parent->GetWorldScaling(); - const MT_Point3 & p_world_pos = parent->GetWorldPosition(); - const MT_Matrix3x3 & p_world_rotation = parent->GetWorldOrientation(); - - child_n_scale = p_world_scale * child_scale; - child_n_rotation = p_world_rotation * child_rotation; - - child_n_pos = p_world_pos + p_world_scale * - (p_world_rotation * child_pos); - - - if (m_initialized) { - - // get the current world positions - - child_w_scale = child->GetWorldScaling(); - child_w_pos = child->GetWorldPosition(); - child_w_rotation = child->GetWorldOrientation(); - - // now 'interpolate' the normal coordinates with the last - // world coordinates to get the new world coordinates. - - MT_Scalar weight = MT_Scalar(1)/(m_relax + 1); - child_w_scale = (m_relax * child_w_scale + child_n_scale) * weight; - child_w_pos = (m_relax * child_w_pos + child_n_pos) * weight; - // for rotation we must go through quaternion - MT_Quaternion child_w_quat = child_w_rotation.getRotation().slerp(child_n_rotation.getRotation(), weight); - child_w_rotation.setRotation(child_w_quat); - //FIXME: update physics controller. - } else { - child_w_scale = child_n_scale; - child_w_pos = child_n_pos; - child_w_rotation = child_n_rotation; - m_initialized = true; - } - - } else { - - child_w_scale = child_scale; - child_w_pos = child_pos; - child_w_rotation = child_rotation; - } - - child->SetWorldScale(child_w_scale); - child->SetWorldPosition(child_w_pos); - child->SetWorldOrientation(child_w_rotation); - child->ClearModified(); - // this node must always be updated, so reschedule it for next time - child->ActivateRecheduleUpdateCallback(); - - return true; //parent != NULL; -} - -/** - * Method inherited from KX_ParentRelation - */ - - SG_ParentRelation * -KX_SlowParentRelation:: -NewCopy( -) { - return new KX_SlowParentRelation(m_relax); -} - -KX_SlowParentRelation:: -KX_SlowParentRelation( - MT_Scalar relaxation -): - m_relax(relaxation), - m_initialized(false) -{ - //nothing to do -} - -KX_SlowParentRelation:: -~KX_SlowParentRelation( -) { - //nothing to do -} - - - - diff --git a/source/gameengine/Ketsji/KX_SG_NodeRelationships.h b/source/gameengine/Ketsji/KX_SG_NodeRelationships.h deleted file mode 100644 index 5d777f5028f..00000000000 --- a/source/gameengine/Ketsji/KX_SG_NodeRelationships.h +++ /dev/null @@ -1,231 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - * - */ - -/** \file KX_SG_NodeRelationships.h - * \ingroup ketsji - * \section KX_SG_NodeRelationships - * This file provides common concrete implementations of - * SG_ParentRelation used by the game engine. These are - * KX_SlowParentRelation a slow parent relationship. - * KX_NormalParentRelation a normal parent relationship where - * orientation and position are inherited from the parent by - * the child. - * KX_VertexParentRelation only location information is - * inherited by the child. - */ - -#ifndef __KX_SG_NODERELATIONSHIPS_H__ -#define __KX_SG_NODERELATIONSHIPS_H__ - -#include "SG_Spatial.h" -#include "SG_ParentRelation.h" - -class KX_NormalParentRelation : public SG_ParentRelation -{ - -public : - /** - * Allocate and construct a new KX_NormalParentRelation - * on the heap. - */ - - static - KX_NormalParentRelation * - New( - ); - - /** - * Method inherited from KX_ParentRelation - */ - - bool - UpdateChildCoordinates( - SG_Spatial * child, - const SG_Spatial * parent, - bool& parentUpdated - ); - - /** - * Method inherited from KX_ParentRelation - */ - - SG_ParentRelation * - NewCopy( - ); - - ~KX_NormalParentRelation( - ); - -private : - - KX_NormalParentRelation( - ); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_NormalParentRelation") -#endif -}; - - -class KX_VertexParentRelation : public SG_ParentRelation -{ - -public : - - /** - * Allocate and construct a new KX_VertexParentRelation - * on the heap. - */ - - static - KX_VertexParentRelation * - New( - ); - - /** - * Method inherited from KX_ParentRelation - */ - - bool - UpdateChildCoordinates( - SG_Spatial * child, - const SG_Spatial * parent, - bool& parentUpdated - ); - - /** - * Method inherited from KX_ParentRelation - */ - - SG_ParentRelation * - NewCopy( - ); - - ~KX_VertexParentRelation( - ); - - bool - IsVertexRelation( - ) { - return true; - } - -private : - - KX_VertexParentRelation( - ); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_VertexParentRelation") -#endif -}; - - -class KX_SlowParentRelation : public SG_ParentRelation -{ - -public : - - /** - * Allocate and construct a new KX_VertexParentRelation - * on the heap. - */ - - static - KX_SlowParentRelation * - New( - MT_Scalar relaxation - ); - - /** - * Method inherited from KX_ParentRelation - */ - - bool - UpdateChildCoordinates( - SG_Spatial * child, - const SG_Spatial * parent, - bool& parentUpdated - ); - - /** - * Method inherited from KX_ParentRelation - */ - - SG_ParentRelation * - NewCopy( - ); - - MT_Scalar - GetTimeOffset( - ) { return m_relax; } - - void - SetTimeOffset( - MT_Scalar relaxation - ) { m_relax = relaxation; } - - ~KX_SlowParentRelation( - ); - - bool - IsSlowRelation( - ) { - return true; - } - -private : - - KX_SlowParentRelation( - MT_Scalar relaxation - ); - - // the relaxation coefficient. - - MT_Scalar m_relax; - - /** - * Looks like a hack flag to me. - * We need to compute valid world coordinates the first - * time we update spatial data of the child. This is done - * by just doing a normal parent relation the first time - * UpdateChildCoordinates is called and then doing the - * slow parent relation - */ - - bool m_initialized; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_SlowParentRelation") -#endif -}; - -#endif diff --git a/source/gameengine/Ketsji/KX_ScalarInterpolator.cpp b/source/gameengine/Ketsji/KX_ScalarInterpolator.cpp deleted file mode 100644 index e234a9621b8..00000000000 --- a/source/gameengine/Ketsji/KX_ScalarInterpolator.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_ScalarInterpolator.cpp - * \ingroup ketsji - */ - - -#include "KX_ScalarInterpolator.h" -#include "KX_IScalarInterpolator.h" - -void KX_ScalarInterpolator::Execute(float currentTime) const -{ - *m_target = m_ipo->GetValue(currentTime); -} diff --git a/source/gameengine/Ketsji/KX_ScalarInterpolator.h b/source/gameengine/Ketsji/KX_ScalarInterpolator.h deleted file mode 100644 index 5d8c3163376..00000000000 --- a/source/gameengine/Ketsji/KX_ScalarInterpolator.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_ScalarInterpolator.h - * \ingroup ketsji - */ - -#ifndef __KX_SCALARINTERPOLATOR_H__ -#define __KX_SCALARINTERPOLATOR_H__ - -#include "MT_Scalar.h" -#include "KX_IInterpolator.h" - -class KX_IScalarInterpolator; - -class KX_ScalarInterpolator : public KX_IInterpolator { -public: - KX_ScalarInterpolator(MT_Scalar* target, - KX_IScalarInterpolator *ipo) : - m_target(target), - m_ipo(ipo) - {} - - virtual ~KX_ScalarInterpolator() {} - virtual void Execute(float currentTime) const; - void SetNewTarget(MT_Scalar* newtarget) - { - m_target=newtarget; - } - MT_Scalar* GetTarget() - { - return m_target; - } -private: - MT_Scalar* m_target; - KX_IScalarInterpolator *m_ipo; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_ScalarInterpolator") -#endif -}; - -#endif - diff --git a/source/gameengine/Ketsji/KX_ScalingInterpolator.cpp b/source/gameengine/Ketsji/KX_ScalingInterpolator.cpp deleted file mode 100644 index dd40cbd22fd..00000000000 --- a/source/gameengine/Ketsji/KX_ScalingInterpolator.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_ScalingInterpolator.cpp - * \ingroup ketsji - */ - - -#include "KX_ScalingInterpolator.h" -#include "MT_Vector3.h" -#include "KX_IScalarInterpolator.h" - -void KX_ScalingInterpolator::Execute(float currentTime) const -{ - m_target.setValue(m_ipos[0]->GetValue(currentTime), - m_ipos[1]->GetValue(currentTime), - m_ipos[2]->GetValue(currentTime)); -} diff --git a/source/gameengine/Ketsji/KX_ScalingInterpolator.h b/source/gameengine/Ketsji/KX_ScalingInterpolator.h deleted file mode 100644 index 52b6d0cf8cc..00000000000 --- a/source/gameengine/Ketsji/KX_ScalingInterpolator.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_ScalingInterpolator.h - * \ingroup ketsji - */ - -#ifndef __KX_SCALINGINTERPOLATOR_H__ -#define __KX_SCALINGINTERPOLATOR_H__ - -#include "KX_IInterpolator.h" - -class MT_Vector3; -class KX_IScalarInterpolator; - -class KX_ScalingInterpolator : public KX_IInterpolator { -public: - KX_ScalingInterpolator(MT_Vector3& target, - KX_IScalarInterpolator *ipos[]) - : m_target(target) - { - m_ipos[0] = ipos[0]; - m_ipos[1] = ipos[1]; - m_ipos[2] = ipos[2]; - } - - virtual void Execute(float currentTime) const; - -private: - MT_Vector3& m_target; - KX_IScalarInterpolator *m_ipos[3]; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_ScalingInterpolator") -#endif -}; - -#endif - diff --git a/source/gameengine/Ketsji/KX_Scene.cpp b/source/gameengine/Ketsji/KX_Scene.cpp deleted file mode 100644 index 0e6b04c6df5..00000000000 --- a/source/gameengine/Ketsji/KX_Scene.cpp +++ /dev/null @@ -1,2644 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - * Ketsji scene. Holds references to all scene data. - */ - -/** \file gameengine/Ketsji/KX_Scene.cpp - * \ingroup ketsji - */ - - -#ifdef _MSC_VER -# pragma warning (disable:4786) -#endif - -#include - -#include "KX_Scene.h" -#include "KX_PythonInit.h" -#include "MT_assert.h" -#include "KX_KetsjiEngine.h" -#include "KX_BlenderMaterial.h" -#include "KX_FontObject.h" -#include "RAS_IPolygonMaterial.h" -#include "EXP_ListValue.h" -#include "SCA_LogicManager.h" -#include "SCA_TimeEventManager.h" -//#include "SCA_AlwaysEventManager.h" -//#include "SCA_RandomEventManager.h" -//#include "KX_RayEventManager.h" -#include "SCA_2DFilterActuator.h" -#include "SCA_PythonController.h" -#include "KX_TouchEventManager.h" -#include "SCA_KeyboardManager.h" -#include "SCA_MouseManager.h" -//#include "SCA_PropertyEventManager.h" -#include "SCA_ActuatorEventManager.h" -#include "SCA_BasicEventManager.h" -#include "KX_Camera.h" -#include "SCA_JoystickManager.h" -#include "KX_PyMath.h" -#include "RAS_MeshObject.h" -#include "SCA_IScene.h" - -#include "RAS_IRasterizer.h" -#include "RAS_ICanvas.h" -#include "RAS_BucketManager.h" - -#include "EXP_FloatValue.h" -#include "SCA_IController.h" -#include "SCA_IActuator.h" -#include "SG_Node.h" -#include "BL_System.h" -#include "SG_Controller.h" -#include "SG_IObject.h" -#include "SG_Tree.h" -#include "DNA_group_types.h" -#include "DNA_scene_types.h" -#include "DNA_property_types.h" - -#include "KX_SG_NodeRelationships.h" - -#include "KX_NetworkEventManager.h" -#include "NG_NetworkScene.h" -#include "PHY_IPhysicsEnvironment.h" -#include "PHY_IGraphicController.h" -#include "PHY_IPhysicsController.h" -#include "KX_BlenderSceneConverter.h" -#include "KX_MotionState.h" - -#include "BL_ModifierDeformer.h" -#include "BL_ShapeDeformer.h" -#include "BL_DeformableGameObject.h" -#include "KX_ObstacleSimulation.h" - -#ifdef WITH_BULLET -# include "KX_SoftBodyDeformer.h" -#endif - -#ifdef WITH_PYTHON -# include "EXP_PythonCallBack.h" -#endif - -#include "KX_Light.h" - -#include "BKE_group.h" -#include "BLI_task.h" - -static void *KX_SceneReplicationFunc(SG_IObject* node,void* gameobj,void* scene) -{ - KX_GameObject* replica = ((KX_Scene*)scene)->AddNodeReplicaObject(node,(KX_GameObject*)gameobj); - - if (replica) - replica->Release(); - - return (void*)replica; -} - -static void *KX_SceneDestructionFunc(SG_IObject* node,void* gameobj,void* scene) -{ - ((KX_Scene*)scene)->RemoveNodeDestructObject(node,(KX_GameObject*)gameobj); - - return NULL; -}; - -bool KX_Scene::KX_ScenegraphUpdateFunc(SG_IObject* node,void* gameobj,void* scene) -{ - return ((SG_Node*)node)->Schedule(((KX_Scene*)scene)->m_sghead); -} - -bool KX_Scene::KX_ScenegraphRescheduleFunc(SG_IObject* node,void* gameobj,void* scene) -{ - return ((SG_Node*)node)->Reschedule(((KX_Scene*)scene)->m_sghead); -} - -SG_Callbacks KX_Scene::m_callbacks = SG_Callbacks( - KX_SceneReplicationFunc, - KX_SceneDestructionFunc, - KX_GameObject::UpdateTransformFunc, - KX_Scene::KX_ScenegraphUpdateFunc, - KX_Scene::KX_ScenegraphRescheduleFunc); - -// temporarily var until there is a button in the userinterface -// (defined in KX_PythonInit.cpp) -extern bool gUseVisibilityTemp; - -KX_Scene::KX_Scene(class SCA_IInputDevice* keyboarddevice, - class SCA_IInputDevice* mousedevice, - class NG_NetworkDeviceInterface *ndi, - const STR_String& sceneName, - Scene *scene, - class RAS_ICanvas* canvas): - PyObjectPlus(), - m_keyboardmgr(NULL), - m_mousemgr(NULL), - m_sceneConverter(NULL), - m_physicsEnvironment(0), - m_sceneName(sceneName), - m_networkDeviceInterface(ndi), - m_active_camera(NULL), - m_ueberExecutionPriority(0), - m_blenderScene(scene), - m_isActivedHysteresis(false), - m_lodHysteresisValue(0) -{ - m_suspendedtime = 0.0; - m_suspendeddelta = 0.0; - - m_dbvt_culling = false; - m_dbvt_occlusion_res = 0; - m_activity_culling = false; - m_suspend = false; - m_isclearingZbuffer = true; - m_isShadowDone = false; - m_tempObjectList = new CListValue(); - m_objectlist = new CListValue(); - m_parentlist = new CListValue(); - m_lightlist= new CListValue(); - m_inactivelist = new CListValue(); - m_euthanasyobjects = new CListValue(); - m_animatedlist = new CListValue(); - - m_logicmgr = new SCA_LogicManager(); - - m_timemgr = new SCA_TimeEventManager(m_logicmgr); - m_keyboardmgr = new SCA_KeyboardManager(m_logicmgr,keyboarddevice); - m_mousemgr = new SCA_MouseManager(m_logicmgr,mousedevice, canvas); - - //SCA_AlwaysEventManager* alwaysmgr = new SCA_AlwaysEventManager(m_logicmgr); - //SCA_PropertyEventManager* propmgr = new SCA_PropertyEventManager(m_logicmgr); - SCA_ActuatorEventManager* actmgr = new SCA_ActuatorEventManager(m_logicmgr); - //SCA_RandomEventManager* rndmgr = new SCA_RandomEventManager(m_logicmgr); - SCA_BasicEventManager* basicmgr = new SCA_BasicEventManager(m_logicmgr); - //KX_RayEventManager* raymgr = new KX_RayEventManager(m_logicmgr); - - KX_NetworkEventManager* netmgr = new KX_NetworkEventManager(m_logicmgr, ndi); - - - - //m_logicmgr->RegisterEventManager(alwaysmgr); - //m_logicmgr->RegisterEventManager(propmgr); - m_logicmgr->RegisterEventManager(actmgr); - m_logicmgr->RegisterEventManager(m_keyboardmgr); - m_logicmgr->RegisterEventManager(m_mousemgr); - m_logicmgr->RegisterEventManager(m_timemgr); - //m_logicmgr->RegisterEventManager(rndmgr); - //m_logicmgr->RegisterEventManager(raymgr); - m_logicmgr->RegisterEventManager(netmgr); - m_logicmgr->RegisterEventManager(basicmgr); - - - SYS_SystemHandle hSystem = SYS_GetSystem(); - bool nojoystick= SYS_GetCommandLineInt(hSystem,"nojoystick",0); - if (!nojoystick) - { - SCA_JoystickManager *joymgr = new SCA_JoystickManager(m_logicmgr); - m_logicmgr->RegisterEventManager(joymgr); - } - - MT_assert (m_networkDeviceInterface != NULL); - m_networkScene = new NG_NetworkScene(m_networkDeviceInterface); - - m_rootnode = NULL; - - m_bucketmanager=new RAS_BucketManager(); - - bool showObstacleSimulation = (scene->gm.flag & GAME_SHOW_OBSTACLE_SIMULATION) != 0; - switch (scene->gm.obstacleSimulation) - { - case OBSTSIMULATION_TOI_rays: - m_obstacleSimulation = new KX_ObstacleSimulationTOI_rays((MT_Scalar)scene->gm.levelHeight, showObstacleSimulation); - break; - case OBSTSIMULATION_TOI_cells: - m_obstacleSimulation = new KX_ObstacleSimulationTOI_cells((MT_Scalar)scene->gm.levelHeight, showObstacleSimulation); - break; - default: - m_obstacleSimulation = NULL; - } - -#ifdef WITH_PYTHON - m_attr_dict = NULL; - m_draw_call_pre = NULL; - m_draw_call_post = NULL; - m_draw_setup_call_pre = NULL; -#endif -} - - - -KX_Scene::~KX_Scene() -{ - // The release of debug properties used to be in SCA_IScene::~SCA_IScene - // It's still there but we remove all properties here otherwise some - // reference might be hanging and causing late release of objects - RemoveAllDebugProperties(); - - while (GetRootParentList()->GetCount() > 0) - { - KX_GameObject* parentobj = (KX_GameObject*) GetRootParentList()->GetValue(0); - this->RemoveObject(parentobj); - } - - if (m_obstacleSimulation) - delete m_obstacleSimulation; - - if (m_objectlist) - m_objectlist->Release(); - - if (m_parentlist) - m_parentlist->Release(); - - if (m_inactivelist) - m_inactivelist->Release(); - - if (m_lightlist) - m_lightlist->Release(); - - if (m_tempObjectList) - m_tempObjectList->Release(); - - if (m_euthanasyobjects) - m_euthanasyobjects->Release(); - - if (m_animatedlist) - m_animatedlist->Release(); - - if (m_logicmgr) - delete m_logicmgr; - - if (m_physicsEnvironment) - delete m_physicsEnvironment; - - if (m_networkScene) - delete m_networkScene; - - if (m_bucketmanager) - { - delete m_bucketmanager; - } - -#ifdef WITH_PYTHON - if (m_attr_dict) { - PyDict_Clear(m_attr_dict); - /* Py_CLEAR: Py_DECREF's and NULL's */ - Py_CLEAR(m_attr_dict); - } - - /* these may be NULL but the macro checks */ - Py_CLEAR(m_draw_call_pre); - Py_CLEAR(m_draw_call_post); -#endif -} - -RAS_BucketManager* KX_Scene::GetBucketManager() -{ - return m_bucketmanager; -} - - -CListValue* KX_Scene::GetTempObjectList() -{ - return m_tempObjectList; -} - -CListValue* KX_Scene::GetObjectList() -{ - return m_objectlist; -} - - -CListValue* KX_Scene::GetRootParentList() -{ - return m_parentlist; -} - -CListValue* KX_Scene::GetInactiveList() -{ - return m_inactivelist; -} - - - -CListValue* KX_Scene::GetLightList() -{ - return m_lightlist; -} - -SCA_LogicManager* KX_Scene::GetLogicManager() -{ - return m_logicmgr; -} - -SCA_TimeEventManager* KX_Scene::GetTimeEventManager() -{ - return m_timemgr; -} - - - - -list* KX_Scene::GetCameras() -{ - return &m_cameras; -} - -void KX_Scene::SetFramingType(RAS_FrameSettings & frame_settings) -{ - m_frame_settings = frame_settings; -}; - -/** - * Return a const reference to the framing - * type set by the above call. - * The contents are not guaranteed to be sensible - * if you don't call the above function. - */ -const RAS_FrameSettings& KX_Scene::GetFramingType() const -{ - return m_frame_settings; -}; - - - -/** - * Store the current scene's viewport on the - * game engine canvas. - */ -void KX_Scene::SetSceneViewport(const RAS_Rect &viewport) -{ - m_viewport = viewport; -} - - - -const RAS_Rect& KX_Scene::GetSceneViewport() const -{ - return m_viewport; -} - - - -void KX_Scene::SetWorldInfo(class KX_WorldInfo* worldinfo) -{ - m_worldinfo = worldinfo; -} - - - -class KX_WorldInfo* KX_Scene::GetWorldInfo() -{ - return m_worldinfo; -} - - -const STR_String& KX_Scene::GetName() -{ - return m_sceneName; -} - - -void KX_Scene::Suspend() -{ - m_suspend = true; -} - -void KX_Scene::Resume() -{ - m_suspend = false; -} - -void KX_Scene::SetActivityCulling(bool b) -{ - m_activity_culling = b; -} - -bool KX_Scene::IsSuspended() -{ - return m_suspend; -} - -bool KX_Scene::IsClearingZBuffer() -{ - return m_isclearingZbuffer; -} - -void KX_Scene::EnableZBufferClearing(bool isclearingZbuffer) -{ - m_isclearingZbuffer = isclearingZbuffer; -} - -void KX_Scene::AddObjectDebugProperties(class KX_GameObject* gameobj) -{ - Object* blenderobject = gameobj->GetBlenderObject(); - bProperty* prop = (bProperty*)blenderobject->prop.first; - - while (prop) { - if (prop->flag & PROP_DEBUG) - AddDebugProperty(gameobj,STR_String(prop->name)); - prop = prop->next; - } - - if (blenderobject->scaflag & OB_DEBUGSTATE) - AddDebugProperty(gameobj,STR_String("__state__")); -} - -void KX_Scene::RemoveNodeDestructObject(class SG_IObject* node,class CValue* gameobj) -{ - KX_GameObject* orgobj = (KX_GameObject*)gameobj; - if (NewRemoveObject(orgobj) != 0) - { - // object is not yet deleted because a reference is hanging somewhere. - // This should not happen anymore since we use proxy object for Python - // confident enough to put an assert? - //assert(false); - printf("Zombie object! name=%s\n", orgobj->GetName().ReadPtr()); - orgobj->SetSGNode(NULL); - PHY_IGraphicController* ctrl = orgobj->GetGraphicController(); - if (ctrl) - { - // a graphic controller is set, we must delete it as the node will be deleted - delete ctrl; - orgobj->SetGraphicController(NULL); - } - } - if (node) - delete node; -} - -KX_GameObject* KX_Scene::AddNodeReplicaObject(class SG_IObject* node, class CValue* gameobj) -{ - // for group duplication, limit the duplication of the hierarchy to the - // objects that are part of the group. - if (!IsObjectInGroup(gameobj)) - return NULL; - - KX_GameObject* orgobj = (KX_GameObject*)gameobj; - KX_GameObject* newobj = (KX_GameObject*)orgobj->GetReplica(); - m_map_gameobject_to_replica.insert(orgobj, newobj); - - // also register 'timers' (time properties) of the replica - int numprops = newobj->GetPropertyCount(); - - for (int i = 0; i < numprops; i++) - { - CValue* prop = newobj->GetProperty(i); - - if (prop->GetProperty("timer")) - this->m_timemgr->AddTimeProperty(prop); - } - - if (node) - { - newobj->SetSGNode((SG_Node*)node); - } - else - { - m_rootnode = new SG_Node(newobj,this,KX_Scene::m_callbacks); - - // this fixes part of the scaling-added object bug - SG_Node* orgnode = orgobj->GetSGNode(); - m_rootnode->SetLocalScale(orgnode->GetLocalScale()); - m_rootnode->SetLocalPosition(orgnode->GetLocalPosition()); - m_rootnode->SetLocalOrientation(orgnode->GetLocalOrientation()); - - // define the relationship between this node and it's parent. - KX_NormalParentRelation * parent_relation = - KX_NormalParentRelation::New(); - m_rootnode->SetParentRelation(parent_relation); - - newobj->SetSGNode(m_rootnode); - } - - SG_IObject* replicanode = newobj->GetSGNode(); -// SG_Node* rootnode = (replicanode == m_rootnode ? NULL : m_rootnode); - - replicanode->SetSGClientObject(newobj); - - // this is the list of object that are send to the graphics pipeline - m_objectlist->Add(newobj->AddRef()); - if (newobj->GetGameObjectType()==SCA_IObject::OBJ_LIGHT) - m_lightlist->Add(newobj->AddRef()); - else if (newobj->GetGameObjectType()==SCA_IObject::OBJ_TEXT) - AddFont((KX_FontObject*)newobj); - newobj->AddMeshUser(); - - // logic cannot be replicated, until the whole hierarchy is replicated. - m_logicHierarchicalGameObjects.push_back(newobj); - //replicate controllers of this node - SGControllerList scenegraphcontrollers = orgobj->GetSGNode()->GetSGControllerList(); - replicanode->RemoveAllControllers(); - SGControllerList::iterator cit; - //int numcont = scenegraphcontrollers.size(); - - for (cit = scenegraphcontrollers.begin();!(cit==scenegraphcontrollers.end());++cit) - { - // controller replication is quite complicated - // only replicate ipo controller for now - - SG_Controller* replicacontroller = (*cit)->GetReplica((SG_Node*) replicanode); - if (replicacontroller) - { - replicacontroller->SetObject(replicanode); - replicanode->AddSGController(replicacontroller); - } - } - // replicate graphic controller - if (orgobj->GetGraphicController()) - { - PHY_IMotionState* motionstate = new KX_MotionState(newobj->GetSGNode()); - PHY_IGraphicController* newctrl = orgobj->GetGraphicController()->GetReplica(motionstate); - newctrl->SetNewClientInfo(newobj->getClientInfo()); - newobj->SetGraphicController(newctrl); - } - - // replicate physics controller - if (orgobj->GetPhysicsController()) - { - PHY_IMotionState* motionstate = new KX_MotionState(newobj->GetSGNode()); - PHY_IPhysicsController* newctrl = orgobj->GetPhysicsController()->GetReplica(); - - KX_GameObject *parent = newobj->GetParent(); - PHY_IPhysicsController* parentctrl = (parent) ? parent->GetPhysicsController() : NULL; - - newctrl->SetNewClientInfo(newobj->getClientInfo()); - newobj->SetPhysicsController(newctrl, newobj->IsDynamic()); - newctrl->PostProcessReplica(motionstate, parentctrl); - - // Child objects must be static - if (parent) - newctrl->SuspendDynamics(); - } - - return newobj; -} - - - -// before calling this method KX_Scene::ReplicateLogic(), make sure to -// have called 'GameObject::ReParentLogic' for each object this -// hierarchy that's because first ALL bricks must exist in the new -// replica of the hierarchy in order to make cross-links work properly -// ! -// It is VERY important that the order of sensors and actuators in -// the replicated object is preserved: it is used to reconnect the logic. -// This method is more robust then using the bricks name in case of complex -// group replication. The replication of logic bricks is done in -// SCA_IObject::ReParentLogic(), make sure it preserves the order of the bricks. -void KX_Scene::ReplicateLogic(KX_GameObject* newobj) -{ - /* add properties to debug list, for added objects and DupliGroups */ - if (KX_GetActiveEngine()->GetAutoAddDebugProperties()) { - AddObjectDebugProperties(newobj); - } - // also relink the controller to sensors/actuators - SCA_ControllerList& controllers = newobj->GetControllers(); - //SCA_SensorList& sensors = newobj->GetSensors(); - //SCA_ActuatorList& actuators = newobj->GetActuators(); - - for (SCA_ControllerList::iterator itc = controllers.begin(); !(itc==controllers.end());itc++) - { - SCA_IController* cont = (*itc); - cont->SetUeberExecutePriority(m_ueberExecutionPriority); - vector linkedsensors = cont->GetLinkedSensors(); - vector linkedactuators = cont->GetLinkedActuators(); - - // disconnect the sensors and actuators - // do it directly on the list at this controller is not connected to anything at this stage - cont->GetLinkedSensors().clear(); - cont->GetLinkedActuators().clear(); - - // now relink each sensor - for (vector::iterator its = linkedsensors.begin();!(its==linkedsensors.end());its++) - { - SCA_ISensor* oldsensor = (*its); - SCA_IObject* oldsensorobj = oldsensor->GetParent(); - SCA_IObject* newsensorobj = NULL; - - // the original owner of the sensor has been replicated? - void **h_obj = m_map_gameobject_to_replica[oldsensorobj]; - if (h_obj) - newsensorobj = (SCA_IObject*)(*h_obj); - if (!newsensorobj) - { - // no, then the sensor points outside the hierarchy, keep it the same - if (m_objectlist->SearchValue(oldsensorobj)) - // only replicate links that points to active objects - m_logicmgr->RegisterToSensor(cont,oldsensor); - } - else - { - // yes, then the new sensor has the same position - SCA_SensorList& sensorlist = oldsensorobj->GetSensors(); - SCA_SensorList::iterator sit; - SCA_ISensor* newsensor = NULL; - int sensorpos; - - for (sensorpos=0, sit=sensorlist.begin(); sit!=sensorlist.end(); sit++, sensorpos++) - { - if ((*sit) == oldsensor) - { - newsensor = newsensorobj->GetSensors().at(sensorpos); - break; - } - } - assert(newsensor != NULL); - m_logicmgr->RegisterToSensor(cont,newsensor); - } - } - - // now relink each actuator - for (vector::iterator ita = linkedactuators.begin();!(ita==linkedactuators.end());ita++) - { - SCA_IActuator* oldactuator = (*ita); - SCA_IObject* oldactuatorobj = oldactuator->GetParent(); - SCA_IObject* newactuatorobj = NULL; - - // the original owner of the sensor has been replicated? - void **h_obj = m_map_gameobject_to_replica[oldactuatorobj]; - if (h_obj) - newactuatorobj = (SCA_IObject*)(*h_obj); - - if (!newactuatorobj) - { - // no, then the sensor points outside the hierarchy, keep it the same - if (m_objectlist->SearchValue(oldactuatorobj)) - // only replicate links that points to active objects - m_logicmgr->RegisterToActuator(cont,oldactuator); - } - else - { - // yes, then the new sensor has the same position - SCA_ActuatorList& actuatorlist = oldactuatorobj->GetActuators(); - SCA_ActuatorList::iterator ait; - SCA_IActuator* newactuator = NULL; - int actuatorpos; - - for (actuatorpos=0, ait=actuatorlist.begin(); ait!=actuatorlist.end(); ait++, actuatorpos++) - { - if ((*ait) == oldactuator) - { - newactuator = newactuatorobj->GetActuators().at(actuatorpos); - break; - } - } - assert(newactuator != NULL); - m_logicmgr->RegisterToActuator(cont,newactuator); - newactuator->SetUeberExecutePriority(m_ueberExecutionPriority); - } - } - } - // ready to set initial state - newobj->ResetState(); -} - -void KX_Scene::DupliGroupRecurse(CValue* obj, int level) -{ - KX_GameObject* groupobj = (KX_GameObject*) obj; - KX_GameObject* replica; - KX_GameObject* gameobj; - Object* blgroupobj = groupobj->GetBlenderObject(); - Group* group; - vector duplilist; - - if (!groupobj->GetSGNode() || - !groupobj->IsDupliGroup() || - level>MAX_DUPLI_RECUR) - return; - - // we will add one group at a time - m_logicHierarchicalGameObjects.clear(); - m_map_gameobject_to_replica.clear(); - m_ueberExecutionPriority++; - // for groups will do something special: - // we will force the creation of objects to those in the group only - // Again, this is match what Blender is doing (it doesn't care of parent relationship) - m_groupGameObjects.clear(); - - group = blgroupobj->dup_group; - FOREACH_GROUP_BASE_BEGIN(group, base) - { - Object *blenderobj = base->object; - if (blgroupobj == blenderobj) - // this check is also in group_duplilist() - continue; - - gameobj = (KX_GameObject*)m_logicmgr->FindGameObjByBlendObj(blenderobj); - if (gameobj == NULL) - { - // this object has not been converted!!! - // Should not happen as dupli group are created automatically - continue; - } - - gameobj->SetBlenderGroupObject(blgroupobj); - - if ((base->flag & BASE_VISIBLED) == 0) { - // object is not visible in the 3D view, will not be instantiated - continue; - } - m_groupGameObjects.insert(gameobj); - } - FOREACH_GROUP_BASE_END; - - set::iterator oit; - for (oit=m_groupGameObjects.begin(); oit != m_groupGameObjects.end(); oit++) - { - gameobj = (KX_GameObject*)(*oit); - - KX_GameObject *parent = gameobj->GetParent(); - if (parent != NULL) - { - // this object is not a top parent. Either it is the child of another - // object in the group and it will be added automatically when the parent - // is added. Or it is the child of an object outside the group and the group - // is inconsistent, skip it anyway - continue; - } - replica = (KX_GameObject*) AddNodeReplicaObject(NULL,gameobj); - // add to 'rootparent' list (this is the list of top hierarchy objects, updated each frame) - m_parentlist->Add(replica->AddRef()); - - // recurse replication into children nodes - NodeList& children = gameobj->GetSGNode()->GetSGChildren(); - - replica->GetSGNode()->ClearSGChildren(); - for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit) - { - SG_Node* orgnode = (*childit); - SG_Node* childreplicanode = orgnode->GetSGReplica(); - if (childreplicanode) - replica->GetSGNode()->AddChild(childreplicanode); - } - // don't replicate logic now: we assume that the objects in the group can have - // logic relationship, even outside parent relationship - // In order to match 3D view, the position of groupobj is used as a - // transformation matrix instead of the new position. This means that - // the group reference point is 0,0,0 - - // get the rootnode's scale - MT_Vector3 newscale = groupobj->NodeGetWorldScaling(); - // set the replica's relative scale with the rootnode's scale - replica->NodeSetRelativeScale(newscale); - - MT_Point3 offset(group->dupli_ofs); - MT_Point3 newpos = groupobj->NodeGetWorldPosition() + - newscale*(groupobj->NodeGetWorldOrientation() * (gameobj->NodeGetWorldPosition()-offset)); - replica->NodeSetLocalPosition(newpos); - // set the orientation after position for softbody! - MT_Matrix3x3 newori = groupobj->NodeGetWorldOrientation() * gameobj->NodeGetWorldOrientation(); - replica->NodeSetLocalOrientation(newori); - // update scenegraph for entire tree of children - replica->GetSGNode()->UpdateWorldData(0); - replica->GetSGNode()->SetBBox(gameobj->GetSGNode()->BBox()); - replica->GetSGNode()->SetRadius(gameobj->GetSGNode()->Radius()); - // we can now add the graphic controller to the physic engine - replica->ActivateGraphicController(true); - - // done with replica - replica->Release(); - } - - // the logic must be replicated first because we need - // the new logic bricks before relinking - vector::iterator git; - for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git) - { - (*git)->ReParentLogic(); - } - - // relink any pointers as necessary, sort of a temporary solution - for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git) - { - // this will also relink the actuator to objects within the hierarchy - (*git)->Relink(&m_map_gameobject_to_replica); - // add the object in the layer of the parent - (*git)->SetLayer(groupobj->GetLayer()); - } - - // replicate crosslinks etc. between logic bricks - for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git) - { - ReplicateLogic((*git)); - } - - // now look if object in the hierarchy have dupli group and recurse - for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git) - { - /* Replicate all constraints. */ - if ((*git)->GetPhysicsController()) { - (*git)->GetPhysicsController()->ReplicateConstraints((*git), m_logicHierarchicalGameObjects); - (*git)->ClearConstraints(); - } - - if ((*git) != groupobj && (*git)->IsDupliGroup()) - // can't instantiate group immediately as it destroys m_logicHierarchicalGameObjects - duplilist.push_back((*git)); - - if ((*git)->GetBlenderGroupObject() == blgroupobj) { - // set references for dupli-group - // groupobj holds a list of all objects, that belongs to this group - groupobj->AddInstanceObjects((*git)); - - // every object gets the reference to its dupli-group object - (*git)->SetDupliGroupObject(groupobj); - } - } - - for (git = duplilist.begin(); !(git == duplilist.end()); ++git) - { - DupliGroupRecurse((*git), level+1); - } -} - - -SCA_IObject* KX_Scene::AddReplicaObject(class CValue* originalobject, - class CValue* referenceobject, - int lifespan) -{ - - m_logicHierarchicalGameObjects.clear(); - m_map_gameobject_to_replica.clear(); - m_groupGameObjects.clear(); - - KX_GameObject* originalobj = (KX_GameObject*) originalobject; - KX_GameObject* referenceobj = (KX_GameObject*) referenceobject; - - m_ueberExecutionPriority++; - - // lets create a replica - KX_GameObject* replica = (KX_GameObject*) AddNodeReplicaObject(NULL,originalobj); - - // add a timebomb to this object - // lifespan of zero means 'this object lives forever' - if (lifespan > 0) - { - // for now, convert between so called frames and realtime - m_tempObjectList->Add(replica->AddRef()); - // this convert the life from frames to sort-of seconds, hard coded 0.02 that assumes we have 50 frames per second - // if you change this value, make sure you change it in KX_GameObject::pyattr_get_life property too - CValue *fval = new CFloatValue(lifespan*0.02f); - replica->SetProperty("::timebomb",fval); - fval->Release(); - } - - // add to 'rootparent' list (this is the list of top hierarchy objects, updated each frame) - m_parentlist->Add(replica->AddRef()); - - // recurse replication into children nodes - - NodeList& children = originalobj->GetSGNode()->GetSGChildren(); - - replica->GetSGNode()->ClearSGChildren(); - for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit) - { - SG_Node* orgnode = (*childit); - SG_Node* childreplicanode = orgnode->GetSGReplica(); - if (childreplicanode) - replica->GetSGNode()->AddChild(childreplicanode); - } - - if (referenceobj) { - // At this stage all the objects in the hierarchy have been duplicated, - // we can update the scenegraph, we need it for the duplication of logic - MT_Point3 newpos = referenceobj->NodeGetWorldPosition(); - replica->NodeSetLocalPosition(newpos); - - MT_Matrix3x3 newori = referenceobj->NodeGetWorldOrientation(); - replica->NodeSetLocalOrientation(newori); - - // get the rootnode's scale - MT_Vector3 newscale = referenceobj->GetSGNode()->GetRootSGParent()->GetLocalScale(); - // set the replica's relative scale with the rootnode's scale - replica->NodeSetRelativeScale(newscale); - } - - replica->GetSGNode()->UpdateWorldData(0); - replica->GetSGNode()->SetBBox(originalobj->GetSGNode()->BBox()); - replica->GetSGNode()->SetRadius(originalobj->GetSGNode()->Radius()); - // the size is correct, we can add the graphic controller to the physic engine - replica->ActivateGraphicController(true); - - // now replicate logic - vector::iterator git; - for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git) - { - (*git)->ReParentLogic(); - } - - // relink any pointers as necessary, sort of a temporary solution - for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git) - { - // this will also relink the actuators in the hierarchy - (*git)->Relink(&m_map_gameobject_to_replica); - if (referenceobj) { - // add the object in the layer of the reference object - (*git)->SetLayer(referenceobj->GetLayer()); - } - else { - // We don't know what layer set, so we set all visible layers in the blender scene. - (*git)->SetLayer(m_blenderScene->lay); - } - } - - // replicate crosslinks etc. between logic bricks - for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git) - { - ReplicateLogic((*git)); - } - - // check if there are objects with dupligroup in the hierarchy - vector duplilist; - for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git) - { - if ((*git)->IsDupliGroup()) - { - // separate list as m_logicHierarchicalGameObjects is also used by DupliGroupRecurse() - duplilist.push_back(*git); - } - } - for (git = duplilist.begin();!(git==duplilist.end());++git) - { - DupliGroupRecurse(*git, 0); - } - // don't release replica here because we are returning it, not done with it... - return replica; -} - - - -void KX_Scene::RemoveObject(class CValue* gameobj) -{ - KX_GameObject* newobj = (KX_GameObject*) gameobj; - - // disconnect child from parent - SG_Node* node = newobj->GetSGNode(); - - if (node) - { - node->DisconnectFromParent(); - - // recursively destruct - node->Destruct(); - } - //no need to do that: the object is destroyed and memory released - //newobj->SetSGNode(0); -} - -void KX_Scene::RemoveDupliGroup(class CValue *gameobj) -{ - KX_GameObject *newobj = (KX_GameObject *) gameobj; - - if (newobj->IsDupliGroup()) { - for (int i = 0; i < newobj->GetInstanceObjects()->GetCount(); i++) { - CValue *obj = newobj->GetInstanceObjects()->GetValue(i); - DelayedRemoveObject(obj); - } - } -} - -void KX_Scene::DelayedRemoveObject(class CValue* gameobj) -{ - RemoveDupliGroup(gameobj); - - if (!m_euthanasyobjects->SearchValue(gameobj)) - { - m_euthanasyobjects->Add(gameobj->AddRef()); - } -} - -int KX_Scene::NewRemoveObject(class CValue* gameobj) -{ - int ret; - KX_GameObject* newobj = (KX_GameObject*) gameobj; - - /* remove property from debug list */ - RemoveObjectDebugProperties(newobj); - - /* Invalidate the python reference, since the object may exist in script lists - * its possible that it wont be automatically invalidated, so do it manually here, - * - * if for some reason the object is added back into the scene python can always get a new Proxy - */ - newobj->InvalidateProxy(); - - // keep the blender->game object association up to date - // note that all the replicas of an object will have the same - // blender object, that's why we need to check the game object - // as only the deletion of the original object must be recorded - m_logicmgr->UnregisterGameObj(newobj->GetBlenderObject(), gameobj); - - //todo: look at this - //GetPhysicsEnvironment()->RemovePhysicsController(gameobj->getPhysicsController()); - - // remove all sensors/controllers/actuators from logicsystem... - - SCA_SensorList& sensors = newobj->GetSensors(); - for (SCA_SensorList::iterator its = sensors.begin(); - !(its==sensors.end());its++) - { - m_logicmgr->RemoveSensor(*its); - } - - SCA_ControllerList& controllers = newobj->GetControllers(); - for (SCA_ControllerList::iterator itc = controllers.begin(); - !(itc==controllers.end());itc++) - { - m_logicmgr->RemoveController(*itc); - (*itc)->ReParent(NULL); - } - - SCA_ActuatorList& actuators = newobj->GetActuators(); - for (SCA_ActuatorList::iterator ita = actuators.begin(); - !(ita==actuators.end());ita++) - { - m_logicmgr->RemoveActuator(*ita); - } - // the sensors/controllers/actuators must also be released, this is done in ~SCA_IObject - - // now remove the timer properties from the time manager - int numprops = newobj->GetPropertyCount(); - - for (int i = 0; i < numprops; i++) - { - CValue* propval = newobj->GetProperty(i); - if (propval->GetProperty("timer")) - { - m_timemgr->RemoveTimeProperty(propval); - } - } - - // if the object is the dupligroup proxy, you have to cleanup all m_pDupliGroupObject's in all - // instances refering to this group - if (newobj->GetInstanceObjects()) { - for (int i = 0; i < newobj->GetInstanceObjects()->GetCount(); i++) { - KX_GameObject* instance = (KX_GameObject*)newobj->GetInstanceObjects()->GetValue(i); - instance->RemoveDupliGroupObject(); - } - } - - // if this object was part of a group, make sure to remove it from that group's instance list - KX_GameObject* group = newobj->GetDupliGroupObject(); - if (group) - group->RemoveInstanceObject(newobj); - - newobj->RemoveMeshes(); - - switch (newobj->GetGameObjectType()) { - case SCA_IObject::OBJ_CAMERA: - m_cameras.remove((KX_Camera *)newobj); - break; - case SCA_IObject::OBJ_TEXT: - m_fonts.remove((KX_FontObject *)newobj); - break; - } - - ret = 1; - if (newobj->GetGameObjectType()==SCA_IObject::OBJ_LIGHT && m_lightlist->RemoveValue(newobj)) - ret = newobj->Release(); - if (m_objectlist->RemoveValue(newobj)) - ret = newobj->Release(); - if (m_tempObjectList->RemoveValue(newobj)) - ret = newobj->Release(); - if (m_parentlist->RemoveValue(newobj)) - ret = newobj->Release(); - if (m_inactivelist->RemoveValue(newobj)) - ret = newobj->Release(); - if (m_euthanasyobjects->RemoveValue(newobj)) - ret = newobj->Release(); - if (m_animatedlist->RemoveValue(newobj)) - ret = newobj->Release(); - - /* Warning 'newobj' maye be freed now, only compare, don't access */ - - - if (newobj == m_active_camera) - { - //no AddRef done on m_active_camera so no Release - //m_active_camera->Release(); - m_active_camera = NULL; - } - - /* currently does nothing, keep in case we need to Unregister something */ -#if 0 - if (m_sceneConverter) - m_sceneConverter->UnregisterGameObject(newobj); -#endif - - // return value will be 0 if the object is actually deleted (all reference gone) - - return ret; -} - - - -void KX_Scene::ReplaceMesh(class CValue* obj,void* meshobj, bool use_gfx, bool use_phys) -{ - KX_GameObject* gameobj = static_cast(obj); - RAS_MeshObject* mesh = static_cast(meshobj); - - if (!gameobj) { - std::cout << "KX_Scene::ReplaceMesh Warning: invalid object, doing nothing" << std::endl; - return; - } - - if (use_gfx && mesh != NULL) - { - gameobj->RemoveMeshes(); - gameobj->AddMesh(mesh); - - if (gameobj->m_isDeformable) - { - BL_DeformableGameObject* newobj = static_cast( gameobj ); - - if (newobj->GetDeformer()) - { - delete newobj->GetDeformer(); - newobj->SetDeformer(NULL); - } - - if (mesh->GetMesh()) - { - // we must create a new deformer but which one? - KX_GameObject* parentobj = newobj->GetParent(); - // this always return the original game object (also for replicate) - Object* blendobj = newobj->GetBlenderObject(); - // object that owns the new mesh - Object* oldblendobj = static_cast(m_logicmgr->FindBlendObjByGameMeshName(mesh->GetName())); - Mesh* blendmesh = mesh->GetMesh(); - - bool bHasModifier = BL_ModifierDeformer::HasCompatibleDeformer(blendobj); - bool bHasShapeKey = blendmesh->key != NULL && blendmesh->key->type==KEY_RELATIVE; - bool bHasDvert = blendmesh->dvert != NULL; - bool bHasArmature = - BL_ModifierDeformer::HasArmatureDeformer(blendobj) && - parentobj && // current parent is armature - parentobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE && - oldblendobj && // needed for mesh deform - blendobj->parent && // original object had armature (not sure this test is needed) - blendobj->parent->type == OB_ARMATURE && - blendmesh->dvert!=NULL; // mesh has vertex group -#ifdef WITH_BULLET - bool bHasSoftBody = (!parentobj && (blendobj->gameflag & OB_SOFT_BODY)); -#endif - - if (oldblendobj==NULL) { - if (bHasModifier || bHasShapeKey || bHasDvert || bHasArmature) { - std::cout << "warning: ReplaceMesh() new mesh is not used in an object from the current scene, you will get incorrect behavior" << std::endl; - bHasShapeKey= bHasDvert= bHasArmature=bHasModifier= false; - } - } - - if (bHasModifier) - { - BL_ModifierDeformer* modifierDeformer; - if (bHasShapeKey || bHasArmature) - { - modifierDeformer = new BL_ModifierDeformer( - newobj, - m_blenderScene, - oldblendobj, blendobj, - mesh, - true, - static_cast( parentobj->AddRef() ) - ); - modifierDeformer->LoadShapeDrivers(parentobj); - } - else - { - modifierDeformer = new BL_ModifierDeformer( - newobj, - m_blenderScene, - oldblendobj, blendobj, - mesh, - false, - NULL - ); - } - newobj->SetDeformer(modifierDeformer); - } - else if (bHasShapeKey) { - BL_ShapeDeformer* shapeDeformer; - if (bHasArmature) - { - shapeDeformer = new BL_ShapeDeformer( - newobj, - oldblendobj, blendobj, - mesh, - true, - true, - static_cast( parentobj->AddRef() ) - ); - shapeDeformer->LoadShapeDrivers(parentobj); - } - else - { - shapeDeformer = new BL_ShapeDeformer( - newobj, - oldblendobj, blendobj, - mesh, - false, - true, - NULL - ); - } - newobj->SetDeformer( shapeDeformer); - } - else if (bHasArmature) - { - BL_SkinDeformer* skinDeformer = new BL_SkinDeformer( - newobj, - oldblendobj, blendobj, - mesh, - true, - true, - static_cast( parentobj->AddRef() ) - ); - newobj->SetDeformer(skinDeformer); - } - else if (bHasDvert) - { - BL_MeshDeformer* meshdeformer = new BL_MeshDeformer( - newobj, oldblendobj, mesh - ); - newobj->SetDeformer(meshdeformer); - } -#ifdef WITH_BULLET - else if (bHasSoftBody) - { - KX_SoftBodyDeformer *softdeformer = new KX_SoftBodyDeformer(mesh, newobj); - newobj->SetDeformer(softdeformer); - } -#endif - } - } - - gameobj->AddMeshUser(); - } - - if (use_phys) { /* update the new assigned mesh with the physics mesh */ - if (gameobj->GetPhysicsController()) - gameobj->GetPhysicsController()->ReinstancePhysicsShape(NULL, use_gfx?NULL:mesh); - } -} - -/* Font Object routines */ -void KX_Scene::AddFont(KX_FontObject* font) -{ - if (!FindFont(font)) - m_fonts.push_back(font); -} - -KX_FontObject* KX_Scene::FindFont(KX_FontObject* font) -{ - list::iterator it = m_fonts.begin(); - - while ((it != m_fonts.end()) && ((*it) != font)) - { - ++it; - } - - return ((it == m_fonts.end()) ? NULL : (*it)); -} - - -/* Camera Object routines */ -KX_Camera* KX_Scene::FindCamera(KX_Camera* cam) -{ - list::iterator it = m_cameras.begin(); - - while ((it != m_cameras.end()) && ((*it) != cam)) { - it++; - } - - return ((it == m_cameras.end()) ? NULL : (*it)); -} - - -KX_Camera* KX_Scene::FindCamera(STR_String& name) -{ - list::iterator it = m_cameras.begin(); - - while ((it != m_cameras.end()) && ((*it)->GetName() != name)) { - it++; - } - - return ((it == m_cameras.end()) ? NULL : (*it)); -} - -void KX_Scene::AddCamera(KX_Camera* cam) -{ - if (!FindCamera(cam)) - m_cameras.push_back(cam); -} - - -KX_Camera* KX_Scene::GetActiveCamera() -{ - // NULL if not defined - return m_active_camera; -} - - -void KX_Scene::SetActiveCamera(KX_Camera* cam) -{ - // only set if the cam is in the active list? Or add it otherwise? - if (!FindCamera(cam)) { - AddCamera(cam); - if (cam) std::cout << "Added cam " << cam->GetName() << std::endl; - } - - m_active_camera = cam; -} - -void KX_Scene::SetCameraOnTop(KX_Camera* cam) -{ - if (!FindCamera(cam)) { - // adding is always done at the back, so that's all that needs to be done - AddCamera(cam); - if (cam) std::cout << "Added cam " << cam->GetName() << std::endl; - } else { - m_cameras.remove(cam); - m_cameras.push_back(cam); - } -} - -void KX_Scene::MarkVisible(SG_Tree *node, RAS_IRasterizer* rasty, KX_Camera* cam, int layer) -{ - int intersect = KX_Camera::INTERSECT; - KX_GameObject *gameobj = node->Client()?(KX_GameObject*) node->Client()->GetSGClientObject():NULL; - bool visible = (gameobj && gameobj->GetVisible() && (!layer || (gameobj->GetLayer() & layer))); - bool dotest = visible || node->Left() || node->Right(); - - /* If the camera is inside the box, assume intersect. */ - if (dotest && !node->inside( cam->NodeGetWorldPosition())) - { - MT_Scalar radius = node->Radius(); - MT_Point3 center = node->Center(); - - intersect = cam->SphereInsideFrustum(center, radius); - - if (intersect == KX_Camera::INTERSECT) - { - MT_Point3 box[8]; - node->get(box); - intersect = cam->BoxInsideFrustum(box); - } - } - - switch (intersect) - { - case KX_Camera::OUTSIDE: - MarkSubTreeVisible(node, rasty, false, cam); - break; - case KX_Camera::INTERSECT: - if (gameobj) - MarkVisible(rasty, gameobj, cam, layer); - if (node->Left()) - MarkVisible(node->Left(), rasty, cam, layer); - if (node->Right()) - MarkVisible(node->Right(), rasty, cam, layer); - break; - case KX_Camera::INSIDE: - MarkSubTreeVisible(node, rasty, true, cam, layer); - break; - } -} - -void KX_Scene::MarkSubTreeVisible(SG_Tree *node, RAS_IRasterizer* rasty, bool visible, KX_Camera* cam, int layer) -{ - if (node->Client()) - { - KX_GameObject *gameobj = (KX_GameObject*) node->Client()->GetSGClientObject(); - if (gameobj->GetVisible()) - { - if (visible) - { - int nummeshes = gameobj->GetMeshCount(); - - // this adds the vertices to the display list - for (int m=0;mGetMesh(m))->SchedulePolygons(rasty->GetDrawingMode()); - } - - gameobj->SetCulled(!visible); - gameobj->UpdateBuckets(false); - } - } - if (node->Left()) - MarkSubTreeVisible(node->Left(), rasty, visible, cam, layer); - if (node->Right()) - MarkSubTreeVisible(node->Right(), rasty, visible, cam, layer); -} - -void KX_Scene::MarkVisible(RAS_IRasterizer* rasty, KX_GameObject* gameobj,KX_Camera* cam,int layer) -{ - // User (Python/Actuator) has forced object invisible... - if (!gameobj->GetSGNode() || !gameobj->GetVisible()) - return; - - // Shadow lamp layers - if (layer && !(gameobj->GetLayer() & layer)) { - gameobj->SetCulled(true); - gameobj->UpdateBuckets(false); - return; - } - - // If Frustum culling is off, the object is always visible. - bool vis = !cam->GetFrustumCulling(); - - // If the camera is inside this node, then the object is visible. - if (!vis) - { - vis = gameobj->GetSGNode()->inside( cam->GetCameraLocation() ); - } - - // Test the object's bound sphere against the view frustum. - if (!vis) - { - MT_Vector3 scale = gameobj->GetSGNode()->GetWorldScaling(); - MT_Scalar radius = fabs(scale[scale.closestAxis()] * gameobj->GetSGNode()->Radius()); - switch (cam->SphereInsideFrustum(gameobj->NodeGetWorldPosition(), radius)) - { - case KX_Camera::INSIDE: - vis = true; - break; - case KX_Camera::OUTSIDE: - vis = false; - break; - case KX_Camera::INTERSECT: - // Test the object's bound box against the view frustum. - MT_Point3 box[8]; - gameobj->GetSGNode()->getBBox(box); - vis = cam->BoxInsideFrustum(box) != KX_Camera::OUTSIDE; - break; - } - } - - if (vis) - { - int nummeshes = gameobj->GetMeshCount(); - - for (int m=0;mGetMesh(m))->SchedulePolygons(rasty->GetDrawingMode()); - } - // Visibility/ non-visibility are marked - // elsewhere now. - gameobj->SetCulled(false); - gameobj->UpdateBuckets(false); - } else { - gameobj->SetCulled(true); - gameobj->UpdateBuckets(false); - } -} - -void KX_Scene::PhysicsCullingCallback(KX_ClientObjectInfo *objectInfo, void* cullingInfo) -{ - KX_GameObject* gameobj = objectInfo->m_gameobject; - if (!gameobj->GetVisible()) - // ideally, invisible objects should be removed from the culling tree temporarily - return; - if (((CullingInfo*)cullingInfo)->m_layer && !(gameobj->GetLayer() & ((CullingInfo*)cullingInfo)->m_layer)) - // used for shadow: object is not in shadow layer - return; - - // make object visible - gameobj->SetCulled(false); - gameobj->UpdateBuckets(false); -} - -void KX_Scene::CalculateVisibleMeshes(RAS_IRasterizer* rasty,KX_Camera* cam, int layer) -{ - bool dbvt_culling = false; - if (m_dbvt_culling) - { - /* Reset KX_GameObject m_bCulled to true before doing culling - * since DBVT culling will only set it to false. - * This is similar to what RAS_BucketManager does for RAS_MeshSlot culling. - */ - for (int i = 0; i < m_objectlist->GetCount(); i++) { - KX_GameObject *gameobj = static_cast(m_objectlist->GetValue(i)); - gameobj->SetCulled(true); - } - - // test culling through Bullet - MT_Vector4 planes[6]; - // get the clip planes - MT_Vector4* cplanes = cam->GetNormalizedClipPlanes(); - // and convert - planes[0].setValue(cplanes[4].getValue()); // near - planes[1].setValue(cplanes[5].getValue()); // far - planes[2].setValue(cplanes[0].getValue()); // left - planes[3].setValue(cplanes[1].getValue()); // right - planes[4].setValue(cplanes[2].getValue()); // top - planes[5].setValue(cplanes[3].getValue()); // bottom - CullingInfo info(layer); - - float mvmat[16] = {0}; - cam->GetModelviewMatrix().getValue(mvmat); - float pmat[16] = {0}; - cam->GetProjectionMatrix().getValue(pmat); - - dbvt_culling = m_physicsEnvironment->CullingTest(PhysicsCullingCallback,&info,planes,5,m_dbvt_occlusion_res, - KX_GetActiveEngine()->GetCanvas()->GetViewPort(), - mvmat, pmat); - } - if (!dbvt_culling) { - // the physics engine couldn't help us, do it the hard way - for (int i = 0; i < m_objectlist->GetCount(); i++) - { - MarkVisible(rasty, static_cast(m_objectlist->GetValue(i)), cam, layer); - } - } -} - -// logic stuff -void KX_Scene::LogicBeginFrame(double curtime) -{ - // have a look at temp objects ... - int lastobj = m_tempObjectList->GetCount() - 1; - - for (int i = lastobj; i >= 0; i--) - { - CValue* objval = m_tempObjectList->GetValue(i); - CFloatValue* propval = (CFloatValue*) objval->GetProperty("::timebomb"); - - if (propval) - { - float timeleft = (float)(propval->GetNumber() - 1.0/KX_KetsjiEngine::GetTicRate()); - - if (timeleft > 0) - { - propval->SetFloat(timeleft); - } - else - { - DelayedRemoveObject(objval); - // remove obj - } - } - else - { - // all object is the tempObjectList should have a clock - } - } - m_logicmgr->BeginFrame(curtime, 1.0/KX_KetsjiEngine::GetTicRate()); -} - -void KX_Scene::AddAnimatedObject(CValue* gameobj) -{ - gameobj->AddRef(); - m_animatedlist->Add(gameobj); -} - -static void update_anim_thread_func(TaskPool *pool, void *taskdata, int UNUSED(threadid)) -{ - KX_GameObject *gameobj, *child, *parent; - CListValue *children; - bool needs_update; - double curtime = *(double*)BLI_task_pool_userdata(pool); - - gameobj = (KX_GameObject*)taskdata; - - // Non-armature updates are fast enough, so just update them - needs_update = gameobj->GetGameObjectType() != SCA_IObject::OBJ_ARMATURE; - - if (!needs_update) { - // If we got here, we're looking to update an armature, so check its children meshes - // to see if we need to bother with a more expensive pose update - children = gameobj->GetChildren(); - - bool has_mesh = false, has_non_mesh = false; - - // Check for meshes that haven't been culled - for (int j=0; jGetCount(); ++j) { - child = (KX_GameObject*)children->GetValue(j); - - if (!child->GetCulled()) { - needs_update = true; - break; - } - - if (child->GetMeshCount() == 0) - has_non_mesh = true; - else - has_mesh = true; - } - - // If we didn't find a non-culled mesh, check to see - // if we even have any meshes, and update if this - // armature has only non-mesh children. - if (!needs_update && !has_mesh && has_non_mesh) - needs_update = true; - - children->Release(); - } - - if (needs_update) { - gameobj->UpdateActionManager(curtime); - children = gameobj->GetChildren(); - parent = gameobj->GetParent(); - - // Only do deformers here if they are not parented to an armature, otherwise the armature will - // handle updating its children - if (gameobj->GetDeformer() && (!parent || parent->GetGameObjectType() != SCA_IObject::OBJ_ARMATURE)) - gameobj->GetDeformer()->Update(); - - for (int j=0; jGetCount(); ++j) { - child = (KX_GameObject*)children->GetValue(j); - - if (child->GetDeformer()) { - child->GetDeformer()->Update(); - } - } - - children->Release(); - } -} - -void KX_Scene::UpdateAnimations(double curtime) -{ - TaskPool *pool = BLI_task_pool_create(KX_GetActiveEngine()->GetTaskScheduler(), &curtime); - - for (int i=0; iGetCount(); ++i) { - BLI_task_pool_push(pool, update_anim_thread_func, m_animatedlist->GetValue(i), false, TASK_PRIORITY_LOW); - } - - BLI_task_pool_work_and_wait(pool); - BLI_task_pool_free(pool); -} - -void KX_Scene::LogicUpdateFrame(double curtime, bool frame) -{ - m_logicmgr->UpdateFrame(curtime, frame); -} - - - -void KX_Scene::LogicEndFrame() -{ - m_logicmgr->EndFrame(); - int numobj; - - KX_GameObject* obj; - - while ((numobj = m_euthanasyobjects->GetCount()) > 0) - { - // remove the object from this list to make sure we will not hit it again - obj = (KX_GameObject*)m_euthanasyobjects->GetValue(numobj-1); - m_euthanasyobjects->Remove(numobj-1); - obj->Release(); - RemoveObject(obj); - } - - //prepare obstacle simulation for new frame - if (m_obstacleSimulation) - m_obstacleSimulation->UpdateObstacles(); -} - - - -/** - * UpdateParents: SceneGraph transformation update. - */ -void KX_Scene::UpdateParents(double curtime) -{ - // we use the SG dynamic list - SG_Node* node; - - while ((node = SG_Node::GetNextScheduled(m_sghead)) != NULL) - { - node->UpdateWorldData(curtime); - } - - //for (int i=0; iGetCount(); i++) - //{ - // KX_GameObject* parentobj = (KX_GameObject*)GetRootParentList()->GetValue(i); - // parentobj->NodeUpdateGS(curtime); - //} - - // the list must be empty here - assert(m_sghead.Empty()); - // some nodes may be ready for reschedule, move them to schedule list for next time - while ((node = SG_Node::GetNextRescheduled(m_sghead)) != NULL) - { - node->Schedule(m_sghead); - } -} - - -RAS_MaterialBucket* KX_Scene::FindBucket(class RAS_IPolyMaterial* polymat, bool &bucketCreated) -{ - return m_bucketmanager->FindBucket(polymat, bucketCreated); -} - - - -void KX_Scene::RenderBuckets(const MT_Transform & cameratransform, - class RAS_IRasterizer* rasty) -{ - m_bucketmanager->Renderbuckets(cameratransform,rasty); - KX_BlenderMaterial::EndFrame(); -} - -void KX_Scene::RenderFonts() -{ - list::iterator it = m_fonts.begin(); - while (it != m_fonts.end()) { - (*it)->DrawFontText(); - ++it; - } -} - -void KX_Scene::UpdateObjectLods(void) -{ - KX_GameObject* gameobj; - - if (!this->m_active_camera) - return; - - MT_Vector3 cam_pos = this->m_active_camera->NodeGetWorldPosition(); - - for (int i = 0; i < this->GetObjectList()->GetCount(); i++) { - gameobj = (KX_GameObject*) GetObjectList()->GetValue(i); - if (!gameobj->GetCulled()) { - gameobj->UpdateLod(cam_pos); - } - } -} - -void KX_Scene::SetLodHysteresis(bool active) -{ - m_isActivedHysteresis = active; -} - -bool KX_Scene::IsActivedLodHysteresis(void) -{ - return m_isActivedHysteresis; -} - -void KX_Scene::SetLodHysteresisValue(int hysteresisvalue) -{ - m_lodHysteresisValue = hysteresisvalue; -} - -int KX_Scene::GetLodHysteresisValue(void) -{ - return m_lodHysteresisValue; -} - -void KX_Scene::UpdateObjectActivity(void) -{ - if (m_activity_culling) { - /* determine the activity criterium and set objects accordingly */ - int i=0; - - MT_Point3 camloc = GetActiveCamera()->NodeGetWorldPosition(); //GetCameraLocation(); - - for (i=0;iGetCount();i++) - { - KX_GameObject* ob = (KX_GameObject*) GetObjectList()->GetValue(i); - - if (!ob->GetIgnoreActivityCulling()) { - /* Simple test: more than 10 away from the camera, count - * Manhattan distance. */ - MT_Point3 obpos = ob->NodeGetWorldPosition(); - - if ((fabsf(camloc[0] - obpos[0]) > m_activity_box_radius) || - (fabsf(camloc[1] - obpos[1]) > m_activity_box_radius) || - (fabsf(camloc[2] - obpos[2]) > m_activity_box_radius) ) - { - ob->Suspend(); - } - else { - ob->Resume(); - } - } - } - } -} - -void KX_Scene::SetActivityCullingRadius(float f) -{ - if (f < 0.5f) - f = 0.5f; - m_activity_box_radius = f; -} - -NG_NetworkDeviceInterface* KX_Scene::GetNetworkDeviceInterface() -{ - return m_networkDeviceInterface; -} - -NG_NetworkScene* KX_Scene::GetNetworkScene() -{ - return m_networkScene; -} - -void KX_Scene::SetNetworkDeviceInterface(NG_NetworkDeviceInterface* newInterface) -{ - m_networkDeviceInterface = newInterface; -} - -void KX_Scene::SetNetworkScene(NG_NetworkScene *newScene) -{ - m_networkScene = newScene; -} - - -void KX_Scene::SetGravity(const MT_Vector3& gravity) -{ - GetPhysicsEnvironment()->SetGravity(gravity[0],gravity[1],gravity[2]); -} - -MT_Vector3 KX_Scene::GetGravity() -{ - MT_Vector3 gravity; - - GetPhysicsEnvironment()->GetGravity(gravity); - - return gravity; -} - -void KX_Scene::SetSceneConverter(class KX_BlenderSceneConverter* sceneConverter) -{ - m_sceneConverter = sceneConverter; -} - -void KX_Scene::SetPhysicsEnvironment(class PHY_IPhysicsEnvironment* physEnv) -{ - m_physicsEnvironment = physEnv; - if (m_physicsEnvironment) { - KX_TouchEventManager* touchmgr = new KX_TouchEventManager(m_logicmgr, physEnv); - m_logicmgr->RegisterEventManager(touchmgr); - } -} - -void KX_Scene::setSuspendedTime(double suspendedtime) -{ - m_suspendedtime = suspendedtime; -} -double KX_Scene::getSuspendedTime() -{ - return m_suspendedtime; -} -void KX_Scene::setSuspendedDelta(double suspendeddelta) -{ - m_suspendeddelta = suspendeddelta; -} -double KX_Scene::getSuspendedDelta() -{ - return m_suspendeddelta; -} - -short KX_Scene::GetAnimationFPS() -{ - return m_blenderScene->r.frs_sec; -} - -static void MergeScene_LogicBrick(SCA_ILogicBrick* brick, KX_Scene *from, KX_Scene *to) -{ - SCA_LogicManager *logicmgr= to->GetLogicManager(); - - brick->Replace_IScene(to); - brick->Replace_NetworkScene(to->GetNetworkScene()); - brick->SetLogicManager(to->GetLogicManager()); - - // If we end up replacing a KX_TouchEventManager, we need to make sure - // physics controllers are properly in place. In other words, do this - // after merging physics controllers! - SCA_ISensor *sensor= dynamic_cast(brick); - if (sensor) { - sensor->Replace_EventManager(logicmgr); - } - - SCA_2DFilterActuator *filter_actuator = dynamic_cast(brick); - if (filter_actuator) { - filter_actuator->SetScene(to); - } - -#ifdef WITH_PYTHON - // Python must be called from the main thread unless we want to deal - // with GIL issues. So, this is delayed until here in case of async - // libload (originally in KX_ConvertControllers) - SCA_PythonController *pyctrl = dynamic_cast(brick); - if (pyctrl) { - pyctrl->SetNamespace(KX_GetActiveEngine()->GetPyNamespace()); - - if (pyctrl->m_mode==SCA_PythonController::SCA_PYEXEC_SCRIPT) - pyctrl->Compile(); - } -#endif -} - -static void MergeScene_GameObject(KX_GameObject* gameobj, KX_Scene *to, KX_Scene *from) -{ - { - SCA_ActuatorList& actuators= gameobj->GetActuators(); - SCA_ActuatorList::iterator ita; - - for (ita = actuators.begin(); !(ita==actuators.end()); ++ita) - { - MergeScene_LogicBrick(*ita, from, to); - } - } - - - { - SCA_SensorList& sensors= gameobj->GetSensors(); - SCA_SensorList::iterator its; - - for (its = sensors.begin(); !(its==sensors.end()); ++its) - { - MergeScene_LogicBrick(*its, from, to); - } - } - - { - SCA_ControllerList& controllers= gameobj->GetControllers(); - SCA_ControllerList::iterator itc; - - for (itc = controllers.begin(); !(itc==controllers.end()); ++itc) - { - SCA_IController *cont= *itc; - MergeScene_LogicBrick(cont, from, to); - } - } - - /* graphics controller */ - PHY_IController *ctrl = gameobj->GetGraphicController(); - if (ctrl) { - /* SHOULD update the m_cullingTree */ - ctrl->SetPhysicsEnvironment(to->GetPhysicsEnvironment()); - } - - ctrl = gameobj->GetPhysicsController(); - if (ctrl) { - ctrl->SetPhysicsEnvironment(to->GetPhysicsEnvironment()); - } - - /* SG_Node can hold a scene reference */ - SG_Node *sg= gameobj->GetSGNode(); - if (sg) { - if (sg->GetSGClientInfo() == from) { - sg->SetSGClientInfo(to); - - /* Make sure to grab the children too since they might not be tied to a game object */ - NodeList children = sg->GetSGChildren(); - for (int i=0; iSetSGClientInfo(to); - } - } - /* If the object is a light, update it's scene */ - if (gameobj->GetGameObjectType() == SCA_IObject::OBJ_LIGHT) - ((KX_LightObject*)gameobj)->UpdateScene(to); - - if (gameobj->GetGameObjectType() == SCA_IObject::OBJ_CAMERA) - to->AddCamera((KX_Camera*)gameobj); - - // All armatures should be in the animated object list to be umpdated. - if (gameobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE) - to->AddAnimatedObject(gameobj); - - /* Add the object to the scene's logic manager */ - to->GetLogicManager()->RegisterGameObjectName(gameobj->GetName(), gameobj); - to->GetLogicManager()->RegisterGameObj(gameobj->GetBlenderObject(), gameobj); - - for (int i = 0; i < gameobj->GetMeshCount(); ++i) { - RAS_MeshObject *meshobj = gameobj->GetMesh(i); - // Register the mesh object by name and blender object. - to->GetLogicManager()->RegisterGameMeshName(meshobj->GetName(), gameobj->GetBlenderObject()); - to->GetLogicManager()->RegisterMeshName(meshobj->GetName(), meshobj); - } -} - -bool KX_Scene::MergeScene(KX_Scene *other) -{ - PHY_IPhysicsEnvironment *env = this->GetPhysicsEnvironment(); - PHY_IPhysicsEnvironment *env_other = other->GetPhysicsEnvironment(); - - if ((env==NULL) != (env_other==NULL)) /* TODO - even when both scenes have NONE physics, the other is loaded with bullet enabled, ??? */ - { - printf("KX_Scene::MergeScene: physics scenes type differ, aborting\n"); - printf("\tsource %d, terget %d\n", (int)(env!=NULL), (int)(env_other!=NULL)); - return false; - } - - if (GetSceneConverter() != other->GetSceneConverter()) { - printf("KX_Scene::MergeScene: converters differ, aborting\n"); - return false; - } - - - GetBucketManager()->MergeBucketManager(other->GetBucketManager(), this); - - - /* active + inactive == all ??? - lets hope so */ - for (int i = 0; i < other->GetObjectList()->GetCount(); i++) - { - KX_GameObject* gameobj = (KX_GameObject*)other->GetObjectList()->GetValue(i); - MergeScene_GameObject(gameobj, this, other); - - /* add properties to debug list for LibLoad objects */ - if (KX_GetActiveEngine()->GetAutoAddDebugProperties()) { - AddObjectDebugProperties(gameobj); - } - - gameobj->UpdateBuckets(false); /* only for active objects */ - } - - for (int i = 0; i < other->GetInactiveList()->GetCount(); i++) - { - KX_GameObject* gameobj = (KX_GameObject*)other->GetInactiveList()->GetValue(i); - MergeScene_GameObject(gameobj, this, other); - } - - if (env) { - env->MergeEnvironment(env_other); - CListValue *otherObjects = other->GetObjectList(); - - // List of all physics objects to merge (needed by ReplicateConstraints). - std::vector physicsObjects; - for (unsigned int i = 0; i < otherObjects->GetCount(); ++i) { - KX_GameObject *gameobj = (KX_GameObject *)otherObjects->GetValue(i); - if (gameobj->GetPhysicsController()) { - physicsObjects.push_back(gameobj); - } - } - - for (unsigned int i = 0; i < physicsObjects.size(); ++i) { - KX_GameObject *gameobj = physicsObjects[i]; - // Replicate all constraints in the right physics environment. - gameobj->GetPhysicsController()->ReplicateConstraints(gameobj, physicsObjects); - gameobj->ClearConstraints(); - } - } - - - GetTempObjectList()->MergeList(other->GetTempObjectList()); - other->GetTempObjectList()->ReleaseAndRemoveAll(); - - GetObjectList()->MergeList(other->GetObjectList()); - other->GetObjectList()->ReleaseAndRemoveAll(); - - GetInactiveList()->MergeList(other->GetInactiveList()); - other->GetInactiveList()->ReleaseAndRemoveAll(); - - GetRootParentList()->MergeList(other->GetRootParentList()); - other->GetRootParentList()->ReleaseAndRemoveAll(); - - GetLightList()->MergeList(other->GetLightList()); - other->GetLightList()->ReleaseAndRemoveAll(); - - /* move materials across, assume they both use the same scene-converters - * Do this after lights are merged so materials can use the lights in shaders - */ - GetSceneConverter()->MergeScene(this, other); - - /* merge logic */ - { - SCA_LogicManager *logicmgr= GetLogicManager(); - SCA_LogicManager *logicmgr_other= other->GetLogicManager(); - - vectorevtmgrs= logicmgr->GetEventManagers(); - //vectorevtmgrs_others= logicmgr_other->GetEventManagers(); - - //SCA_EventManager *evtmgr; - SCA_EventManager *evtmgr_other; - - for (unsigned int i= 0; i < evtmgrs.size(); i++) { - evtmgr_other= logicmgr_other->FindEventManager(evtmgrs[i]->GetType()); - - if (evtmgr_other) /* unlikely but possible one scene has a joystick and not the other */ - evtmgr_other->Replace_LogicManager(logicmgr); - - /* when merging objects sensors are moved across into the new manager, don't need to do this here */ - } - - /* grab any timer properties from the other scene */ - SCA_TimeEventManager *timemgr= GetTimeEventManager(); - SCA_TimeEventManager *timemgr_other= other->GetTimeEventManager(); - vector times = timemgr_other->GetTimeValues(); - - for (unsigned int i= 0; i < times.size(); i++) { - timemgr->AddTimeProperty(times[i]); - } - - } - return true; -} - -void KX_Scene::Update2DFilter(vector& propNames, void* gameObj, RAS_2DFilterManager::RAS_2DFILTER_MODE filtermode, int pass, STR_String& text) -{ - m_filtermanager.EnableFilter(propNames, gameObj, filtermode, pass, text); -} - -void KX_Scene::Render2DFilters(RAS_ICanvas* canvas) -{ - m_filtermanager.RenderFilters(canvas); -} - -#ifdef WITH_PYTHON - -void KX_Scene::RunDrawingCallbacks(PyObject *cb_list) -{ - if (!cb_list || PyList_GET_SIZE(cb_list) == 0) - return; - - RunPythonCallBackList(cb_list, NULL, 0, 0); -} - -//---------------------------------------------------------------------------- -//Python - -PyTypeObject KX_Scene::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_Scene", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0, - &Sequence, - &Mapping, - 0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &CValue::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_Scene::Methods[] = { - KX_PYMETHODTABLE(KX_Scene, addObject), - KX_PYMETHODTABLE(KX_Scene, end), - KX_PYMETHODTABLE(KX_Scene, restart), - KX_PYMETHODTABLE(KX_Scene, replace), - KX_PYMETHODTABLE(KX_Scene, suspend), - KX_PYMETHODTABLE(KX_Scene, resume), - KX_PYMETHODTABLE(KX_Scene, drawObstacleSimulation), - - - /* dict style access */ - KX_PYMETHODTABLE(KX_Scene, get), - - {NULL,NULL} //Sentinel -}; -static PyObject *Map_GetItem(PyObject *self_v, PyObject *item) -{ - KX_Scene* self = static_castBGE_PROXY_REF(self_v); - const char *attr_str= _PyUnicode_AsString(item); - PyObject *pyconvert; - - if (self == NULL) { - PyErr_SetString(PyExc_SystemError, "val = scene[key]: KX_Scene, " BGE_PROXY_ERROR_MSG); - return NULL; - } - - if (!self->m_attr_dict) - self->m_attr_dict = PyDict_New(); - - if (self->m_attr_dict && (pyconvert=PyDict_GetItem(self->m_attr_dict, item))) { - - if (attr_str) - PyErr_Clear(); - Py_INCREF(pyconvert); - return pyconvert; - } - else { - if (attr_str) PyErr_Format(PyExc_KeyError, "value = scene[key]: KX_Scene, key \"%s\" does not exist", attr_str); - else PyErr_SetString(PyExc_KeyError, "value = scene[key]: KX_Scene, key does not exist"); - return NULL; - } - -} - -static int Map_SetItem(PyObject *self_v, PyObject *key, PyObject *val) -{ - KX_Scene* self = static_castBGE_PROXY_REF(self_v); - const char *attr_str= _PyUnicode_AsString(key); - if (attr_str==NULL) - PyErr_Clear(); - - if (self == NULL) { - PyErr_SetString(PyExc_SystemError, "scene[key] = value: KX_Scene, " BGE_PROXY_ERROR_MSG); - return -1; - } - - if (!self->m_attr_dict) - self->m_attr_dict = PyDict_New(); - - if (val==NULL) { /* del ob["key"] */ - int del= 0; - - if (self->m_attr_dict) - del |= (PyDict_DelItem(self->m_attr_dict, key)==0) ? 1:0; - - if (del==0) { - if (attr_str) PyErr_Format(PyExc_KeyError, "scene[key] = value: KX_Scene, key \"%s\" could not be set", attr_str); - else PyErr_SetString(PyExc_KeyError, "del scene[key]: KX_Scene, key could not be deleted"); - return -1; - } - else if (self->m_attr_dict) { - PyErr_Clear(); /* PyDict_DelItem sets an error when it fails */ - } - } - else { /* ob["key"] = value */ - int set = 0; - - if (self->m_attr_dict==NULL) /* lazy init */ - self->m_attr_dict= PyDict_New(); - - - if (PyDict_SetItem(self->m_attr_dict, key, val)==0) - set= 1; - else - PyErr_SetString(PyExc_KeyError, "scene[key] = value: KX_Scene, key not be added to internal dictionary"); - - if (set==0) - return -1; /* pythons error value */ - - } - - return 0; /* success */ -} - -static int Seq_Contains(PyObject *self_v, PyObject *value) -{ - KX_Scene* self = static_castBGE_PROXY_REF(self_v); - - if (self == NULL) { - PyErr_SetString(PyExc_SystemError, "val in scene: KX_Scene, " BGE_PROXY_ERROR_MSG); - return -1; - } - - if (!self->m_attr_dict) - self->m_attr_dict = PyDict_New(); - - if (self->m_attr_dict && PyDict_GetItem(self->m_attr_dict, value)) - return 1; - - return 0; -} - -PyMappingMethods KX_Scene::Mapping = { - (lenfunc)NULL, /* inquiry mp_length */ - (binaryfunc)Map_GetItem, /* binaryfunc mp_subscript */ - (objobjargproc)Map_SetItem, /* objobjargproc mp_ass_subscript */ -}; - -PySequenceMethods KX_Scene::Sequence = { - NULL, /* Cant set the len otherwise it can evaluate as false */ - NULL, /* sq_concat */ - NULL, /* sq_repeat */ - NULL, /* sq_item */ - NULL, /* sq_slice */ - NULL, /* sq_ass_item */ - NULL, /* sq_ass_slice */ - (objobjproc)Seq_Contains, /* sq_contains */ - (binaryfunc) NULL, /* sq_inplace_concat */ - (ssizeargfunc) NULL, /* sq_inplace_repeat */ -}; - -PyObject *KX_Scene::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_Scene* self = static_cast(self_v); - return PyUnicode_From_STR_String(self->GetName()); -} - -PyObject *KX_Scene::pyattr_get_objects(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_Scene* self = static_cast(self_v); - return self->GetObjectList()->GetProxy(); -} - -PyObject *KX_Scene::pyattr_get_objects_inactive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_Scene* self = static_cast(self_v); - return self->GetInactiveList()->GetProxy(); -} - -PyObject *KX_Scene::pyattr_get_lights(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_Scene* self = static_cast(self_v); - return self->GetLightList()->GetProxy(); -} - -PyObject *KX_Scene::pyattr_get_world(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_Scene* self = static_cast(self_v); - KX_WorldInfo *world = self->GetWorldInfo(); - - if (world->GetName() != "") { - return world->GetProxy(); - } - else { - Py_RETURN_NONE; - } -} - -PyObject *KX_Scene::pyattr_get_cameras(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - /* With refcounts in this case... - * the new CListValue is owned by python, so its possible python holds onto it longer then the BGE - * however this is the same with "scene.objects + []", when you make a copy by adding lists. - */ - - KX_Scene* self = static_cast(self_v); - CListValue* clist = new CListValue(); - - /* return self->GetCameras()->GetProxy(); */ - - list::iterator it = self->GetCameras()->begin(); - while (it != self->GetCameras()->end()) { - clist->Add((*it)->AddRef()); - it++; - } - - return clist->NewProxy(true); -} - -PyObject *KX_Scene::pyattr_get_active_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_Scene* self = static_cast(self_v); - KX_Camera* cam= self->GetActiveCamera(); - if (cam) - return self->GetActiveCamera()->GetProxy(); - else - Py_RETURN_NONE; -} - - -int KX_Scene::pyattr_set_active_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_Scene* self = static_cast(self_v); - KX_Camera *camOb; - - if (!ConvertPythonToCamera(value, &camOb, false, "scene.active_camera = value: KX_Scene")) - return PY_SET_ATTR_FAIL; - - self->SetActiveCamera(camOb); - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_Scene::pyattr_get_drawing_callback_pre(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_Scene* self = static_cast(self_v); - - if (self->m_draw_call_pre==NULL) - self->m_draw_call_pre= PyList_New(0); - Py_INCREF(self->m_draw_call_pre); - return self->m_draw_call_pre; -} - -PyObject *KX_Scene::pyattr_get_drawing_callback_post(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_Scene* self = static_cast(self_v); - - if (self->m_draw_call_post==NULL) - self->m_draw_call_post= PyList_New(0); - Py_INCREF(self->m_draw_call_post); - return self->m_draw_call_post; -} - -PyObject *KX_Scene::pyattr_get_drawing_setup_callback_pre(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_Scene* self = static_cast(self_v); - - if (self->m_draw_setup_call_pre == NULL) - self->m_draw_setup_call_pre = PyList_New(0); - - Py_INCREF(self->m_draw_setup_call_pre); - return self->m_draw_setup_call_pre; -} - -int KX_Scene::pyattr_set_drawing_callback_pre(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_Scene* self = static_cast(self_v); - - if (!PyList_CheckExact(value)) - { - PyErr_SetString(PyExc_ValueError, "Expected a list"); - return PY_SET_ATTR_FAIL; - } - Py_XDECREF(self->m_draw_call_pre); - - Py_INCREF(value); - self->m_draw_call_pre = value; - - return PY_SET_ATTR_SUCCESS; -} - -int KX_Scene::pyattr_set_drawing_callback_post(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_Scene* self = static_cast(self_v); - - if (!PyList_CheckExact(value)) - { - PyErr_SetString(PyExc_ValueError, "Expected a list"); - return PY_SET_ATTR_FAIL; - } - Py_XDECREF(self->m_draw_call_post); - - Py_INCREF(value); - self->m_draw_call_post = value; - - return PY_SET_ATTR_SUCCESS; -} - -int KX_Scene::pyattr_set_drawing_setup_callback_pre(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_Scene* self = static_cast(self_v); - - if (!PyList_CheckExact(value)) { - PyErr_SetString(PyExc_ValueError, "Expected a list"); - return PY_SET_ATTR_FAIL; - } - - Py_XDECREF(self->m_draw_setup_call_pre); - Py_INCREF(value); - - self->m_draw_setup_call_pre = value; - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_Scene::pyattr_get_gravity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_Scene* self = static_cast(self_v); - - return PyObjectFrom(self->GetGravity()); -} - -int KX_Scene::pyattr_set_gravity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_Scene* self = static_cast(self_v); - - MT_Vector3 vec; - if (!PyVecTo(value, vec)) - return PY_SET_ATTR_FAIL; - - self->SetGravity(vec); - return PY_SET_ATTR_SUCCESS; -} - -PyAttributeDef KX_Scene::Attributes[] = { - KX_PYATTRIBUTE_RO_FUNCTION("name", KX_Scene, pyattr_get_name), - KX_PYATTRIBUTE_RO_FUNCTION("objects", KX_Scene, pyattr_get_objects), - KX_PYATTRIBUTE_RO_FUNCTION("objectsInactive", KX_Scene, pyattr_get_objects_inactive), - KX_PYATTRIBUTE_RO_FUNCTION("lights", KX_Scene, pyattr_get_lights), - KX_PYATTRIBUTE_RO_FUNCTION("cameras", KX_Scene, pyattr_get_cameras), - KX_PYATTRIBUTE_RO_FUNCTION("world", KX_Scene, pyattr_get_world), - KX_PYATTRIBUTE_RW_FUNCTION("active_camera", KX_Scene, pyattr_get_active_camera, pyattr_set_active_camera), - KX_PYATTRIBUTE_RW_FUNCTION("pre_draw", KX_Scene, pyattr_get_drawing_callback_pre, pyattr_set_drawing_callback_pre), - KX_PYATTRIBUTE_RW_FUNCTION("post_draw", KX_Scene, pyattr_get_drawing_callback_post, pyattr_set_drawing_callback_post), - KX_PYATTRIBUTE_RW_FUNCTION("pre_draw_setup", KX_Scene, pyattr_get_drawing_setup_callback_pre, pyattr_set_drawing_setup_callback_pre), - KX_PYATTRIBUTE_RW_FUNCTION("gravity", KX_Scene, pyattr_get_gravity, pyattr_set_gravity), - KX_PYATTRIBUTE_BOOL_RO("suspended", KX_Scene, m_suspend), - KX_PYATTRIBUTE_BOOL_RO("activity_culling", KX_Scene, m_activity_culling), - KX_PYATTRIBUTE_FLOAT_RW("activity_culling_radius", 0.5f, FLT_MAX, KX_Scene, m_activity_box_radius), - KX_PYATTRIBUTE_BOOL_RO("dbvt_culling", KX_Scene, m_dbvt_culling), - { NULL } //Sentinel -}; - -KX_PYMETHODDEF_DOC(KX_Scene, addObject, -"addObject(object, other, time=0)\n" -"Returns the added object.\n") -{ - PyObject *pyob, *pyreference = Py_None; - KX_GameObject *ob, *reference; - - int time = 0; - - if (!PyArg_ParseTuple(args, "O|Oi:addObject", &pyob, &pyreference, &time)) - return NULL; - - if (!ConvertPythonToGameObject(m_logicmgr, pyob, &ob, false, "scene.addObject(object, reference, time): KX_Scene (first argument)") || - !ConvertPythonToGameObject(m_logicmgr, pyreference, &reference, true, "scene.addObject(object, reference, time): KX_Scene (second argument)")) - return NULL; - - if (!m_inactivelist->SearchValue(ob)) { - PyErr_Format(PyExc_ValueError, "scene.addObject(object, reference, time): KX_Scene (first argument): object must be in an inactive layer"); - return NULL; - } - SCA_IObject *replica = AddReplicaObject((SCA_IObject*)ob, reference, time); - - // release here because AddReplicaObject AddRef's - // the object is added to the scene so we don't want python to own a reference - replica->Release(); - return replica->GetProxy(); -} - -KX_PYMETHODDEF_DOC(KX_Scene, end, -"end()\n" -"Removes this scene from the game.\n") -{ - - KX_GetActiveEngine()->RemoveScene(m_sceneName); - - Py_RETURN_NONE; -} - -KX_PYMETHODDEF_DOC(KX_Scene, restart, - "restart()\n" - "Restarts this scene.\n") -{ - KX_GetActiveEngine()->ReplaceScene(m_sceneName, m_sceneName); - - Py_RETURN_NONE; -} - -KX_PYMETHODDEF_DOC(KX_Scene, replace, - "replace(newScene)\n" - "Replaces this scene with another one.\n" - "Return True if the new scene exists and scheduled for replacement, False otherwise.\n") -{ - char* name; - - if (!PyArg_ParseTuple(args, "s:replace", &name)) - return NULL; - - if (KX_GetActiveEngine()->ReplaceScene(m_sceneName, name)) - Py_RETURN_TRUE; - - Py_RETURN_FALSE; -} - -KX_PYMETHODDEF_DOC(KX_Scene, suspend, - "suspend()\n" - "Suspends this scene.\n") -{ - Suspend(); - - Py_RETURN_NONE; -} - -KX_PYMETHODDEF_DOC(KX_Scene, resume, - "resume()\n" - "Resumes this scene.\n") -{ - Resume(); - - Py_RETURN_NONE; -} - -KX_PYMETHODDEF_DOC(KX_Scene, drawObstacleSimulation, - "drawObstacleSimulation()\n" - "Draw debug visualization of obstacle simulation.\n") -{ - if (GetObstacleSimulation()) - GetObstacleSimulation()->DrawObstacles(); - - Py_RETURN_NONE; -} - -/* Matches python dict.get(key, [default]) */ -KX_PYMETHODDEF_DOC(KX_Scene, get, "") -{ - PyObject *key; - PyObject *def = Py_None; - PyObject *ret; - - if (!PyArg_ParseTuple(args, "O|O:get", &key, &def)) - return NULL; - - if (m_attr_dict && (ret=PyDict_GetItem(m_attr_dict, key))) { - Py_INCREF(ret); - return ret; - } - - Py_INCREF(def); - return def; -} - -#endif // WITH_PYTHON diff --git a/source/gameengine/Ketsji/KX_Scene.h b/source/gameengine/Ketsji/KX_Scene.h deleted file mode 100644 index 6d8ae8a321b..00000000000 --- a/source/gameengine/Ketsji/KX_Scene.h +++ /dev/null @@ -1,697 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_Scene.h - * \ingroup ketsji - */ - -#ifndef __KX_SCENE_H__ -#define __KX_SCENE_H__ - - -#include "KX_PhysicsEngineEnums.h" - -#include -#include -#include - -#include "CTR_Map.h" -#include "CTR_HashedPtr.h" -#include "SG_IObject.h" -#include "SCA_IScene.h" -#include "MT_Transform.h" - -#include "RAS_FramingManager.h" -#include "RAS_Rect.h" - - -#include "EXP_PyObjectPlus.h" -#include "RAS_2DFilterManager.h" - -/** - * \section Forward declarations - */ -struct SM_MaterialProps; -struct SM_ShapeProps; -struct Scene; - -class CTR_HashedPtr; -class CListValue; -class CValue; -class SCA_LogicManager; -class SCA_KeyboardManager; -class SCA_TimeEventManager; -class SCA_MouseManager; -class SCA_ISystem; -class SCA_IInputDevice; -class NG_NetworkDeviceInterface; -class NG_NetworkScene; -class SG_IObject; -class SG_Node; -class SG_Tree; -class KX_WorldInfo; -class KX_Camera; -class KX_GameObject; -class KX_LightObject; -class RAS_BucketManager; -class RAS_MaterialBucket; -class RAS_IPolyMaterial; -class RAS_IRasterizer; -class RAS_IRenderTools; -class SCA_JoystickManager; -class btCollisionShape; -class KX_BlenderSceneConverter; -struct KX_ClientObjectInfo; -class KX_ObstacleSimulation; - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -/* for ID freeing */ -#define IS_TAGGED(_id) ((_id) && (((ID *)_id)->tag & LIB_TAG_DOIT)) - -/** - * The KX_Scene holds all data for an independent scene. It relates - * KX_Objects to the specific objects in the modules. - * */ -class KX_Scene : public PyObjectPlus, public SCA_IScene -{ - Py_Header - -#ifdef WITH_PYTHON - PyObject* m_attr_dict; - PyObject* m_draw_call_pre; - PyObject* m_draw_call_post; - PyObject* m_draw_setup_call_pre; -#endif - - struct CullingInfo { - int m_layer; - CullingInfo(int layer) : m_layer(layer) {} - }; - -protected: - RAS_BucketManager* m_bucketmanager; - CListValue* m_tempObjectList; - - /** - * The list of objects which have been removed during the - * course of one frame. They are actually destroyed in - * LogicEndFrame() via a call to RemoveObject(). - */ - CListValue* m_euthanasyobjects; - - CListValue* m_objectlist; - CListValue* m_parentlist; // all 'root' parents - CListValue* m_lightlist; - CListValue* m_inactivelist; // all objects that are not in the active layer - CListValue* m_animatedlist; // all animated objects - - SG_QList m_sghead; // list of nodes that needs scenegraph update - // the Dlist is not object that must be updated - // the Qlist is for objects that needs to be rescheduled - // for updates after udpate is over (slow parent, bone parent) - - - /** - * The set of cameras for this scene - */ - std::list m_cameras; - - /** - * The set of fonts for this scene - */ - std::list m_fonts; - - - /** - * Various SCA managers used by the scene - */ - SCA_LogicManager* m_logicmgr; - SCA_KeyboardManager* m_keyboardmgr; - SCA_MouseManager* m_mousemgr; - SCA_TimeEventManager* m_timemgr; - - // Scene converter where many scene entities are registered - // Used to deregister objects that are deleted - class KX_BlenderSceneConverter* m_sceneConverter; - /** - * physics engine abstraction - */ - //e_PhysicsEngine m_physicsEngine; //who needs this ? - class PHY_IPhysicsEnvironment* m_physicsEnvironment; - - /** - * Does this scene clear the z-buffer? - */ - bool m_isclearingZbuffer; - - /** - * Does the shadow buffer needs calculing - */ - bool m_isShadowDone; - - /** - * The name of the scene - */ - STR_String m_sceneName; - - /** - * stores the world-settings for a scene - */ - KX_WorldInfo* m_worldinfo; - - /** - * \section Different scenes, linked to ketsji scene - */ - - /** - * Network scene. - */ - NG_NetworkDeviceInterface* m_networkDeviceInterface; - NG_NetworkScene* m_networkScene; - - /** - * A temporary variable used to parent objects together on - * replication. Don't get confused by the name it is not - * the scene's root node! - */ - SG_Node* m_rootnode; - - /** - * The active camera for the scene - */ - KX_Camera* m_active_camera; - - /** - * Another temporary variable outstaying its welcome - * used in AddReplicaObject to map game objects to their - * replicas so pointers can be updated. - */ - CTR_Map m_map_gameobject_to_replica; - - /** - * Another temporary variable outstaying its welcome - * used in AddReplicaObject to keep a record of all added - * objects. Logic can only be updated when all objects - * have been updated. This stores a list of the new objects. - */ - std::vector m_logicHierarchicalGameObjects; - - /** - * This temporary variable will contain the list of - * object that can be added during group instantiation. - * objects outside this list will not be added (can - * happen with children that are outside the group). - * Used in AddReplicaObject. If the list is empty, it - * means don't care. - */ - std::set m_groupGameObjects; - - /** - * Pointer to system variable passed in in constructor - * only used in constructor so we do not need to keep it - * around in this class. - */ - - SCA_ISystem* m_kxsystem; - - /** - * The execution priority of replicated object actuators? - */ - int m_ueberExecutionPriority; - - /** - * Activity 'bubble' settings : - * Suspend (freeze) the entire scene. - */ - bool m_suspend; - - /** - * Radius in Manhattan distance of the box for activity culling. - */ - float m_activity_box_radius; - - /** - * Toggle to enable or disable activity culling. - */ - bool m_activity_culling; - - /** - * Toggle to enable or disable culling via DBVT broadphase of Bullet. - */ - bool m_dbvt_culling; - - /** - * Occlusion culling resolution - */ - int m_dbvt_occlusion_res; - - /** - * The framing settings used by this scene - */ - - RAS_FrameSettings m_frame_settings; - - /** - * This scenes viewport into the game engine - * canvas.Maintained externally, initially [0,0] -> [0,0] - */ - RAS_Rect m_viewport; - - /** - * Visibility testing functions. - */ - void MarkVisible(SG_Tree *node, RAS_IRasterizer* rasty, KX_Camera*cam,int layer=0); - void MarkSubTreeVisible(SG_Tree *node, RAS_IRasterizer* rasty, bool visible, KX_Camera*cam,int layer=0); - void MarkVisible(RAS_IRasterizer* rasty, KX_GameObject* gameobj, KX_Camera*cam, int layer=0); - static void PhysicsCullingCallback(KX_ClientObjectInfo* objectInfo, void* cullingInfo); - - double m_suspendedtime; - double m_suspendeddelta; - - struct Scene* m_blenderScene; - - RAS_2DFilterManager m_filtermanager; - - KX_ObstacleSimulation* m_obstacleSimulation; - - /** - * LOD Hysteresis settings - */ - bool m_isActivedHysteresis; - int m_lodHysteresisValue; - -public: - KX_Scene(class SCA_IInputDevice* keyboarddevice, - class SCA_IInputDevice* mousedevice, - class NG_NetworkDeviceInterface* ndi, - const STR_String& scenename, - struct Scene* scene, - class RAS_ICanvas* canvas); - - virtual - ~KX_Scene(); - - RAS_BucketManager* GetBucketManager(); - RAS_MaterialBucket* FindBucket(RAS_IPolyMaterial* polymat, bool &bucketCreated); - void RenderBuckets(const MT_Transform& cameratransform, - RAS_IRasterizer* rasty); - - /** - * Update all transforms according to the scenegraph. - */ - static bool KX_ScenegraphUpdateFunc(SG_IObject* node,void* gameobj,void* scene); - static bool KX_ScenegraphRescheduleFunc(SG_IObject* node,void* gameobj,void* scene); - void UpdateParents(double curtime); - void DupliGroupRecurse(CValue* gameobj, int level); - bool IsObjectInGroup(CValue* gameobj) - { - return (m_groupGameObjects.empty() || - m_groupGameObjects.find(gameobj) != m_groupGameObjects.end()); - } - void AddObjectDebugProperties(class KX_GameObject* gameobj); - SCA_IObject* AddReplicaObject(CValue* gameobj, - CValue* locationobj, - int lifespan=0); - KX_GameObject* AddNodeReplicaObject(SG_IObject* node, - CValue* gameobj); - void RemoveNodeDestructObject(SG_IObject* node, - CValue* gameobj); - void RemoveObject(CValue* gameobj); - void RemoveDupliGroup(CValue *gameobj); - void DelayedRemoveObject(CValue* gameobj); - - int NewRemoveObject(CValue* gameobj); - void ReplaceMesh(CValue* gameobj, - void* meshob, bool use_gfx, bool use_phys); - - void AddAnimatedObject(CValue* gameobj); - - /** - * \section Logic stuff - * Initiate an update of the logic system. - */ - void LogicBeginFrame(double curtime); - void LogicUpdateFrame(double curtime, bool frame); - void UpdateAnimations(double curtime); - - void - LogicEndFrame( - ); - - CListValue* - GetTempObjectList( - ); - - CListValue* - GetObjectList( - ); - - CListValue* - GetInactiveList( - ); - - CListValue* - GetRootParentList( - ); - - CListValue* - GetLightList( - ); - - SCA_LogicManager * - GetLogicManager( - ); - - SCA_TimeEventManager * - GetTimeEventManager( - ); - - /** Font Routines */ - - /** Find a font in the scene by pointer. */ - KX_FontObject* - FindFont( - KX_FontObject* - ); - - /** Add a camera to this scene. */ - void - AddFont( - KX_FontObject* - ); - - /** Render the fonts in this scene. */ - void - RenderFonts( - ); - - /** Camera Routines */ - - std::list* - GetCameras( - ); - - - /** Find a camera in the scene by pointer. */ - KX_Camera* - FindCamera( - KX_Camera* - ); - - /** Find a scene in the scene by name. */ - KX_Camera* - FindCamera( - STR_String& - ); - - /** Add a camera to this scene. */ - void - AddCamera( - KX_Camera* - ); - - /** Find the currently active camera. */ - KX_Camera* - GetActiveCamera( - ); - - /** - * Set this camera to be the active camera in the scene. If the - * camera is not present in the camera list, it will be added - */ - - void - SetActiveCamera( - class KX_Camera* - ); - - /** - * Move this camera to the end of the list so that it is rendered last. - * If the camera is not on the list, it will be added - */ - void - SetCameraOnTop( - class KX_Camera* - ); - - /** - * Activates new desired canvas width set at design time. - * \param width The new desired width. - */ - void - SetCanvasDesignWidth( - unsigned int width - ); - /** - * Activates new desired canvas height set at design time. - * \param width The new desired height. - */ - void - SetCanvasDesignHeight( - unsigned int height - ); - /** - * Returns the current desired canvas width set at design time. - * \return The desired width. - */ - unsigned int - GetCanvasDesignWidth( - void - ) const; - - /** - * Returns the current desired canvas height set at design time. - * \return The desired height. - */ - unsigned int - GetCanvasDesignHeight( - void - ) const; - - /** - * Set the framing options for this scene - */ - - void - SetFramingType( - RAS_FrameSettings & frame_settings - ); - - /** - * Return a const reference to the framing - * type set by the above call. - * The contents are not guaranteed to be sensible - * if you don't call the above function. - */ - - const - RAS_FrameSettings & - GetFramingType( - ) const; - - /** - * Store the current scene's viewport on the - * game engine canvas. - */ - void SetSceneViewport(const RAS_Rect &viewport); - - /** - * Get the current scene's viewport on the - * game engine canvas. This maintained - * externally in KX_GameEngine - */ - const RAS_Rect& GetSceneViewport() const; - - /** - * \section Accessors to different scenes of this scene - */ - void SetNetworkDeviceInterface(NG_NetworkDeviceInterface* newInterface); - void SetNetworkScene(NG_NetworkScene *newScene); - void SetWorldInfo(class KX_WorldInfo* wi); - KX_WorldInfo* GetWorldInfo(); - void CalculateVisibleMeshes(RAS_IRasterizer* rasty, KX_Camera *cam, int layer=0); - KX_Camera* GetpCamera(); - NG_NetworkDeviceInterface* GetNetworkDeviceInterface(); - NG_NetworkScene* GetNetworkScene(); - KX_BlenderSceneConverter *GetSceneConverter() { return m_sceneConverter; } - - /** - * Replicate the logic bricks associated to this object. - */ - - void ReplicateLogic(class KX_GameObject* newobj); - static SG_Callbacks m_callbacks; - - const STR_String& GetName(); - - // Suspend the entire scene. - void Suspend(); - - // Resume a suspended scene. - void Resume(); - - // Update the mesh for objects based on level of detail settings - void UpdateObjectLods(void); - - // LoD Hysteresis functions - void SetLodHysteresis(bool active); - bool IsActivedLodHysteresis(); - void SetLodHysteresisValue(int hysteresisvalue); - int GetLodHysteresisValue(); - - // Update the activity box settings for objects in this scene, if needed. - void UpdateObjectActivity(void); - - // Enable/disable activity culling. - void SetActivityCulling(bool b); - - // Set the radius of the activity culling box. - void SetActivityCullingRadius(float f); - bool IsSuspended(); - bool IsClearingZBuffer(); - void EnableZBufferClearing(bool isclearingZbuffer); - bool IsShadowDone() { return m_isShadowDone; } - void SetShadowDone(bool b) { m_isShadowDone = b; } - // use of DBVT tree for camera culling - void SetDbvtCulling(bool b) { m_dbvt_culling = b; } - bool GetDbvtCulling() { return m_dbvt_culling; } - void SetDbvtOcclusionRes(int i) { m_dbvt_occlusion_res = i; } - int GetDbvtOcclusionRes() { return m_dbvt_occlusion_res; } - - void SetSceneConverter(class KX_BlenderSceneConverter* sceneConverter); - - class PHY_IPhysicsEnvironment* GetPhysicsEnvironment() - { - return m_physicsEnvironment; - } - - void SetPhysicsEnvironment(class PHY_IPhysicsEnvironment* physEnv); - - void SetGravity(const MT_Vector3& gravity); - MT_Vector3 GetGravity(); - - short GetAnimationFPS(); - - /** - * Sets the node tree for this scene. - */ - void SetNodeTree(SG_Tree* root); - - /** - * 2D Filters - */ - void Update2DFilter(std::vector& propNames, void* gameObj, RAS_2DFilterManager::RAS_2DFILTER_MODE filtermode, int pass, STR_String& text); - void Render2DFilters(RAS_ICanvas* canvas); - - KX_ObstacleSimulation* GetObstacleSimulation() { return m_obstacleSimulation; } - -#ifdef WITH_PYTHON - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - - KX_PYMETHOD_DOC(KX_Scene, addObject); - KX_PYMETHOD_DOC(KX_Scene, end); - KX_PYMETHOD_DOC(KX_Scene, restart); - KX_PYMETHOD_DOC(KX_Scene, replace); - KX_PYMETHOD_DOC(KX_Scene, suspend); - KX_PYMETHOD_DOC(KX_Scene, resume); - KX_PYMETHOD_DOC(KX_Scene, get); - KX_PYMETHOD_DOC(KX_Scene, drawObstacleSimulation); - - - /* attributes */ - static PyObject* pyattr_get_name(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_objects(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_objects_inactive(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_lights(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_cameras(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_world(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_active_camera(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_active_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_drawing_callback_pre(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_drawing_callback_pre(void *selv_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_drawing_callback_post(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_drawing_callback_post(void *selv_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_drawing_setup_callback_pre(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_drawing_setup_callback_pre(void *selv_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_gravity(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_gravity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - - virtual PyObject *py_repr(void) { return PyUnicode_From_STR_String(GetName()); } - - /* getitem/setitem */ - static PyMappingMethods Mapping; - static PySequenceMethods Sequence; - - /** - * Run the registered python drawing functions. - */ - void RunDrawingCallbacks(PyObject *cb_list); - - PyObject *GetPreDrawCB() { return m_draw_call_pre; } - PyObject *GetPostDrawCB() { return m_draw_call_post; } - PyObject *GetPreDrawSetupCB() { return m_draw_setup_call_pre; } -#endif - - /** - * Sets the time the scene was suspended - */ - void setSuspendedTime(double suspendedtime); - /** - * Returns the "curtime" the scene was suspended - */ - double getSuspendedTime(); - /** - * Sets the difference between the local time of the scene (when it - * was running and not suspended) and the "curtime" - */ - void setSuspendedDelta(double suspendeddelta); - /** - * Returns the difference between the local time of the scene (when it - * was running and not suspended) and the "curtime" - */ - double getSuspendedDelta(); - /** - * Returns the Blender scene this was made from - */ - struct Scene *GetBlenderScene() { return m_blenderScene; } - - bool MergeScene(KX_Scene *other); - - - //void PrintStats(int verbose_level) { - // m_bucketmanager->PrintStats(verbose_level) - //} -}; - -typedef std::vector KX_SceneList; - -#endif /* __KX_SCENE_H__ */ diff --git a/source/gameengine/Ketsji/KX_SceneActuator.cpp b/source/gameengine/Ketsji/KX_SceneActuator.cpp deleted file mode 100644 index 6fe33fd2f63..00000000000 --- a/source/gameengine/Ketsji/KX_SceneActuator.cpp +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Set scene/camera stuff - * - * - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_SceneActuator.cpp - * \ingroup ketsji - */ - - -#include "SCA_IActuator.h" -#include "KX_SceneActuator.h" -#include -#include "KX_Scene.h" -#include "KX_Camera.h" -#include "KX_KetsjiEngine.h" - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -KX_SceneActuator::KX_SceneActuator(SCA_IObject *gameobj, - int mode, - KX_Scene *scene, - KX_KetsjiEngine* ketsjiEngine, - const STR_String& nextSceneName, - KX_Camera* camera) - : SCA_IActuator(gameobj, KX_ACT_SCENE) -{ - m_mode = mode; - m_scene = scene; - m_KetsjiEngine=ketsjiEngine; - m_camera = camera; - m_nextSceneName = nextSceneName; - if (m_camera) - m_camera->RegisterActuator(this); -} /* End of constructor */ - - - -KX_SceneActuator::~KX_SceneActuator() -{ - if (m_camera) - m_camera->UnregisterActuator(this); -} /* end of destructor */ - - - -CValue* KX_SceneActuator::GetReplica() -{ - KX_SceneActuator* replica = new KX_SceneActuator(*this); - replica->ProcessReplica(); - return replica; -} - -void KX_SceneActuator::ProcessReplica() -{ - if (m_camera) - m_camera->RegisterActuator(this); - SCA_IActuator::ProcessReplica(); -} - -bool KX_SceneActuator::UnlinkObject(SCA_IObject* clientobj) -{ - if (clientobj == (SCA_IObject*)m_camera) - { - // this object is being deleted, we cannot continue to track it. - m_camera = NULL; - return true; - } - return false; -} - -void KX_SceneActuator::Relink(CTR_Map *obj_map) -{ - void **h_obj = (*obj_map)[m_camera]; - if (h_obj) { - if (m_camera) - m_camera->UnregisterActuator(this); - m_camera = (KX_Camera*)(*h_obj); - m_camera->RegisterActuator(this); - } -} - - -bool KX_SceneActuator::Update() -{ - // bool result = false; /*unused*/ - bool bNegativeEvent = IsNegativeEvent(); - RemoveAllEvents(); - - if (bNegativeEvent) - return false; // do nothing on negative events - - switch (m_mode) - { - case KX_SCENE_RESTART: - { - m_KetsjiEngine->ReplaceScene(m_scene->GetName(),m_scene->GetName()); - break; - } - case KX_SCENE_SET_CAMERA: - if (m_camera) - { - m_scene->SetActiveCamera(m_camera); - } - else - { - // if no camera is set and the parent object is a camera, use it as the camera - SCA_IObject* parent = GetParent(); - if (parent->GetGameObjectType()==SCA_IObject::OBJ_CAMERA) - { - m_scene->SetActiveCamera((KX_Camera*)parent); - } - } - break; - default: - break; - } - - if (!m_nextSceneName.Length()) - return false; - - switch (m_mode) - { - case KX_SCENE_SET_SCENE: - { - m_KetsjiEngine->ReplaceScene(m_scene->GetName(),m_nextSceneName); - break; - } - case KX_SCENE_ADD_FRONT_SCENE: - { - bool overlay=true; - m_KetsjiEngine->ConvertAndAddScene(m_nextSceneName,overlay); - break; - } - case KX_SCENE_ADD_BACK_SCENE: - { - bool overlay=false; - m_KetsjiEngine->ConvertAndAddScene(m_nextSceneName,overlay); - break; - } - case KX_SCENE_REMOVE_SCENE: - { - m_KetsjiEngine->RemoveScene(m_nextSceneName); - break; - } - case KX_SCENE_SUSPEND: - { - m_KetsjiEngine->SuspendScene(m_nextSceneName); - break; - } - case KX_SCENE_RESUME: - { - m_KetsjiEngine->ResumeScene(m_nextSceneName); - break; - } - default: - ; /* do nothing? this is an internal error !!! */ - } - - return false; -} - - - -/* returns a camera if the name is valid */ -KX_Camera* KX_SceneActuator::FindCamera(const char *camName) -{ - KX_SceneList* sl = m_KetsjiEngine->CurrentScenes(); - STR_String name = STR_String(camName); - KX_SceneList::iterator it = sl->begin(); - KX_Camera* cam = NULL; - - while ((it != sl->end()) && (!cam)) - { - cam = (*it)->FindCamera(name); - it++; - } - - return cam; -} - - - -KX_Scene* KX_SceneActuator::FindScene(const char *sceneName) -{ - return m_KetsjiEngine->FindScene(sceneName); -} - - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject KX_SceneActuator::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_SceneActuator", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &SCA_IActuator::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_SceneActuator::Methods[] = -{ - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_SceneActuator::Attributes[] = { - KX_PYATTRIBUTE_STRING_RW("scene",0,MAX_ID_NAME-2,true,KX_SceneActuator,m_nextSceneName), - KX_PYATTRIBUTE_RW_FUNCTION("camera",KX_SceneActuator,pyattr_get_camera,pyattr_set_camera), - KX_PYATTRIBUTE_BOOL_RW("useRestart", KX_SceneActuator, m_restart), - KX_PYATTRIBUTE_INT_RW("mode", KX_SCENE_NODEF+1, KX_SCENE_MAX-1, true, KX_SceneActuator, m_mode), - { NULL } //Sentinel -}; - -PyObject *KX_SceneActuator::pyattr_get_camera(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_SceneActuator* actuator = static_cast(self); - if (!actuator->m_camera) - Py_RETURN_NONE; - - return actuator->m_camera->GetProxy(); -} - -int KX_SceneActuator::pyattr_set_camera(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_SceneActuator* actuator = static_cast(self); - KX_Camera *camOb; - - if (!ConvertPythonToCamera(value, &camOb, true, "actu.camera = value: KX_SceneActuator")) - return PY_SET_ATTR_FAIL; - - if (actuator->m_camera) - actuator->m_camera->UnregisterActuator(actuator); - - if (camOb==NULL) { - actuator->m_camera= NULL; - } - else { - actuator->m_camera = camOb; - actuator->m_camera->RegisterActuator(actuator); - } - - return PY_SET_ATTR_SUCCESS; -} - -#endif // WITH_PYTHON - -/* eof */ diff --git a/source/gameengine/Ketsji/KX_SceneActuator.h b/source/gameengine/Ketsji/KX_SceneActuator.h deleted file mode 100644 index 389e9208ef3..00000000000 --- a/source/gameengine/Ketsji/KX_SceneActuator.h +++ /dev/null @@ -1,109 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_SceneActuator.h - * \ingroup ketsji - */ - -#ifndef __KX_SCENEACTUATOR_H__ -#define __KX_SCENEACTUATOR_H__ - -#include "SCA_IActuator.h" -#include "SCA_IScene.h" /* Replace_IScene only */ -#include "KX_Scene.h" /* Replace_IScene only */ - -class KX_SceneActuator : public SCA_IActuator -{ - Py_Header - - int m_mode; - // (restart) has become a toggle internally... not in the interface though - bool m_restart; - // (set Scene) Scene - /** The current scene. */ - class KX_Scene* m_scene; - class KX_KetsjiEngine* m_KetsjiEngine; - /** The scene to switch to. */ - STR_String m_nextSceneName; - - // (Set Camera) Object - class KX_Camera* m_camera; - - /** Is this a valid scene? */ - class KX_Scene* FindScene(const char* sceneName); - /** Is this a valid camera? */ - class KX_Camera* FindCamera(const char* cameraName); - - public: - enum SCA_SceneActuatorMode - { - KX_SCENE_NODEF = 0, - KX_SCENE_RESTART, - KX_SCENE_SET_SCENE, - KX_SCENE_SET_CAMERA, - KX_SCENE_ADD_FRONT_SCENE, - KX_SCENE_ADD_BACK_SCENE, - KX_SCENE_REMOVE_SCENE, - KX_SCENE_SUSPEND, - KX_SCENE_RESUME, - KX_SCENE_MAX - }; - - KX_SceneActuator(SCA_IObject* gameobj, - int mode, - KX_Scene* scene, - KX_KetsjiEngine* ketsjiEngine, - const STR_String& nextSceneName, - KX_Camera* camera); - virtual ~KX_SceneActuator(); - - virtual CValue* GetReplica(); - virtual void ProcessReplica(); - virtual bool UnlinkObject(SCA_IObject* clientobj); - virtual void Relink(CTR_Map *obj_map); - - virtual bool Update(); - -#ifdef WITH_PYTHON - - virtual void Replace_IScene(SCA_IScene *val) - { - m_scene= static_cast(val); - }; - - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - - static PyObject *pyattr_get_camera(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_camera(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - -#endif /* WITH_PYTHON */ - -}; /* end of class KXSceneActuator */ - -#endif diff --git a/source/gameengine/Ketsji/KX_SoundActuator.cpp b/source/gameengine/Ketsji/KX_SoundActuator.cpp deleted file mode 100644 index a09429450cb..00000000000 --- a/source/gameengine/Ketsji/KX_SoundActuator.cpp +++ /dev/null @@ -1,571 +0,0 @@ -/* - * KX_SoundActuator.cpp - * - * - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - * - */ - -/** \file gameengine/Ketsji/KX_SoundActuator.cpp - * \ingroup ketsji - */ - - -#include "KX_SoundActuator.h" - -#ifdef WITH_AUDASPACE -typedef float sample_t; -# include -# include -# include -# include -# include -#endif - -#include "KX_GameObject.h" -#include "KX_PyMath.h" // needed for PyObjectFrom() -#include "KX_PythonInit.h" -#include "KX_Camera.h" -#include - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ -KX_SoundActuator::KX_SoundActuator(SCA_IObject* gameobj, - AUD_Sound* sound, - float volume, - float pitch, - bool is3d, - KX_3DSoundSettings settings, - KX_SOUNDACT_TYPE type)//, - : SCA_IActuator(gameobj, KX_ACT_SOUND) -{ - m_sound = sound ? AUD_Sound_copy(sound) : NULL; - m_handle = NULL; - m_volume = volume; - m_pitch = pitch; - m_is3d = is3d; - m_3d = settings; - m_type = type; - m_isplaying = false; -} - - - -KX_SoundActuator::~KX_SoundActuator() -{ - if (m_handle) { - AUD_Handle_stop(m_handle); - } - - if (m_sound) { - AUD_Sound_free(m_sound); - } -} - -void KX_SoundActuator::play() -{ - if (m_handle) { - AUD_Handle_stop(m_handle); - m_handle = NULL; - } - - if (!m_sound) - return; - - // this is the sound that will be played and not deleted afterwards - AUD_Sound* sound = m_sound; - - bool loop = false; - - switch (m_type) - { - case KX_SOUNDACT_LOOPBIDIRECTIONAL: - case KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP: - sound = AUD_Sound_pingpong(sound); - ATTR_FALLTHROUGH; - case KX_SOUNDACT_LOOPEND: - case KX_SOUNDACT_LOOPSTOP: - loop = true; - break; - case KX_SOUNDACT_PLAYSTOP: - case KX_SOUNDACT_PLAYEND: - default: - break; - } - - AUD_Device* device = AUD_Device_getCurrent(); - m_handle = AUD_Device_play(device, sound, false); - AUD_Device_free(device); - - // in case of pingpong, we have to free the sound - if (sound != m_sound) - AUD_Sound_free(sound); - - if (m_handle != NULL) { - if (m_is3d) { - AUD_Handle_setRelative(m_handle, true); - AUD_Handle_setVolumeMaximum(m_handle, m_3d.max_gain); - AUD_Handle_setVolumeMinimum(m_handle, m_3d.min_gain); - AUD_Handle_setDistanceReference(m_handle, m_3d.reference_distance); - AUD_Handle_setDistanceMaximum(m_handle, m_3d.max_distance); - AUD_Handle_setAttenuation(m_handle, m_3d.rolloff_factor); - AUD_Handle_setConeAngleInner(m_handle, m_3d.cone_inner_angle); - AUD_Handle_setConeAngleOuter(m_handle, m_3d.cone_outer_angle); - AUD_Handle_setConeVolumeOuter(m_handle, m_3d.cone_outer_gain); - } - - if (loop) - AUD_Handle_setLoopCount(m_handle, -1); - AUD_Handle_setPitch(m_handle, m_pitch); - AUD_Handle_setVolume(m_handle, m_volume); - } - - m_isplaying = true; -} - -CValue* KX_SoundActuator::GetReplica() -{ - KX_SoundActuator* replica = new KX_SoundActuator(*this); - replica->ProcessReplica(); - return replica; -} - -void KX_SoundActuator::ProcessReplica() -{ - SCA_IActuator::ProcessReplica(); - m_handle = NULL; - m_sound = AUD_Sound_copy(m_sound); -} - -bool KX_SoundActuator::Update(double curtime, bool frame) -{ - if (!frame) - return true; - bool result = false; - - // do nothing on negative events, otherwise sounds are played twice! - bool bNegativeEvent = IsNegativeEvent(); - bool bPositiveEvent = m_posevent; - - RemoveAllEvents(); - - if (!m_sound) - return false; - - // actual audio device playing state - bool isplaying = m_handle ? (AUD_Handle_getStatus(m_handle) == AUD_STATUS_PLAYING) : false; - - if (bNegativeEvent) - { - // here must be a check if it is still playing - if (m_isplaying && isplaying) - { - switch (m_type) - { - case KX_SOUNDACT_PLAYSTOP: - case KX_SOUNDACT_LOOPSTOP: - case KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP: - { - // stop immediately - if (m_handle) - { - AUD_Handle_stop(m_handle); - m_handle = NULL; - } - break; - } - case KX_SOUNDACT_PLAYEND: - { - // do nothing, sound will stop anyway when it's finished - break; - } - case KX_SOUNDACT_LOOPEND: - case KX_SOUNDACT_LOOPBIDIRECTIONAL: - { - // stop the looping so that the sound stops when it finished - if (m_handle) - AUD_Handle_setLoopCount(m_handle, 0); - break; - } - default: - // implement me !! - break; - } - } - // remember that we tried to stop the actuator - m_isplaying = false; - } - -#if 1 - // Warning: when de-activating the actuator, after a single negative event this runs again with... - // m_posevent==false && m_posevent==false, in this case IsNegativeEvent() returns false - // and assumes this is a positive event. - // check that we actually have a positive event so as not to play sounds when being disabled. - else if (bPositiveEvent) /* <- added since 2.49 */ -#else - else // <- works in most cases except a loop-end sound will never stop unless - // the negative pulse is done continuesly -#endif - { - if (!m_isplaying) - play(); - } - // verify that the sound is still playing - isplaying = m_handle ? (AUD_Handle_getStatus(m_handle) == AUD_STATUS_PLAYING) : false; - - if (isplaying) - { - if (m_is3d) - { - KX_Camera* cam = KX_GetActiveScene()->GetActiveCamera(); - if (cam) - { - KX_GameObject* obj = (KX_GameObject*)this->GetParent(); - MT_Point3 p; - MT_Matrix3x3 Mo; - float data[4]; - - Mo = cam->NodeGetWorldOrientation().inverse(); - p = (obj->NodeGetWorldPosition() - cam->NodeGetWorldPosition()); - p = Mo * p; - p.getValue(data); - AUD_Handle_setLocation(m_handle, data); - p = (obj->GetLinearVelocity() - cam->GetLinearVelocity()); - p = Mo * p; - p.getValue(data); - AUD_Handle_setVelocity(m_handle, data); - (Mo * obj->NodeGetWorldOrientation()).getRotation().getValue(data); - AUD_Handle_setOrientation(m_handle, data); - } - } - result = true; - } - else - { - m_isplaying = false; - result = false; - } - return result; -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - - - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject KX_SoundActuator::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_SoundActuator", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &SCA_IActuator::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_SoundActuator::Methods[] = { - KX_PYMETHODTABLE_NOARGS(KX_SoundActuator, startSound), - KX_PYMETHODTABLE_NOARGS(KX_SoundActuator, pauseSound), - KX_PYMETHODTABLE_NOARGS(KX_SoundActuator, stopSound), - {NULL, NULL} //Sentinel -}; - -PyAttributeDef KX_SoundActuator::Attributes[] = { - KX_PYATTRIBUTE_BOOL_RO("is3D", KX_SoundActuator, m_is3d), - KX_PYATTRIBUTE_RW_FUNCTION("volume_maximum", KX_SoundActuator, pyattr_get_3d_property, pyattr_set_3d_property), - KX_PYATTRIBUTE_RW_FUNCTION("volume_minimum", KX_SoundActuator, pyattr_get_3d_property, pyattr_set_3d_property), - KX_PYATTRIBUTE_RW_FUNCTION("distance_reference", KX_SoundActuator, pyattr_get_3d_property, pyattr_set_3d_property), - KX_PYATTRIBUTE_RW_FUNCTION("distance_maximum", KX_SoundActuator, pyattr_get_3d_property, pyattr_set_3d_property), - KX_PYATTRIBUTE_RW_FUNCTION("attenuation", KX_SoundActuator, pyattr_get_3d_property, pyattr_set_3d_property), - KX_PYATTRIBUTE_RW_FUNCTION("cone_angle_inner", KX_SoundActuator, pyattr_get_3d_property, pyattr_set_3d_property), - KX_PYATTRIBUTE_RW_FUNCTION("cone_angle_outer", KX_SoundActuator, pyattr_get_3d_property, pyattr_set_3d_property), - KX_PYATTRIBUTE_RW_FUNCTION("cone_volume_outer", KX_SoundActuator, pyattr_get_3d_property, pyattr_set_3d_property), - KX_PYATTRIBUTE_RW_FUNCTION("sound", KX_SoundActuator, pyattr_get_sound, pyattr_set_sound), - - KX_PYATTRIBUTE_RW_FUNCTION("time", KX_SoundActuator, pyattr_get_audposition, pyattr_set_audposition), - KX_PYATTRIBUTE_RW_FUNCTION("volume", KX_SoundActuator, pyattr_get_gain, pyattr_set_gain), - KX_PYATTRIBUTE_RW_FUNCTION("pitch", KX_SoundActuator, pyattr_get_pitch, pyattr_set_pitch), - KX_PYATTRIBUTE_ENUM_RW("mode",KX_SoundActuator::KX_SOUNDACT_NODEF+1,KX_SoundActuator::KX_SOUNDACT_MAX-1,false,KX_SoundActuator,m_type), - { NULL } //Sentinel -}; - -/* Methods ----------------------------------------------------------------- */ -KX_PYMETHODDEF_DOC_NOARGS(KX_SoundActuator, startSound, -"startSound()\n" -"\tStarts the sound.\n") -{ - switch (m_handle ? AUD_Handle_getStatus(m_handle) : AUD_STATUS_INVALID) { - case AUD_STATUS_PLAYING: - break; - case AUD_STATUS_PAUSED: - AUD_Handle_resume(m_handle); - break; - default: - play(); - } - Py_RETURN_NONE; -} - -KX_PYMETHODDEF_DOC_NOARGS(KX_SoundActuator, pauseSound, -"pauseSound()\n" -"\tPauses the sound.\n") -{ - if (m_handle) - AUD_Handle_pause(m_handle); - Py_RETURN_NONE; -} - -KX_PYMETHODDEF_DOC_NOARGS(KX_SoundActuator, stopSound, -"stopSound()\n" -"\tStops the sound.\n") -{ - if (m_handle) - { - AUD_Handle_stop(m_handle); - m_handle = NULL; - } - Py_RETURN_NONE; -} - -/* Atribute setting and getting -------------------------------------------- */ -PyObject *KX_SoundActuator::pyattr_get_3d_property(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_SoundActuator * actuator = static_cast (self); - const char* prop = attrdef->m_name; - float result_value = 0.0f; - - if (!strcmp(prop, "volume_maximum")) { - result_value = actuator->m_3d.max_gain; - - } else if (!strcmp(prop, "volume_minimum")) { - result_value = actuator->m_3d.min_gain; - - } else if (!strcmp(prop, "distance_reference")) { - result_value = actuator->m_3d.reference_distance; - - } else if (!strcmp(prop, "distance_maximum")) { - result_value = actuator->m_3d.max_distance; - - } else if (!strcmp(prop, "attenuation")) { - result_value = actuator->m_3d.rolloff_factor; - - } else if (!strcmp(prop, "cone_angle_inner")) { - result_value = actuator->m_3d.cone_inner_angle; - - } else if (!strcmp(prop, "cone_angle_outer")) { - result_value = actuator->m_3d.cone_outer_angle; - - } else if (!strcmp(prop, "cone_volume_outer")) { - result_value = actuator->m_3d.cone_outer_gain; - - } else { - Py_RETURN_NONE; - } - - PyObject *result = PyFloat_FromDouble(result_value); - return result; -} - -PyObject *KX_SoundActuator::pyattr_get_audposition(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_SoundActuator * actuator = static_cast (self); - float position = 0.0f; - - if (actuator->m_handle) - position = AUD_Handle_getPosition(actuator->m_handle); - - PyObject *result = PyFloat_FromDouble(position); - - return result; -} - -PyObject *KX_SoundActuator::pyattr_get_gain(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_SoundActuator * actuator = static_cast (self); - float gain = actuator->m_volume; - - PyObject *result = PyFloat_FromDouble(gain); - - return result; -} - -PyObject *KX_SoundActuator::pyattr_get_pitch(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_SoundActuator * actuator = static_cast (self); - float pitch = actuator->m_pitch; - - PyObject *result = PyFloat_FromDouble(pitch); - - return result; -} - -PyObject *KX_SoundActuator::pyattr_get_sound(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_SoundActuator * actuator = static_cast (self); - if (actuator->m_sound) - return (PyObject *)AUD_getPythonSound(actuator->m_sound); - else - Py_RETURN_NONE; -} - -int KX_SoundActuator::pyattr_set_3d_property(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_SoundActuator * actuator = static_cast (self); - const char* prop = attrdef->m_name; - float prop_value = 0.0f; - - if (!PyArg_Parse(value, "f", &prop_value)) - return PY_SET_ATTR_FAIL; - - // if sound is working and 3D, set the new setting - if (!actuator->m_is3d) - return PY_SET_ATTR_FAIL; - - if (!strcmp(prop, "volume_maximum")) { - actuator->m_3d.max_gain = prop_value; - if (actuator->m_handle) - AUD_Handle_setVolumeMaximum(actuator->m_handle, prop_value); - - } else if (!strcmp(prop, "volume_minimum")) { - actuator->m_3d.min_gain = prop_value; - if (actuator->m_handle) - AUD_Handle_setVolumeMinimum(actuator->m_handle, prop_value); - - } else if (!strcmp(prop, "distance_reference")) { - actuator->m_3d.reference_distance = prop_value; - if (actuator->m_handle) - AUD_Handle_setDistanceReference(actuator->m_handle, prop_value); - - } else if (!strcmp(prop, "distance_maximum")) { - actuator->m_3d.max_distance = prop_value; - if (actuator->m_handle) - AUD_Handle_setDistanceMaximum(actuator->m_handle, prop_value); - - } else if (!strcmp(prop, "attenuation")) { - actuator->m_3d.rolloff_factor = prop_value; - if (actuator->m_handle) - AUD_Handle_setAttenuation(actuator->m_handle, prop_value); - - } else if (!strcmp(prop, "cone_angle_inner")) { - actuator->m_3d.cone_inner_angle = prop_value; - if (actuator->m_handle) - AUD_Handle_setConeAngleInner(actuator->m_handle, prop_value); - - } else if (!strcmp(prop, "cone_angle_outer")) { - actuator->m_3d.cone_outer_angle = prop_value; - if (actuator->m_handle) - AUD_Handle_setConeAngleOuter(actuator->m_handle, prop_value); - - } else if (!strcmp(prop, "cone_volume_outer")) { - actuator->m_3d.cone_outer_gain = prop_value; - if (actuator->m_handle) - AUD_Handle_setConeVolumeOuter(actuator->m_handle, prop_value); - - } else { - return PY_SET_ATTR_FAIL; - } - - return PY_SET_ATTR_SUCCESS; -} - -int KX_SoundActuator::pyattr_set_audposition(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_SoundActuator * actuator = static_cast (self); - - float position = 1.0f; - if (!PyArg_Parse(value, "f", &position)) - return PY_SET_ATTR_FAIL; - - if (actuator->m_handle) - AUD_Handle_setPosition(actuator->m_handle, position); - return PY_SET_ATTR_SUCCESS; -} - -int KX_SoundActuator::pyattr_set_gain(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - float gain = 1.0f; - KX_SoundActuator * actuator = static_cast (self); - if (!PyArg_Parse(value, "f", &gain)) - return PY_SET_ATTR_FAIL; - - actuator->m_volume = gain; - if (actuator->m_handle) - AUD_Handle_setVolume(actuator->m_handle, gain); - - return PY_SET_ATTR_SUCCESS; -} - -int KX_SoundActuator::pyattr_set_pitch(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - float pitch = 1.0f; - KX_SoundActuator * actuator = static_cast (self); - if (!PyArg_Parse(value, "f", &pitch)) - return PY_SET_ATTR_FAIL; - - actuator->m_pitch = pitch; - if (actuator->m_handle) - AUD_Handle_setPitch(actuator->m_handle, pitch); - - return PY_SET_ATTR_SUCCESS; -} - -int KX_SoundActuator::pyattr_set_sound(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - PyObject *sound = NULL; - KX_SoundActuator * actuator = static_cast (self); - if (!PyArg_Parse(value, "O", &sound)) - return PY_SET_ATTR_FAIL; - - AUD_Sound *snd = AUD_getSoundFromPython(sound); - - if (snd) - { - AUD_Sound_free(actuator->m_sound); - actuator->m_sound = snd; - return PY_SET_ATTR_SUCCESS; - } - - return PY_SET_ATTR_FAIL; -} - -#endif // WITH_PYTHON diff --git a/source/gameengine/Ketsji/KX_SoundActuator.h b/source/gameengine/Ketsji/KX_SoundActuator.h deleted file mode 100644 index 4f3e6f707e0..00000000000 --- a/source/gameengine/Ketsji/KX_SoundActuator.h +++ /dev/null @@ -1,127 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_SoundActuator.h - * \ingroup ketsji - */ - -#ifndef __KX_SOUNDACTUATOR_H__ -#define __KX_SOUNDACTUATOR_H__ - -#include "SCA_IActuator.h" - -#ifdef WITH_AUDASPACE -# include -# include -#endif - -#include "BKE_sound.h" - -typedef struct KX_3DSoundSettings { - float min_gain; - float max_gain; - float reference_distance; - float max_distance; - float rolloff_factor; - float cone_inner_angle; - float cone_outer_angle; - float cone_outer_gain; -} KX_3DSoundSettings; - -class KX_SoundActuator : public SCA_IActuator -{ - Py_Header - bool m_isplaying; - AUD_Sound* m_sound; - float m_volume; - float m_pitch; - bool m_is3d; - KX_3DSoundSettings m_3d; - AUD_Handle* m_handle; - - void play(); - -public: - - enum KX_SOUNDACT_TYPE - { - KX_SOUNDACT_NODEF = 0, - KX_SOUNDACT_PLAYSTOP, - KX_SOUNDACT_PLAYEND, - KX_SOUNDACT_LOOPSTOP, - KX_SOUNDACT_LOOPEND, - KX_SOUNDACT_LOOPBIDIRECTIONAL, - KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP, - KX_SOUNDACT_MAX - }; - - KX_SOUNDACT_TYPE m_type; - - KX_SoundActuator(SCA_IObject* gameobj, - AUD_Sound *sound, - float volume, - float pitch, - bool is3d, - KX_3DSoundSettings settings, - KX_SOUNDACT_TYPE type); - - ~KX_SoundActuator(); - - virtual bool Update(double curtime, bool frame); - - CValue* GetReplica(); - void ProcessReplica(); - -#ifdef WITH_PYTHON - - /* -------------------------------------------------------------------- */ - /* Python interface --------------------------------------------------- */ - /* -------------------------------------------------------------------- */ - - KX_PYMETHOD_DOC_NOARGS(KX_SoundActuator, startSound); - KX_PYMETHOD_DOC_NOARGS(KX_SoundActuator, pauseSound); - KX_PYMETHOD_DOC_NOARGS(KX_SoundActuator, stopSound); - - static int pyattr_set_3d_property(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static int pyattr_set_audposition(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static int pyattr_set_gain(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static int pyattr_set_pitch(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static int pyattr_set_type(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static int pyattr_set_sound(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - - static PyObject *pyattr_get_3d_property(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_audposition(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_gain(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_pitch(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_type(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_sound(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - -#endif /* WITH_PYTHON */ - -}; - -#endif /* __KX_SOUNDACTUATOR_H__ */ diff --git a/source/gameengine/Ketsji/KX_StateActuator.cpp b/source/gameengine/Ketsji/KX_StateActuator.cpp deleted file mode 100644 index d918f87c4bf..00000000000 --- a/source/gameengine/Ketsji/KX_StateActuator.cpp +++ /dev/null @@ -1,171 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - * Actuator to toggle visibility/invisibility of objects - */ - -/** \file gameengine/Ketsji/KX_StateActuator.cpp - * \ingroup ketsji - */ - - -#include "KX_StateActuator.h" -#include "KX_GameObject.h" - -KX_StateActuator::KX_StateActuator( - SCA_IObject* gameobj, - int operation, - unsigned int mask - ) - : SCA_IActuator(gameobj, KX_ACT_STATE), - m_operation(operation), - m_mask(mask) -{ - // intentionally empty -} - -KX_StateActuator::~KX_StateActuator( - void - ) -{ - // intentionally empty -} - -// used to put state actuator to be executed before any other actuators -SG_QList KX_StateActuator::m_stateActuatorHead; - -CValue* -KX_StateActuator::GetReplica( - void - ) -{ - KX_StateActuator* replica = new KX_StateActuator(*this); - replica->ProcessReplica(); - return replica; -} - -bool -KX_StateActuator::Update() -{ - bool bNegativeEvent = IsNegativeEvent(); - unsigned int objMask; - - // execution of state actuator means that we are in the execution phase, reset this pointer - // because all the active actuator of this object will be removed for sure. - m_gameobj->m_firstState = NULL; - RemoveAllEvents(); - if (bNegativeEvent) return false; - - KX_GameObject *obj = (KX_GameObject*) GetParent(); - - objMask = obj->GetState(); - switch (m_operation) - { - case OP_CPY: - objMask = m_mask; - break; - case OP_SET: - objMask |= m_mask; - break; - case OP_CLR: - objMask &= ~m_mask; - break; - case OP_NEG: - objMask ^= m_mask; - break; - default: - // unsupported operation, no nothing - return false; - } - obj->SetState(objMask); - return false; -} - -// this function is only used to deactivate actuators outside the logic loop -// e.g. when an object is deleted. -void KX_StateActuator::Deactivate() -{ - if (QDelink()) - { - // the actuator was in the active list - if (m_stateActuatorHead.QEmpty()) - // no more state object active - m_stateActuatorHead.Delink(); - } -} - -void KX_StateActuator::Activate(SG_DList& head) -{ - // sort the state actuators per object on the global list - if (QEmpty()) - { - InsertSelfActiveQList(m_stateActuatorHead, &m_gameobj->m_firstState); - // add front to make sure it runs before other actuators - head.AddFront(&m_stateActuatorHead); - } -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - - - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject KX_StateActuator::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_StateActuator", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &SCA_IActuator::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_StateActuator::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_StateActuator::Attributes[] = { - KX_PYATTRIBUTE_INT_RW("operation",KX_StateActuator::OP_NOP+1,KX_StateActuator::OP_COUNT-1,false,KX_StateActuator,m_operation), - KX_PYATTRIBUTE_INT_RW("mask",0,0x3FFFFFFF,false,KX_StateActuator,m_mask), - { NULL } //Sentinel -}; - -#endif // WITH_PYTHON diff --git a/source/gameengine/Ketsji/KX_StateActuator.h b/source/gameengine/Ketsji/KX_StateActuator.h deleted file mode 100644 index 5ed065d3604..00000000000 --- a/source/gameengine/Ketsji/KX_StateActuator.h +++ /dev/null @@ -1,97 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_StateActuator.h - * \ingroup ketsji - * \brief Actuator to toggle visibility/invisibility of objects - */ - -#ifndef __KX_STATEACTUATOR_H__ -#define __KX_STATEACTUATOR_H__ - -#include "SCA_IActuator.h" - - -/* - * Use of SG_DList : element of actuator being deactivated - * Head: SCA_LogicManager::m_removedActuators - * Use of SG_QList : element of global activated state actuator list - * Head: KX_StateActuator::m_stateActuatorHead - */ -class KX_StateActuator : public SCA_IActuator -{ - Py_Header - - /** Make visible? */ - enum { - OP_NOP = -1, - OP_CPY = 0, - OP_SET, - OP_CLR, - OP_NEG, - OP_COUNT - }; - // SG_Dlist: element of objects with active actuators, always put in front of the list - // Head: SCA_LogicManager::m_activeActuators - // SG_QList: Head of active state actuators list globally - // Elements: KX_StateActuator - static SG_QList m_stateActuatorHead; - int m_operation; - int m_mask; - - public: - - KX_StateActuator( - SCA_IObject* gameobj, - int operation, - unsigned int mask - ); - - virtual - ~KX_StateActuator( - void - ); - - virtual CValue* - GetReplica( - void - ); - - virtual bool - Update(); - - virtual void Deactivate(); - virtual void Activate(SG_DList& head); - - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - -}; - -#endif - diff --git a/source/gameengine/Ketsji/KX_SteeringActuator.cpp b/source/gameengine/Ketsji/KX_SteeringActuator.cpp deleted file mode 100644 index d3a7b665e61..00000000000 --- a/source/gameengine/Ketsji/KX_SteeringActuator.cpp +++ /dev/null @@ -1,639 +0,0 @@ -/* - * Add steering behaviors - * - * - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -#include "BLI_math.h" -#include "KX_SteeringActuator.h" -#include "KX_GameObject.h" -#include "KX_NavMeshObject.h" -#include "KX_ObstacleSimulation.h" -#include "KX_PythonInit.h" -#include "KX_PyMath.h" -#include "Recast.h" - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -KX_SteeringActuator::KX_SteeringActuator(SCA_IObject *gameobj, - int mode, - KX_GameObject *target, - KX_GameObject *navmesh, - float distance, - float velocity, - float acceleration, - float turnspeed, - bool isSelfTerminated, - int pathUpdatePeriod, - KX_ObstacleSimulation* simulation, - short facingmode, - bool normalup, - bool enableVisualization, - bool lockzvel) - : SCA_IActuator(gameobj, KX_ACT_STEERING), - m_target(target), - m_mode(mode), - m_distance(distance), - m_velocity(velocity), - m_acceleration(acceleration), - m_turnspeed(turnspeed), - m_simulation(simulation), - m_updateTime(0), - m_obstacle(NULL), - m_isActive(false), - m_isSelfTerminated(isSelfTerminated), - m_enableVisualization(enableVisualization), - m_facingMode(facingmode), - m_normalUp(normalup), - m_pathLen(0), - m_pathUpdatePeriod(pathUpdatePeriod), - m_lockzvel(lockzvel), - m_wayPointIdx(-1), - m_steerVec(MT_Vector3(0, 0, 0)) -{ - m_navmesh = static_cast(navmesh); - if (m_navmesh) - m_navmesh->RegisterActuator(this); - if (m_target) - m_target->RegisterActuator(this); - - if (m_simulation) - m_obstacle = m_simulation->GetObstacle((KX_GameObject*)gameobj); - KX_GameObject* parent = ((KX_GameObject*)gameobj)->GetParent(); - if (m_facingMode>0 && parent) - { - m_parentlocalmat = parent->GetSGNode()->GetLocalOrientation(); - } - else - m_parentlocalmat.setIdentity(); -} - -KX_SteeringActuator::~KX_SteeringActuator() -{ - if (m_navmesh) - m_navmesh->UnregisterActuator(this); - if (m_target) - m_target->UnregisterActuator(this); -} - -CValue* KX_SteeringActuator::GetReplica() -{ - KX_SteeringActuator* replica = new KX_SteeringActuator(*this); - // replication just copy the m_base pointer => common random generator - replica->ProcessReplica(); - return replica; -} - -void KX_SteeringActuator::ProcessReplica() -{ - if (m_target) - m_target->RegisterActuator(this); - if (m_navmesh) - m_navmesh->RegisterActuator(this); - SCA_IActuator::ProcessReplica(); -} - -void KX_SteeringActuator::ReParent(SCA_IObject* parent) -{ - SCA_IActuator::ReParent(parent); - if (m_simulation) - m_obstacle = m_simulation->GetObstacle((KX_GameObject*)m_gameobj); -} - -bool KX_SteeringActuator::UnlinkObject(SCA_IObject* clientobj) -{ - if (clientobj == m_target) - { - m_target = NULL; - return true; - } - else if (clientobj == m_navmesh) - { - m_navmesh = NULL; - return true; - } - return false; -} - -void KX_SteeringActuator::Relink(CTR_Map *obj_map) -{ - void **h_obj = (*obj_map)[m_target]; - if (h_obj) { - if (m_target) - m_target->UnregisterActuator(this); - m_target = (KX_GameObject*)(*h_obj); - m_target->RegisterActuator(this); - } - - h_obj = (*obj_map)[m_navmesh]; - if (h_obj) { - if (m_navmesh) - m_navmesh->UnregisterActuator(this); - m_navmesh = (KX_NavMeshObject*)(*h_obj); - m_navmesh->RegisterActuator(this); - } -} - -bool KX_SteeringActuator::Update(double curtime, bool frame) -{ - if (frame) - { - double delta = curtime - m_updateTime; - m_updateTime = curtime; - - if (m_posevent && !m_isActive) - { - delta = 0.0; - m_pathUpdateTime = -1.0; - m_updateTime = curtime; - m_isActive = true; - } - bool bNegativeEvent = IsNegativeEvent(); - if (bNegativeEvent) - m_isActive = false; - - RemoveAllEvents(); - - if (!delta) - return true; - - if (bNegativeEvent || !m_target) - return false; // do nothing on negative events - - KX_GameObject *obj = (KX_GameObject*) GetParent(); - const MT_Point3& mypos = obj->NodeGetWorldPosition(); - const MT_Point3& targpos = m_target->NodeGetWorldPosition(); - MT_Vector3 vectotarg = targpos - mypos; - MT_Vector3 vectotarg2d = vectotarg; - vectotarg2d.z() = 0.0f; - m_steerVec = MT_Vector3(0.0f, 0.0f, 0.0f); - bool apply_steerforce = false; - bool terminate = true; - - switch (m_mode) { - case KX_STEERING_SEEK: - if (vectotarg2d.length2()>m_distance*m_distance) - { - terminate = false; - m_steerVec = vectotarg; - m_steerVec.normalize(); - apply_steerforce = true; - } - break; - case KX_STEERING_FLEE: - if (vectotarg2d.length2()m_distance*m_distance) - { - terminate = false; - - static const MT_Scalar WAYPOINT_RADIUS(0.25f); - - if (m_pathUpdateTime<0 || (m_pathUpdatePeriod>=0 && - curtime - m_pathUpdateTime>((double)m_pathUpdatePeriod/1000.0))) - { - m_pathUpdateTime = curtime; - m_pathLen = m_navmesh->FindPath(mypos, targpos, m_path, MAX_PATH_LENGTH); - m_wayPointIdx = m_pathLen > 1 ? 1 : -1; - } - - if (m_wayPointIdx>0) - { - MT_Vector3 waypoint(&m_path[3*m_wayPointIdx]); - if ((waypoint-mypos).length2()=m_pathLen) - { - m_wayPointIdx = -1; - terminate = true; - } - else - waypoint.setValue(&m_path[3*m_wayPointIdx]); - } - - m_steerVec = waypoint - mypos; - apply_steerforce = true; - - - if (m_enableVisualization) - { - //debug draw - static const MT_Vector3 PATH_COLOR(1.0f,0.0f,0.0f); - m_navmesh->DrawPath(m_path, m_pathLen, PATH_COLOR); - } - } - - } - break; - } - - if (apply_steerforce) - { - bool isdyna = obj->IsDynamic(); - if (isdyna) - m_steerVec.z() = 0; - if (!m_steerVec.fuzzyZero()) - m_steerVec.normalize(); - MT_Vector3 newvel = m_velocity * m_steerVec; - - //adjust velocity to avoid obstacles - if (m_simulation && m_obstacle /*&& !newvel.fuzzyZero()*/) - { - if (m_enableVisualization) - KX_RasterizerDrawDebugLine(mypos, mypos + newvel, MT_Vector3(1.0f, 0.0f, 0.0f)); - m_simulation->AdjustObstacleVelocity(m_obstacle, m_mode!=KX_STEERING_PATHFOLLOWING ? m_navmesh : NULL, - newvel, m_acceleration*(float)delta, m_turnspeed/(180.0f*(float)(M_PI*delta))); - if (m_enableVisualization) - KX_RasterizerDrawDebugLine(mypos, mypos + newvel, MT_Vector3(0.0f, 1.0f, 0.0f)); - } - - HandleActorFace(newvel); - if (isdyna) - { - //temporary solution: set 2D steering velocity directly to obj - //correct way is to apply physical force - MT_Vector3 curvel = obj->GetLinearVelocity(); - - if (m_lockzvel) - newvel.z() = 0.0f; - else - newvel.z() = curvel.z(); - - obj->setLinearVelocity(newvel, false); - } - else - { - MT_Vector3 movement = delta*newvel; - obj->ApplyMovement(movement, false); - } - } - else - { - if (m_simulation && m_obstacle) - { - m_obstacle->dvel[0] = 0.f; - m_obstacle->dvel[1] = 0.f; - } - - } - - if (terminate && m_isSelfTerminated) - return false; - } - - return true; -} - -const MT_Vector3& KX_SteeringActuator::GetSteeringVec() -{ - static MT_Vector3 ZERO_VECTOR(0, 0, 0); - if (m_isActive) - return m_steerVec; - else - return ZERO_VECTOR; -} - -inline float vdot2(const float* a, const float* b) -{ - return a[0]*b[0] + a[2]*b[2]; -} -static bool barDistSqPointToTri(const float* p, const float* a, const float* b, const float* c) -{ - float v0[3], v1[3], v2[3]; - rcVsub(v0, c,a); - rcVsub(v1, b,a); - rcVsub(v2, p,a); - - const float dot00 = vdot2(v0, v0); - const float dot01 = vdot2(v0, v1); - const float dot02 = vdot2(v0, v2); - const float dot11 = vdot2(v1, v1); - const float dot12 = vdot2(v1, v2); - - // Compute barycentric coordinates - float invDenom = 1.0f / (dot00 * dot11 - dot01 * dot01); - float u = (dot11 * dot02 - dot01 * dot12) * invDenom; - float v = (dot00 * dot12 - dot01 * dot02) * invDenom; - - float ud = u<0.f ? -u : (u>1.f ? u-1.f : 0.f); - float vd = v<0.f ? -v : (v>1.f ? v-1.f : 0.f); - return ud * ud + vd * vd; -} - -inline void flipAxes(float* vec) -{ - std::swap(vec[1],vec[2]); -} - -static bool getNavmeshNormal(dtStatNavMesh* navmesh, const MT_Vector3& pos, MT_Vector3& normal) -{ - static const float polyPickExt[3] = {2, 4, 2}; - float spos[3]; - pos.getValue(spos); - flipAxes(spos); - dtStatPolyRef sPolyRef = navmesh->findNearestPoly(spos, polyPickExt); - if (sPolyRef == 0) - return false; - const dtStatPoly* p = navmesh->getPoly(sPolyRef-1); - const dtStatPolyDetail* pd = navmesh->getPolyDetail(sPolyRef-1); - - float distMin = FLT_MAX; - int idxMin = -1; - for (int i = 0; i < pd->ntris; ++i) - { - const unsigned char* t = navmesh->getDetailTri(pd->tbase+i); - const float* v[3]; - for (int j = 0; j < 3; ++j) - { - if (t[j] < p->nv) - v[j] = navmesh->getVertex(p->v[t[j]]); - else - v[j] = navmesh->getDetailVertex(pd->vbase+(t[j]-p->nv)); - } - float dist = barDistSqPointToTri(spos, v[0], v[1], v[2]); - if (dist=0) - { - const unsigned char* t = navmesh->getDetailTri(pd->tbase+idxMin); - const float* v[3]; - for (int j = 0; j < 3; ++j) - { - if (t[j] < p->nv) - v[j] = navmesh->getVertex(p->v[t[j]]); - else - v[j] = navmesh->getDetailVertex(pd->vbase+(t[j]-p->nv)); - } - MT_Vector3 tri[3]; - for (size_t j=0; j<3; j++) - tri[j].setValue(v[j][0],v[j][2],v[j][1]); - MT_Vector3 a,b; - a = tri[1]-tri[0]; - b = tri[2]-tri[0]; - normal = b.cross(a).safe_normalized(); - return true; - } - - return false; -} - -void KX_SteeringActuator::HandleActorFace(MT_Vector3& velocity) -{ - if (m_facingMode==0 && (!m_navmesh || !m_normalUp)) - return; - KX_GameObject* curobj = (KX_GameObject*) GetParent(); - MT_Vector3 dir = m_facingMode==0 ? curobj->NodeGetLocalOrientation().getColumn(1) : velocity; - if (dir.fuzzyZero()) - return; - dir.normalize(); - MT_Vector3 up(0,0,1); - MT_Vector3 left; - MT_Matrix3x3 mat; - - if (m_navmesh && m_normalUp) - { - dtStatNavMesh* navmesh = m_navmesh->GetNavMesh(); - MT_Vector3 normal; - MT_Vector3 trpos = m_navmesh->TransformToLocalCoords(curobj->NodeGetWorldPosition()); - if (getNavmeshNormal(navmesh, trpos, normal)) - { - - left = (dir.cross(up)).safe_normalized(); - dir = (-left.cross(normal)).safe_normalized(); - up = normal; - } - } - - switch (m_facingMode) - { - case 1: // TRACK X - { - left = dir.safe_normalized(); - dir = -(left.cross(up)).safe_normalized(); - break; - }; - case 2: // TRACK Y - { - left = (dir.cross(up)).safe_normalized(); - break; - } - - case 3: // track Z - { - left = up.safe_normalized(); - up = dir.safe_normalized(); - dir = left; - left = (dir.cross(up)).safe_normalized(); - break; - } - - case 4: // TRACK -X - { - left = -dir.safe_normalized(); - dir = -(left.cross(up)).safe_normalized(); - break; - }; - case 5: // TRACK -Y - { - left = (-dir.cross(up)).safe_normalized(); - dir = -dir; - break; - } - case 6: // track -Z - { - left = up.safe_normalized(); - up = -dir.safe_normalized(); - dir = left; - left = (dir.cross(up)).safe_normalized(); - break; - } - } - - mat.setValue ( - left[0], dir[0],up[0], - left[1], dir[1],up[1], - left[2], dir[2],up[2] - ); - - - - KX_GameObject* parentObject = curobj->GetParent(); - if (parentObject) - { - MT_Point3 localpos; - localpos = curobj->GetSGNode()->GetLocalPosition(); - MT_Matrix3x3 parentmatinv; - parentmatinv = parentObject->NodeGetWorldOrientation ().inverse (); - mat = parentmatinv * mat; - mat = m_parentlocalmat * mat; - curobj->NodeSetLocalOrientation(mat); - curobj->NodeSetLocalPosition(localpos); - } - else - { - curobj->NodeSetLocalOrientation(mat); - } - -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject KX_SteeringActuator::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_SteeringActuator", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &SCA_IActuator::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_SteeringActuator::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_SteeringActuator::Attributes[] = { - KX_PYATTRIBUTE_INT_RW("behavior", KX_STEERING_NODEF+1, KX_STEERING_MAX-1, true, KX_SteeringActuator, m_mode), - KX_PYATTRIBUTE_RW_FUNCTION("target", KX_SteeringActuator, pyattr_get_target, pyattr_set_target), - KX_PYATTRIBUTE_RW_FUNCTION("navmesh", KX_SteeringActuator, pyattr_get_navmesh, pyattr_set_navmesh), - KX_PYATTRIBUTE_FLOAT_RW("distance", 0.0f, 1000.0f, KX_SteeringActuator, m_distance), - KX_PYATTRIBUTE_FLOAT_RW("velocity", 0.0f, 1000.0f, KX_SteeringActuator, m_velocity), - KX_PYATTRIBUTE_FLOAT_RW("acceleration", 0.0f, 1000.0f, KX_SteeringActuator, m_acceleration), - KX_PYATTRIBUTE_FLOAT_RW("turnspeed", 0.0f, 720.0f, KX_SteeringActuator, m_turnspeed), - KX_PYATTRIBUTE_BOOL_RW("selfterminated", KX_SteeringActuator, m_isSelfTerminated), - KX_PYATTRIBUTE_BOOL_RW("enableVisualization", KX_SteeringActuator, m_enableVisualization), - KX_PYATTRIBUTE_RO_FUNCTION("steeringVec", KX_SteeringActuator, pyattr_get_steeringVec), - KX_PYATTRIBUTE_SHORT_RW("facingMode", 0, 6, true, KX_SteeringActuator, m_facingMode), - KX_PYATTRIBUTE_INT_RW("pathUpdatePeriod", -1, 100000, true, KX_SteeringActuator, m_pathUpdatePeriod), - KX_PYATTRIBUTE_BOOL_RW("lockZVelocity", KX_SteeringActuator, m_lockzvel), - { NULL } //Sentinel -}; - -PyObject *KX_SteeringActuator::pyattr_get_target(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_SteeringActuator* actuator = static_cast(self); - if (!actuator->m_target) - Py_RETURN_NONE; - else - return actuator->m_target->GetProxy(); -} - -int KX_SteeringActuator::pyattr_set_target(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_SteeringActuator* actuator = static_cast(self); - KX_GameObject *gameobj; - - if (!ConvertPythonToGameObject(actuator->GetLogicManager(), value, &gameobj, true, "actuator.object = value: KX_SteeringActuator")) - return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error - - if (actuator->m_target != NULL) - actuator->m_target->UnregisterActuator(actuator); - - actuator->m_target = (KX_GameObject*) gameobj; - - if (actuator->m_target) - actuator->m_target->RegisterActuator(actuator); - - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_SteeringActuator::pyattr_get_navmesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_SteeringActuator* actuator = static_cast(self); - if (!actuator->m_navmesh) - Py_RETURN_NONE; - else - return actuator->m_navmesh->GetProxy(); -} - -int KX_SteeringActuator::pyattr_set_navmesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_SteeringActuator* actuator = static_cast(self); - KX_GameObject *gameobj; - - if (!ConvertPythonToGameObject(actuator->GetLogicManager(), value, &gameobj, true, "actuator.object = value: KX_SteeringActuator")) - return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error - - if (dynamic_cast(gameobj) == NULL) { - PyErr_Format(PyExc_TypeError, "KX_NavMeshObject is expected"); - return PY_SET_ATTR_FAIL; - } - - if (actuator->m_navmesh != NULL) - actuator->m_navmesh->UnregisterActuator(actuator); - - actuator->m_navmesh = static_cast(gameobj); - - if (actuator->m_navmesh) - actuator->m_navmesh->RegisterActuator(actuator); - - return PY_SET_ATTR_SUCCESS; -} - -PyObject *KX_SteeringActuator::pyattr_get_steeringVec(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_SteeringActuator* actuator = static_cast(self); - const MT_Vector3& steeringVec = actuator->GetSteeringVec(); - return PyObjectFrom(steeringVec); -} - -#endif // WITH_PYTHON - -/* eof */ - diff --git a/source/gameengine/Ketsji/KX_SteeringActuator.h b/source/gameengine/Ketsji/KX_SteeringActuator.h deleted file mode 100644 index 3273471c166..00000000000 --- a/source/gameengine/Ketsji/KX_SteeringActuator.h +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Add steering behaviors - * - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -#ifndef __KX_STEERINGACTUATOR_H__ -#define __KX_STEERINGACTUATOR_H__ - -#include "SCA_IActuator.h" -#include "SCA_LogicManager.h" -#include "MT_Matrix3x3.h" - -class KX_GameObject; -class KX_NavMeshObject; -struct KX_Obstacle; -class KX_ObstacleSimulation; -const int MAX_PATH_LENGTH = 128; - -class KX_SteeringActuator : public SCA_IActuator -{ - Py_Header - - /** Target object */ - KX_GameObject *m_target; - KX_NavMeshObject *m_navmesh; - int m_mode; - float m_distance; - float m_velocity; - float m_acceleration; - float m_turnspeed; - KX_ObstacleSimulation* m_simulation; - - double m_updateTime; - KX_Obstacle* m_obstacle; - bool m_isActive; - bool m_isSelfTerminated; - bool m_enableVisualization; - short m_facingMode; - bool m_normalUp; - float m_path[MAX_PATH_LENGTH*3]; - int m_pathLen; - int m_pathUpdatePeriod; - double m_pathUpdateTime; - bool m_lockzvel; - int m_wayPointIdx; - MT_Matrix3x3 m_parentlocalmat; - MT_Vector3 m_steerVec; - void HandleActorFace(MT_Vector3& velocity); -public: - enum KX_STEERINGACT_MODE - { - KX_STEERING_NODEF = 0, - KX_STEERING_SEEK, - KX_STEERING_FLEE, - KX_STEERING_PATHFOLLOWING, - KX_STEERING_MAX - }; - - KX_SteeringActuator(class SCA_IObject* gameobj, - int mode, - KX_GameObject *target, - KX_GameObject *navmesh, - float distance, - float velocity, - float acceleration, - float turnspeed, - bool isSelfTerminated, - int pathUpdatePeriod, - KX_ObstacleSimulation* simulation, - short facingmode, - bool normalup, - bool enableVisualization, - bool lockzvel); - virtual ~KX_SteeringActuator(); - virtual bool Update(double curtime, bool frame); - - virtual CValue* GetReplica(); - virtual void ProcessReplica(); - virtual void ReParent(SCA_IObject* parent); - virtual void Relink(CTR_Map *obj_map); - virtual bool UnlinkObject(SCA_IObject* clientobj); - const MT_Vector3& GetSteeringVec(); - -#ifdef WITH_PYTHON - - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - - /* These are used to get and set m_target */ - static PyObject *pyattr_get_target(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_target(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject *pyattr_get_navmesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_navmesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject *pyattr_get_steeringVec(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - - -#endif /* WITH_PYTHON */ - -}; /* end of class KX_SteeringActuator : public SCA_PropertyActuator */ - -#endif /* __KX_STEERINGACTUATOR_H__ */ diff --git a/source/gameengine/Ketsji/KX_TimeCategoryLogger.cpp b/source/gameengine/Ketsji/KX_TimeCategoryLogger.cpp deleted file mode 100644 index 13717993c4c..00000000000 --- a/source/gameengine/Ketsji/KX_TimeCategoryLogger.cpp +++ /dev/null @@ -1,141 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_TimeCategoryLogger.cpp - * \ingroup ketsji - */ - - -#include "KX_TimeCategoryLogger.h" - -KX_TimeCategoryLogger::KX_TimeCategoryLogger(unsigned int maxNumMeasurements) -: m_maxNumMeasurements(maxNumMeasurements) -{ -} - - -KX_TimeCategoryLogger::~KX_TimeCategoryLogger(void) -{ - DisposeLoggers(); -} - - -void KX_TimeCategoryLogger::SetMaxNumMeasurements(unsigned int maxNumMeasurements) -{ - KX_TimeLoggerMap::iterator it; - for (it = m_loggers.begin(); it != m_loggers.end(); it++) { - it->second->SetMaxNumMeasurements(maxNumMeasurements); - } - m_maxNumMeasurements = maxNumMeasurements; -} - - -unsigned int KX_TimeCategoryLogger::GetMaxNumMeasurements(void) const -{ - return m_maxNumMeasurements; -} - - -void KX_TimeCategoryLogger::AddCategory(TimeCategory tc) -{ - // Only add if not already present - if (m_loggers.find(tc) == m_loggers.end()) { - KX_TimeLogger* logger = new KX_TimeLogger(m_maxNumMeasurements); - //assert(logger); - m_loggers.insert(KX_TimeLoggerMap::value_type(tc, logger)); - } -} - - -void KX_TimeCategoryLogger::StartLog(TimeCategory tc, double now, bool endOtherCategories) -{ - if (endOtherCategories) { - KX_TimeLoggerMap::iterator it; - for (it = m_loggers.begin(); it != m_loggers.end(); it++) { - if (it->first != tc) { - it->second->EndLog(now); - } - } - } - //assert(m_loggers[tc] != m_loggers.end()); - m_loggers[tc]->StartLog(now); -} - - -void KX_TimeCategoryLogger::EndLog(TimeCategory tc, double now) -{ - //assert(m_loggers[tc] != m_loggers.end()); - m_loggers[tc]->EndLog(now); -} - - -void KX_TimeCategoryLogger::EndLog(double now) -{ - KX_TimeLoggerMap::iterator it; - for (it = m_loggers.begin(); it != m_loggers.end(); it++) { - it->second->EndLog(now); - } -} - - -void KX_TimeCategoryLogger::NextMeasurement(double now) -{ - KX_TimeLoggerMap::iterator it; - for (it = m_loggers.begin(); it != m_loggers.end(); it++) { - it->second->NextMeasurement(now); - } -} - - -double KX_TimeCategoryLogger::GetAverage(TimeCategory tc) -{ - //assert(m_loggers[tc] != m_loggers.end()); - return m_loggers[tc]->GetAverage(); -} - - -double KX_TimeCategoryLogger::GetAverage(void) -{ - double time = 0.0; - - KX_TimeLoggerMap::iterator it; - for (it = m_loggers.begin(); it != m_loggers.end(); it++) { - time += it->second->GetAverage(); - } - - return time; -} - - -void KX_TimeCategoryLogger::DisposeLoggers(void) -{ - KX_TimeLoggerMap::iterator it; - for (it = m_loggers.begin(); it != m_loggers.end(); it++) { - delete it->second; - } -} - diff --git a/source/gameengine/Ketsji/KX_TimeCategoryLogger.h b/source/gameengine/Ketsji/KX_TimeCategoryLogger.h deleted file mode 100644 index e097454fca7..00000000000 --- a/source/gameengine/Ketsji/KX_TimeCategoryLogger.h +++ /dev/null @@ -1,136 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_TimeCategoryLogger.h - * \ingroup ketsji - */ - -#ifndef __KX_TIMECATEGORYLOGGER_H__ -#define __KX_TIMECATEGORYLOGGER_H__ - -#ifdef _MSC_VER -# pragma warning (disable:4786) /* suppress stl-MSVC debug info warning */ -#endif - -#include - -#include "KX_TimeLogger.h" - -/** - * Stores and manages time measurements by category. - * Categories can be added dynamically. - * Average measurements can be established for each separate category - * or for all categories together. - */ -class KX_TimeCategoryLogger { -public: - typedef int TimeCategory; - - /** - * Constructor. - * \param maxNumMesasurements Maximum number of measurements stored (> 1). - */ - KX_TimeCategoryLogger(unsigned int maxNumMeasurements = 10); - - /** - * Destructor. - */ - virtual ~KX_TimeCategoryLogger(void); - - /** - * Changes the maximum number of measurements that can be stored. - */ - virtual void SetMaxNumMeasurements(unsigned int maxNumMeasurements); - - /** - * Changes the maximum number of measurements that can be stored. - */ - virtual unsigned int GetMaxNumMeasurements(void) const; - - /** - * Adds a category. - * \param category The new category. - */ - virtual void AddCategory(TimeCategory tc); - - /** - * Starts logging in current measurement for the given category. - * \param tc The category to log to. - * \param now The current time. - * \param endOtherCategories Whether to stop logging to other categories. - */ - virtual void StartLog(TimeCategory tc, double now, bool endOtherCategories = true); - - /** - * End logging in current measurement for the given category. - * \param tc The category to log to. - * \param now The current time. - */ - virtual void EndLog(TimeCategory tc, double now); - - /** - * End logging in current measurement for all categories. - * \param now The current time. - */ - virtual void EndLog(double now); - - /** - * Logs time in next measurement. - * \param now The current time. - */ - virtual void NextMeasurement(double now); - - /** - * Returns average of all but the current measurement time. - * \return The average of all but the current measurement. - */ - virtual double GetAverage(TimeCategory tc); - - /** - * Returns average for grand total. - */ - virtual double GetAverage(void); - -protected: - /** - * Disposes loggers. - */ - virtual void DisposeLoggers(void); - - /** Storage for the loggers. */ - typedef std::map KX_TimeLoggerMap; - KX_TimeLoggerMap m_loggers; - /** Maximum number of measurements. */ - unsigned int m_maxNumMeasurements; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_TimeCategoryLogger") -#endif -}; - -#endif /* __KX_TIMECATEGORYLOGGER_H__ */ diff --git a/source/gameengine/Ketsji/KX_TimeLogger.cpp b/source/gameengine/Ketsji/KX_TimeLogger.cpp deleted file mode 100644 index 12106245c4d..00000000000 --- a/source/gameengine/Ketsji/KX_TimeLogger.cpp +++ /dev/null @@ -1,117 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_TimeLogger.cpp - * \ingroup ketsji - */ - - -#include "KX_TimeLogger.h" - -KX_TimeLogger::KX_TimeLogger(unsigned int maxNumMeasurements) : - m_maxNumMeasurements(maxNumMeasurements), - m_logStart(0), - m_logging(false) -{ -} - - -KX_TimeLogger::~KX_TimeLogger(void) -{ -} - - -void KX_TimeLogger::SetMaxNumMeasurements(unsigned int maxNumMeasurements) -{ - if ((m_maxNumMeasurements != maxNumMeasurements) && maxNumMeasurements) { - // Actual removing is done in NextMeasurement() - m_maxNumMeasurements = maxNumMeasurements; - } -} - - -unsigned int KX_TimeLogger::GetMaxNumMeasurements(void) const -{ - return m_maxNumMeasurements; -} - - -void KX_TimeLogger::StartLog(double now) -{ - if (!m_logging) { - m_logging = true; - m_logStart = now; - } -} - - -void KX_TimeLogger::EndLog(double now) -{ - if (m_logging) { - m_logging = false; - double time = now - m_logStart; - if (m_measurements.size() > 0) { - m_measurements[0] += time; - } - } -} - - -void KX_TimeLogger::NextMeasurement(double now) -{ - // End logging to current measurement - EndLog(now); - - // Add a new measurement at the front - double m = 0.0; - m_measurements.push_front(m); - - // Remove measurement if we grow beyond the maximum size - if ((m_measurements.size()) > m_maxNumMeasurements) { - while (m_measurements.size() > m_maxNumMeasurements) { - m_measurements.pop_back(); - } - } -} - - - -double KX_TimeLogger::GetAverage(void) const -{ - double avg = 0.0; - - unsigned int numMeasurements = m_measurements.size(); - if (numMeasurements > 1) { - for (unsigned int i = 1; i < numMeasurements; i++) { - avg += m_measurements[i]; - } - avg /= (double)numMeasurements - 1.0; - } - - return avg; -} - diff --git a/source/gameengine/Ketsji/KX_TimeLogger.h b/source/gameengine/Ketsji/KX_TimeLogger.h deleted file mode 100644 index 59d7bdc84e3..00000000000 --- a/source/gameengine/Ketsji/KX_TimeLogger.h +++ /dev/null @@ -1,114 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_TimeLogger.h - * \ingroup ketsji - */ - -#ifndef __KX_TIMELOGGER_H__ -#define __KX_TIMELOGGER_H__ - -#ifdef _MSC_VER -# pragma warning (disable:4786) /* suppress stl-MSVC debug info warning */ -#endif - -#include - -#ifdef WITH_CXX_GUARDEDALLOC -# include "MEM_guardedalloc.h" -#endif - -/** - * Stores and manages time measurements. - */ -class KX_TimeLogger { -public: - /** - * Constructor. - * \param maxNumMesasurements Maximum number of measurements stored (>1). - */ - KX_TimeLogger(unsigned int maxNumMeasurements = 10); - - /** - * Destructor. - */ - virtual ~KX_TimeLogger(void); - - /** - * Changes the maximum number of measurements that can be stored. - */ - virtual void SetMaxNumMeasurements(unsigned int maxNumMeasurements); - - /** - * Changes the maximum number of measurements that can be stored. - */ - virtual unsigned int GetMaxNumMeasurements(void) const; - - /** - * Starts logging in current measurement. - * \param now The current time. - */ - virtual void StartLog(double now); - - /** - * End logging in current measurement. - * \param now The current time. - */ - virtual void EndLog(double now); - - /** - * Logs time in next measurement. - * \param now The current time. - */ - virtual void NextMeasurement(double now); - - /** - * Returns average of all but the current measurement. - * \return The average of all but the current measurement. - */ - virtual double GetAverage(void) const; - -protected: - /** Storage for the measurements. */ - std::deque m_measurements; - - /** Maximum number of measurements. */ - unsigned int m_maxNumMeasurements; - - /** Time at start of logging. */ - double m_logStart; - - /** State of logging. */ - bool m_logging; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_TimeLogger") -#endif -}; - -#endif /* __KX_TIMELOGGER_H__ */ diff --git a/source/gameengine/Ketsji/KX_TouchEventManager.cpp b/source/gameengine/Ketsji/KX_TouchEventManager.cpp deleted file mode 100644 index 7f167652464..00000000000 --- a/source/gameengine/Ketsji/KX_TouchEventManager.cpp +++ /dev/null @@ -1,246 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_TouchEventManager.cpp - * \ingroup ketsji - */ - - -#include "KX_TouchEventManager.h" -#include "SCA_ISensor.h" -#include "KX_TouchSensor.h" -#include "KX_GameObject.h" -#include "PHY_IPhysicsEnvironment.h" -#include "PHY_IPhysicsController.h" - - -KX_TouchEventManager::KX_TouchEventManager(class SCA_LogicManager* logicmgr, - PHY_IPhysicsEnvironment* physEnv) - : SCA_EventManager(logicmgr, TOUCH_EVENTMGR), - m_physEnv(physEnv) -{ - //notm_scene->addTouchCallback(STATIC_RESPONSE, KX_TouchEventManager::collisionResponse, this); - - //m_scene->addTouchCallback(OBJECT_RESPONSE, KX_TouchEventManager::collisionResponse, this); - //m_scene->addTouchCallback(SENSOR_RESPONSE, KX_TouchEventManager::collisionResponse, this); - - m_physEnv->AddTouchCallback(PHY_OBJECT_RESPONSE, KX_TouchEventManager::newCollisionResponse, this); - m_physEnv->AddTouchCallback(PHY_SENSOR_RESPONSE, KX_TouchEventManager::newCollisionResponse, this); - m_physEnv->AddTouchCallback(PHY_BROADPH_RESPONSE, KX_TouchEventManager::newBroadphaseResponse, this); - -} - -bool KX_TouchEventManager::NewHandleCollision(void* object1, void* object2, const PHY_CollData *coll_data) -{ - - PHY_IPhysicsController* obj1 = static_cast(object1); - PHY_IPhysicsController* obj2 = static_cast(object2); - - m_newCollisions.insert(NewCollision(obj1, obj2, coll_data)); - - return false; -} - - -bool KX_TouchEventManager::newCollisionResponse(void *client_data, - void *object1, - void *object2, - const PHY_CollData *coll_data) -{ - KX_TouchEventManager *touchmgr = (KX_TouchEventManager *) client_data; - touchmgr->NewHandleCollision(object1, object2, coll_data); - return false; -} - -bool KX_TouchEventManager::newBroadphaseResponse(void *client_data, - void *object1, - void *object2, - const PHY_CollData *coll_data) -{ - PHY_IPhysicsController* ctrl1 = static_cast(object1); - PHY_IPhysicsController* ctrl2 = static_cast(object2); - - KX_ClientObjectInfo *info1 = (ctrl1) ? static_cast(ctrl1->GetNewClientInfo()) : NULL; - KX_ClientObjectInfo *info2 = (ctrl2) ? static_cast(ctrl2->GetNewClientInfo()) : NULL; - - // This call back should only be called for controllers of Near and Radar sensor - if (!info1) - return true; - - // Get KX_GameObjects for callbacks - KX_GameObject* gobj1 = info1->m_gameobject; - KX_GameObject* gobj2 = (info2) ? info2->m_gameobject : NULL; - - bool has_py_callbacks = false; - -#ifdef WITH_PYTHON - // Consider callbacks for broadphase inclusion if it's a sensor object type - if (gobj1 && gobj2) - has_py_callbacks = gobj1->m_collisionCallbacks || gobj2->m_collisionCallbacks; -#else - (void)gobj1; - (void)gobj2; -#endif - - switch (info1->m_type) - { - case KX_ClientObjectInfo::SENSOR: - if (info1->m_sensors.size() == 1) - { - // only one sensor for this type of object - KX_TouchSensor* touchsensor = static_cast(*info1->m_sensors.begin()); - return touchsensor->BroadPhaseFilterCollision(object1, object2); - } - break; - case KX_ClientObjectInfo::OBSENSOR: - case KX_ClientObjectInfo::OBACTORSENSOR: - // this object may have multiple collision sensors, - // check is any of them is interested in this object - for (std::list::iterator it = info1->m_sensors.begin(); - it != info1->m_sensors.end(); - ++it) - { - if ((*it)->GetSensorType() == SCA_ISensor::ST_TOUCH) - { - KX_TouchSensor* touchsensor = static_cast(*it); - if (touchsensor->BroadPhaseSensorFilterCollision(object1, object2)) - return true; - } - } - - return has_py_callbacks; - - // quiet the compiler - case KX_ClientObjectInfo::STATIC: - case KX_ClientObjectInfo::ACTOR: - case KX_ClientObjectInfo::RESERVED1: - /* do nothing*/ - break; - } - return true; -} - -void KX_TouchEventManager::RegisterSensor(SCA_ISensor* sensor) -{ - KX_TouchSensor* touchsensor = static_cast(sensor); - if (m_sensors.AddBack(touchsensor)) - // the sensor was effectively inserted, register it - touchsensor->RegisterSumo(this); -} - -void KX_TouchEventManager::RemoveSensor(SCA_ISensor* sensor) -{ - KX_TouchSensor* touchsensor = static_cast(sensor); - if (touchsensor->Delink()) - // the sensor was effectively removed, unregister it - touchsensor->UnregisterSumo(this); -} - - - -void KX_TouchEventManager::EndFrame() -{ - SG_DList::iterator it(m_sensors); - for (it.begin();!it.end();++it) - { - (*it)->EndFrame(); - } -} - - - -void KX_TouchEventManager::NextFrame() -{ - SG_DList::iterator it(m_sensors); - for (it.begin();!it.end();++it) - (*it)->SynchronizeTransform(); - - for (std::set::iterator cit = m_newCollisions.begin(); cit != m_newCollisions.end(); ++cit) - { - // Controllers - PHY_IPhysicsController* ctrl1 = (*cit).first; - PHY_IPhysicsController* ctrl2 = (*cit).second; - - // Sensor iterator - list::iterator sit; - - // First client info - KX_ClientObjectInfo *client_info = static_cast(ctrl1->GetNewClientInfo()); - // First gameobject - KX_GameObject *kxObj1 = KX_GameObject::GetClientObject(client_info); - // Invoke sensor response for each object - if (client_info) { - for ( sit = client_info->m_sensors.begin(); sit != client_info->m_sensors.end(); ++sit) { - static_cast(*sit)->NewHandleCollision(ctrl1, ctrl2, NULL); - } - } - - // Second client info - client_info = static_cast(ctrl2->GetNewClientInfo()); - // Second gameobject - KX_GameObject *kxObj2 = KX_GameObject::GetClientObject(client_info); - if (client_info) { - for ( sit = client_info->m_sensors.begin(); sit != client_info->m_sensors.end(); ++sit) { - static_cast(*sit)->NewHandleCollision(ctrl2, ctrl1, NULL); - } - } - // Run python callbacks - PHY_CollData *colldata = cit->colldata; - kxObj1->RunCollisionCallbacks(kxObj2, colldata->m_point1, colldata->m_normal); - kxObj2->RunCollisionCallbacks(kxObj1, colldata->m_point2, -colldata->m_normal); - - delete cit->colldata; - } - - m_newCollisions.clear(); - - for (it.begin();!it.end();++it) - (*it)->Activate(m_logicmgr); - } - - -KX_TouchEventManager::NewCollision::NewCollision(PHY_IPhysicsController *first, - PHY_IPhysicsController *second, - const PHY_CollData *colldata) - : first(first), second(second), colldata(new PHY_CollData(*colldata)) -{} - -KX_TouchEventManager::NewCollision::NewCollision(const NewCollision &to_copy) - : first(to_copy.first), second(to_copy.second), colldata(to_copy.colldata) -{} - -bool KX_TouchEventManager::NewCollision::operator<(const NewCollision &other) const -{ - //see strict weak ordering: https://support.microsoft.com/en-us/kb/949171 - if (first == other.first) { - if (second == other.second) { - return colldata < other.colldata; - } - return second < other.second; - } - return first < other.first; -} diff --git a/source/gameengine/Ketsji/KX_TouchEventManager.h b/source/gameengine/Ketsji/KX_TouchEventManager.h deleted file mode 100644 index d9c6fdad307..00000000000 --- a/source/gameengine/Ketsji/KX_TouchEventManager.h +++ /dev/null @@ -1,109 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_TouchEventManager.h - * \ingroup ketsji - */ - -#ifndef __KX_TOUCHEVENTMANAGER_H__ -#define __KX_TOUCHEVENTMANAGER_H__ - - -#include "SCA_EventManager.h" -#include "KX_TouchSensor.h" -#include "KX_GameObject.h" - -#include -#include - -class SCA_ISensor; -class PHY_IPhysicsEnvironment; - -class KX_TouchEventManager : public SCA_EventManager -{ - /** - * Contains two colliding objects and the first contact point. - */ - class NewCollision { - public: - PHY_IPhysicsController *first; - PHY_IPhysicsController *second; - PHY_CollData *colldata; - - /** - * Creates a copy of the given PHY_CollData; freeing that copy should be done by the owner of - * the NewCollision object. - * - * This allows us to efficiently store NewCollision objects in a std::set without creating more - * copies of colldata, as the NewCollision copy constructor reuses the pointer and doesn't clone - * it again. */ - NewCollision(PHY_IPhysicsController *first, - PHY_IPhysicsController *second, - const PHY_CollData *colldata); - NewCollision(const NewCollision &to_copy); - bool operator<(const NewCollision &other) const; - }; - - PHY_IPhysicsEnvironment* m_physEnv; - - std::set m_newCollisions; - - - static bool newCollisionResponse(void *client_data, - void *object1, - void *object2, - const PHY_CollData *coll_data); - - static bool newBroadphaseResponse(void *client_data, - void *object1, - void *object2, - const PHY_CollData *coll_data); - - virtual bool NewHandleCollision(void* obj1,void* obj2, - const PHY_CollData * coll_data); - - - - - -public: - KX_TouchEventManager(class SCA_LogicManager* logicmgr, - PHY_IPhysicsEnvironment* physEnv); - virtual void NextFrame(); - virtual void EndFrame(); - virtual void RegisterSensor(SCA_ISensor* sensor); - virtual void RemoveSensor(SCA_ISensor* sensor); - SCA_LogicManager* GetLogicManager() { return m_logicmgr;} - PHY_IPhysicsEnvironment *GetPhysicsEnvironment() { return m_physEnv; } - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_TouchEventManager") -#endif -}; - -#endif /* __KX_TOUCHEVENTMANAGER_H__ */ diff --git a/source/gameengine/Ketsji/KX_TouchSensor.cpp b/source/gameengine/Ketsji/KX_TouchSensor.cpp deleted file mode 100644 index 593d3e844e8..00000000000 --- a/source/gameengine/Ketsji/KX_TouchSensor.cpp +++ /dev/null @@ -1,362 +0,0 @@ -/* - * Senses touch and collision events - * - * - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_TouchSensor.cpp - * \ingroup ketsji - */ - - -#include "KX_TouchSensor.h" -#include "SCA_EventManager.h" -#include "SCA_LogicManager.h" -#include "KX_GameObject.h" -#include "KX_TouchEventManager.h" - -#include "PHY_IPhysicsController.h" - -#include "RAS_MeshObject.h" - -#include -#include "PHY_IPhysicsEnvironment.h" - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -void KX_TouchSensor::SynchronizeTransform() -{ - // the touch sensor does not require any synchronization: it uses - // the same physical object which is already synchronized by Blender -} - - -void KX_TouchSensor::EndFrame() -{ - m_colliders->ReleaseAndRemoveAll(); - m_hitObject = NULL; - m_bTriggered = false; - m_bColliderHash = 0; -} - -void KX_TouchSensor::UnregisterToManager() -{ - // before unregistering the sensor, make sure we release all references - EndFrame(); - SCA_ISensor::UnregisterToManager(); -} - -bool KX_TouchSensor::Evaluate() -{ - bool result = false; - bool reset = m_reset && m_level; - m_reset = false; - if (m_bTriggered != m_bLastTriggered) - { - m_bLastTriggered = m_bTriggered; - if (!m_bTriggered) - m_hitObject = NULL; - result = true; - } - if (reset) - // force an event - result = true; - - if (m_bTouchPulse) { /* pulse on changes to the colliders */ - int count = m_colliders->GetCount(); - - if (m_bLastCount!=count || m_bColliderHash!=m_bLastColliderHash) { - m_bLastCount = count; - m_bLastColliderHash= m_bColliderHash; - result = true; - } - } - return result; -} - -KX_TouchSensor::KX_TouchSensor(SCA_EventManager* eventmgr,KX_GameObject* gameobj,bool bFindMaterial,bool bTouchPulse,const STR_String& touchedpropname) -:SCA_ISensor(gameobj,eventmgr), -m_touchedpropname(touchedpropname), -m_bFindMaterial(bFindMaterial), -m_bTouchPulse(bTouchPulse), -m_hitMaterial("") -/*m_sumoObj(sumoObj),*/ -{ -// KX_TouchEventManager* touchmgr = (KX_TouchEventManager*) eventmgr; -// m_resptable = touchmgr->GetResponseTable(); - -// m_solidHandle = m_sumoObj->getObjectHandle(); - - m_colliders = new CListValue(); - - KX_ClientObjectInfo *client_info = gameobj->getClientInfo(); - //client_info->m_gameobject = gameobj; - //client_info->m_auxilary_info = NULL; - client_info->m_sensors.push_back(this); - - m_physCtrl = gameobj->GetPhysicsController(); - MT_assert( !gameobj->GetPhysicsController() || m_physCtrl ); - Init(); -} - -void KX_TouchSensor::Init() -{ - m_bCollision = false; - m_bTriggered = false; - m_bLastTriggered = (m_invert)?true:false; - m_bLastCount = 0; - m_bColliderHash = m_bLastColliderHash = 0; - m_hitObject = NULL; - m_reset = true; -} - -KX_TouchSensor::~KX_TouchSensor() -{ - //DT_ClearObjectResponse(m_resptable,m_solidHandle); - m_colliders->Release(); -} - -CValue* KX_TouchSensor::GetReplica() -{ - KX_TouchSensor* replica = new KX_TouchSensor(*this); - replica->ProcessReplica(); - return replica; -} - -void KX_TouchSensor::ProcessReplica() -{ - SCA_ISensor::ProcessReplica(); - m_colliders = new CListValue(); - Init(); -} - -void KX_TouchSensor::ReParent(SCA_IObject* parent) -{ - KX_GameObject *gameobj = static_cast(parent); - PHY_IPhysicsController *sphy = ((KX_GameObject*)parent)->GetPhysicsController(); - if (sphy) - m_physCtrl = sphy; - -// m_solidHandle = m_sumoObj->getObjectHandle(); - KX_ClientObjectInfo *client_info = gameobj->getClientInfo(); - //client_info->m_gameobject = gameobj; - //client_info->m_auxilary_info = NULL; - - client_info->m_sensors.push_back(this); - SCA_ISensor::ReParent(parent); -} - -void KX_TouchSensor::RegisterSumo(KX_TouchEventManager *touchman) -{ - if (m_physCtrl) - { - if (touchman->GetPhysicsEnvironment()->RequestCollisionCallback(m_physCtrl)) - { - KX_ClientObjectInfo *client_info = static_cast(m_physCtrl->GetNewClientInfo()); - if (client_info->isSensor()) - touchman->GetPhysicsEnvironment()->AddSensor(m_physCtrl); - } - } -} -void KX_TouchSensor::UnregisterSumo(KX_TouchEventManager* touchman) -{ - if (m_physCtrl) - { - if (touchman->GetPhysicsEnvironment()->RemoveCollisionCallback(m_physCtrl)) - { - // no more sensor on the controller, can remove it if it is a sensor object - KX_ClientObjectInfo *client_info = static_cast(m_physCtrl->GetNewClientInfo()); - if (client_info->isSensor()) - touchman->GetPhysicsEnvironment()->RemoveSensor(m_physCtrl); - } - } -} - -// this function is called only for sensor objects -// return true if the controller can collide with the object -bool KX_TouchSensor::BroadPhaseSensorFilterCollision(void*obj1,void*obj2) -{ - assert(obj1==m_physCtrl && obj2); - - KX_GameObject* myobj = (KX_GameObject*)GetParent(); - KX_GameObject* myparent = myobj->GetParent(); - KX_ClientObjectInfo *client_info = static_cast(((PHY_IPhysicsController*)obj2)->GetNewClientInfo()); - KX_ClientObjectInfo *my_client_info = static_cast(m_physCtrl->GetNewClientInfo()); - KX_GameObject* otherobj = ( client_info ? client_info->m_gameobject : NULL); - - // we can only check on persistent characteristic: m_link and m_suspended are not - // good candidate because they are transient. That must be handled at another level - if (!otherobj || - otherobj == myparent || // don't interact with our parent - (my_client_info->m_type == KX_ClientObjectInfo::OBACTORSENSOR && - client_info->m_type != KX_ClientObjectInfo::ACTOR)) // only with actor objects - return false; - - bool found = m_touchedpropname.IsEmpty(); - if (!found) - { - if (m_bFindMaterial) { - for (unsigned int i = 0; i < otherobj->GetMeshCount(); ++i) { - RAS_MeshObject *meshObj = otherobj->GetMesh(i); - for (unsigned int j = 0; j < meshObj->NumMaterials(); ++j) { - found = strcmp(m_touchedpropname.ReadPtr(), meshObj->GetMaterialName(j).ReadPtr() + 2) == 0; - if (found) - break; - } - } - } - else { - found = (otherobj->GetProperty(m_touchedpropname) != NULL); - } - } - return found; -} - -bool KX_TouchSensor::NewHandleCollision(void*object1,void*object2,const PHY_CollData* colldata) -{ -// KX_TouchEventManager* toucheventmgr = (KX_TouchEventManager*)m_eventmgr; - KX_GameObject* parent = (KX_GameObject*)GetParent(); - - // need the mapping from PHY_IPhysicsController to gameobjects now - - KX_ClientObjectInfo *client_info = static_cast (object1 == m_physCtrl? - ((PHY_IPhysicsController*)object2)->GetNewClientInfo(): - ((PHY_IPhysicsController*)object1)->GetNewClientInfo()); - - KX_GameObject* gameobj = ( client_info ? - client_info->m_gameobject : - NULL); - - // add the same check as in SCA_ISensor::Activate(), - // we don't want to record collision when the sensor is not active. - if (m_links && !m_suspended && - gameobj && (gameobj != parent) && client_info->isActor()) - { - - bool found = m_touchedpropname.IsEmpty(); - bool hitMaterial = false; - if (!found) - { - if (m_bFindMaterial) { - for (unsigned int i = 0; i < gameobj->GetMeshCount(); ++i) { - RAS_MeshObject *meshObj = gameobj->GetMesh(i); - for (unsigned int j = 0; j < meshObj->NumMaterials(); ++j) { - found = strcmp(m_touchedpropname.ReadPtr(), meshObj->GetMaterialName(j).ReadPtr() + 2) == 0; - if (found) { - hitMaterial = true; - break; - } - } - } - } - else { - found = (gameobj->GetProperty(m_touchedpropname) != NULL); - } - } - if (found) - { - if (!m_colliders->SearchValue(gameobj)) { - m_colliders->Add(gameobj->AddRef()); - - if (m_bTouchPulse) - m_bColliderHash += (uint_ptr)(static_cast(&gameobj)); - } - m_bTriggered = true; - m_hitObject = gameobj; - m_hitMaterial = hitMaterial; - //printf("KX_TouchSensor::HandleCollision\n"); - } - - } - return false; // was DT_CONTINUE but this was defined in sumo as false. -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject KX_TouchSensor::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_TouchSensor", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &SCA_ISensor::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_TouchSensor::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_TouchSensor::Attributes[] = { - KX_PYATTRIBUTE_STRING_RW("propName",0,MAX_PROP_NAME,false,KX_TouchSensor,m_touchedpropname), - KX_PYATTRIBUTE_BOOL_RW("useMaterial",KX_TouchSensor,m_bFindMaterial), - KX_PYATTRIBUTE_BOOL_RW("usePulseCollision",KX_TouchSensor,m_bTouchPulse), - KX_PYATTRIBUTE_STRING_RO("hitMaterial", KX_TouchSensor, m_hitMaterial), - KX_PYATTRIBUTE_RO_FUNCTION("hitObject", KX_TouchSensor, pyattr_get_object_hit), - KX_PYATTRIBUTE_RO_FUNCTION("hitObjectList", KX_TouchSensor, pyattr_get_object_hit_list), - { NULL } //Sentinel -}; - -/* Python API */ - -PyObject *KX_TouchSensor::pyattr_get_object_hit(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_TouchSensor* self = static_cast(self_v); - - if (self->m_hitObject) - return self->m_hitObject->GetProxy(); - else - Py_RETURN_NONE; -} - -PyObject *KX_TouchSensor::pyattr_get_object_hit_list(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_TouchSensor* self = static_cast(self_v); - return self->m_colliders->GetProxy(); -} - -#endif - -/* eof */ diff --git a/source/gameengine/Ketsji/KX_TouchSensor.h b/source/gameengine/Ketsji/KX_TouchSensor.h deleted file mode 100644 index e1b5725a32b..00000000000 --- a/source/gameengine/Ketsji/KX_TouchSensor.h +++ /dev/null @@ -1,138 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_TouchSensor.h - * \ingroup ketsji - * \brief Senses touch and collision events - */ - -#ifndef __KX_TOUCHSENSOR_H__ -#define __KX_TOUCHSENSOR_H__ - -#include "SCA_ISensor.h" -#include "EXP_ListValue.h" - -struct PHY_CollData; - -#include "KX_ClientObjectInfo.h" - -#if defined(_WIN64) -typedef unsigned __int64 uint_ptr; -#else -typedef unsigned long uint_ptr; -#endif - -class KX_TouchEventManager; - -class KX_TouchSensor : public SCA_ISensor -{ -protected: - Py_Header - - /** - * The sensor should only look for objects with this property. - */ - STR_String m_touchedpropname; - bool m_bFindMaterial; - bool m_bTouchPulse; /* changes in the colliding objects trigger pulses */ - - class PHY_IPhysicsController* m_physCtrl; - - bool m_bCollision; - bool m_bTriggered; - bool m_bLastTriggered; - - // Use with m_bTouchPulse to detect changes - int m_bLastCount; /* size of m_colliders last tick */ - uint_ptr m_bColliderHash; /* hash collision objects pointers to trigger in case one object collides and another takes its place */ - uint_ptr m_bLastColliderHash; - - SCA_IObject* m_hitObject; - class CListValue* m_colliders; - STR_String m_hitMaterial; - -public: - KX_TouchSensor(class SCA_EventManager* eventmgr, - class KX_GameObject* gameobj, - bool bFindMaterial, - bool bTouchPulse, - const STR_String& touchedpropname); - virtual ~KX_TouchSensor(); - - virtual CValue* GetReplica(); - virtual void ProcessReplica(); - virtual void SynchronizeTransform(); - virtual bool Evaluate(); - virtual void Init(); - virtual void ReParent(SCA_IObject* parent); - - virtual void RegisterSumo(KX_TouchEventManager* touchman); - virtual void UnregisterSumo(KX_TouchEventManager* touchman); - virtual void UnregisterToManager(); - -#if 0 - virtual DT_Bool HandleCollision(void* obj1,void* obj2, - const DT_CollData * coll_data); -#endif - - virtual bool NewHandleCollision(void*obj1,void*obj2,const PHY_CollData* colldata); - - // Allows to do pre-filtering and save computation time - // obj1 = sensor physical controller, obj2 = physical controller of second object - // return value = true if collision should be checked on pair of object - virtual bool BroadPhaseFilterCollision(void*obj1,void*obj2) { return true; } - virtual bool BroadPhaseSensorFilterCollision(void*obj1,void*obj2); - virtual sensortype GetSensorType() { return ST_TOUCH; } - - - virtual bool IsPositiveTrigger() { - bool result = m_bTriggered; - if (m_invert) result = !result; - return result; - } - - virtual void EndFrame(); - - class PHY_IPhysicsController* GetPhysicsController() { return m_physCtrl; } - - - // todo: put some info for collision maybe - -#ifdef WITH_PYTHON - - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - - static PyObject* pyattr_get_object_hit(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_object_hit_list(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - -#endif - -}; - -#endif /* __KX_TOUCHSENSOR_H__ */ diff --git a/source/gameengine/Ketsji/KX_TrackToActuator.cpp b/source/gameengine/Ketsji/KX_TrackToActuator.cpp deleted file mode 100644 index a8fa9b0815d..00000000000 --- a/source/gameengine/Ketsji/KX_TrackToActuator.cpp +++ /dev/null @@ -1,430 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_TrackToActuator.cpp - * \ingroup ketsji - * - * Replace the mesh for this actuator's parent - */ - -/* m_trackflag is used to determine the forward tracking direction - * m_upflag for the up direction - * normal situation is +y for forward, +z for up */ - -#include "MT_Scalar.h" -#include "SCA_IActuator.h" -#include "KX_TrackToActuator.h" -#include "SCA_IScene.h" -#include "SCA_LogicManager.h" -#include -#include -#include "KX_GameObject.h" - -#include "EXP_PyObjectPlus.h" - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -KX_TrackToActuator::KX_TrackToActuator(SCA_IObject *gameobj, - SCA_IObject *ob, - int time, - bool allow3D, - int trackflag, - int upflag) - : SCA_IActuator(gameobj, KX_ACT_TRACKTO) -{ - m_time = time; - m_allow3D = allow3D; - m_object = ob; - m_trackflag = trackflag; - m_upflag = upflag; - m_parentobj = 0; - - if (m_object) - m_object->RegisterActuator(this); - - { - // if the object is vertex parented, don't check parent orientation as the link is broken - if (!((KX_GameObject*)gameobj)->IsVertexParent()) { - m_parentobj = ((KX_GameObject*)gameobj)->GetParent(); // check if the object is parented - if (m_parentobj) { - // if so, store the initial local rotation - // this is needed to revert the effect of the parent inverse node (TBC) - m_parentlocalmat = m_parentobj->GetSGNode()->GetLocalOrientation(); - // use registration mechanism rather than AddRef, it creates zombie objects - m_parentobj->RegisterActuator(this); - } - } - } - -} /* End of constructor */ - - - -/* old function from Blender */ -static MT_Matrix3x3 EulToMat3(float eul[3]) -{ - MT_Matrix3x3 mat; - float ci, cj, ch, si, sj, sh, cc, cs, sc, ss; - - ci = cosf(eul[0]); - cj = cosf(eul[1]); - ch = cosf(eul[2]); - si = sinf(eul[0]); - sj = sinf(eul[1]); - sh = sinf(eul[2]); - cc = ci*ch; - cs = ci*sh; - sc = si*ch; - ss = si*sh; - - mat[0][0] = cj*ch; - mat[1][0] = sj*sc-cs; - mat[2][0] = sj*cc+ss; - mat[0][1] = cj*sh; - mat[1][1] = sj*ss+cc; - mat[2][1] = sj*cs-sc; - mat[0][2] = -sj; - mat[1][2] = cj*si; - mat[2][2] = cj*ci; - - return mat; -} - - - -/* old function from Blender */ -static void Mat3ToEulOld(MT_Matrix3x3 mat, float eul[3]) -{ - const float cy = sqrtf(mat[0][0] * mat[0][0] + mat[0][1] * mat[0][1]); - - if (cy > (float)(16.0f * FLT_EPSILON)) { - eul[0] = atan2f( mat[1][2], mat[2][2]); - eul[1] = atan2f(-mat[0][2], cy); - eul[2] = atan2f( mat[0][1], mat[0][0]); - } - else { - eul[0] = atan2f(-mat[2][1], mat[1][1]); - eul[1] = atan2f(-mat[0][2], cy); - eul[2] = 0.0f; - } -} - - - -/* old function from Blender */ -static void compatible_eulFast(float *eul, float *oldrot) -{ - float dx, dy, dz; - - /* angular difference of 360 degrees */ - - dx = eul[0] - oldrot[0]; - dy = eul[1] - oldrot[1]; - dz = eul[2] - oldrot[2]; - - if (fabsf(dx) > (float)MT_PI) { - if (dx > 0.0f) eul[0] -= (float)MT_2_PI; else eul[0] += (float)MT_2_PI; - } - if (fabsf(dy) > (float)MT_PI) { - if (dy > 0.0f) eul[1] -= (float)MT_2_PI; else eul[1] += (float)MT_2_PI; - } - if (fabsf(dz) > (float)MT_PI) { - if (dz > 0.0f) eul[2] -= (float)MT_2_PI; else eul[2] += (float)MT_2_PI; - } -} - - - -static MT_Matrix3x3 matrix3x3_interpol(MT_Matrix3x3 oldmat, MT_Matrix3x3 mat, int m_time) -{ - float eul[3], oldeul[3]; - - Mat3ToEulOld(oldmat, oldeul); - Mat3ToEulOld(mat, eul); - compatible_eulFast(eul, oldeul); - - eul[0] = (m_time * oldeul[0] + eul[0]) / (1.0f + m_time); - eul[1] = (m_time * oldeul[1] + eul[1]) / (1.0f + m_time); - eul[2] = (m_time * oldeul[2] + eul[2]) / (1.0f + m_time); - - return EulToMat3(eul); -} - -static float basis_cross(int n, int m) -{ - switch (n - m) { - case 1: - case -2: - return 1.0f; - - case -1: - case 2: - return -1.0f; - - default: - return 0.0f; - } -} - -/* vectomat function obtained from constrain.c and modified to work with MOTO library */ -static MT_Matrix3x3 vectomat(MT_Vector3 vec, short axis, short upflag, short threedimup) -{ - MT_Matrix3x3 mat; - MT_Vector3 y(MT_Scalar(0.0f), MT_Scalar(1.0f), MT_Scalar(0.0f)); - MT_Vector3 z(MT_Scalar(0.0f), MT_Scalar(0.0f), MT_Scalar(1.0f)); /* world Z axis is the global up axis */ - MT_Vector3 proj; - MT_Vector3 right; - MT_Scalar mul; - int right_index; - - /* Normalized Vec vector*/ - vec = vec.safe_normalized_vec(z); - - /* if 2D doesn't move the up vector */ - if (!threedimup) { - vec.setValue(MT_Scalar(vec[0]), MT_Scalar(vec[1]), MT_Scalar(0.0f)); - vec = (vec - z.dot(vec)*z).safe_normalized_vec(z); - } - - if (axis > 2) - axis -= 3; - else - vec = -vec; - - /* project the up vector onto the plane specified by vec */ - /* first z onto vec... */ - mul = z.dot(vec) / vec.dot(vec); - proj = vec * mul; - /* then onto the plane */ - proj = z - proj; - /* proj specifies the transformation of the up axis */ - proj = proj.safe_normalized_vec(y); - - /* Normalized cross product of vec and proj specifies transformation of the right axis */ - right = proj.cross(vec); - right.normalize(); - - if (axis != upflag) { - right_index = 3 - axis - upflag; - - /* account for up direction, track direction */ - right = right * basis_cross(axis, upflag); - mat.setRow(right_index, right); - mat.setRow(upflag, proj); - mat.setRow(axis, vec); - mat = mat.inverse(); - } - /* identity matrix - don't do anything if the two axes are the same */ - else { - mat.setIdentity(); - } - - return mat; -} - -KX_TrackToActuator::~KX_TrackToActuator() -{ - if (m_object) - m_object->UnregisterActuator(this); - if (m_parentobj) - m_parentobj->UnregisterActuator(this); -} /* end of destructor */ - -void KX_TrackToActuator::ProcessReplica() -{ - // the replica is tracking the same object => register it - if (m_object) - m_object->RegisterActuator(this); - if (m_parentobj) - m_parentobj->RegisterActuator(this); - SCA_IActuator::ProcessReplica(); -} - - -bool KX_TrackToActuator::UnlinkObject(SCA_IObject* clientobj) -{ - if (clientobj == m_object) - { - // this object is being deleted, we cannot continue to track it. - m_object = NULL; - return true; - } - if (clientobj == m_parentobj) - { - m_parentobj = NULL; - return true; - } - return false; -} - -void KX_TrackToActuator::Relink(CTR_Map *obj_map) -{ - void **h_obj = (*obj_map)[m_object]; - if (h_obj) { - if (m_object) - m_object->UnregisterActuator(this); - m_object = (SCA_IObject*)(*h_obj); - m_object->RegisterActuator(this); - } - - void **h_parobj = (*obj_map)[m_parentobj]; - if (h_parobj) { - if (m_parentobj) - m_parentobj->UnregisterActuator(this); - m_parentobj= (KX_GameObject*)(*h_parobj); - m_parentobj->RegisterActuator(this); - } -} - - -bool KX_TrackToActuator::Update(double curtime, bool frame) -{ - bool result = false; - bool bNegativeEvent = IsNegativeEvent(); - RemoveAllEvents(); - - if (bNegativeEvent) - { - // do nothing on negative events - } - else if (m_object) - { - KX_GameObject* curobj = (KX_GameObject*) GetParent(); - MT_Vector3 dir = curobj->NodeGetWorldPosition() - ((KX_GameObject*)m_object)->NodeGetWorldPosition(); - MT_Matrix3x3 mat; - MT_Matrix3x3 oldmat; - - mat = vectomat(dir, m_trackflag, m_upflag, m_allow3D); - oldmat = curobj->NodeGetWorldOrientation(); - - /* erwin should rewrite this! */ - mat = matrix3x3_interpol(oldmat, mat, m_time); - - /* check if the model is parented and calculate the child transform */ - if (m_parentobj) { - - MT_Point3 localpos; - localpos = curobj->GetSGNode()->GetLocalPosition(); - // Get the inverse of the parent matrix - MT_Matrix3x3 parentmatinv; - parentmatinv = m_parentobj->NodeGetWorldOrientation().inverse(); - // transform the local coordinate system into the parents system - mat = parentmatinv * mat; - // append the initial parent local rotation matrix - mat = m_parentlocalmat * mat; - - // set the models tranformation properties - curobj->NodeSetLocalOrientation(mat); - curobj->NodeSetLocalPosition(localpos); - //curobj->UpdateTransform(); - } - else { - curobj->NodeSetLocalOrientation(mat); - } - - result = true; - } - - return result; -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject KX_TrackToActuator::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_TrackToActuator", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &SCA_IActuator::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_TrackToActuator::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_TrackToActuator::Attributes[] = { - KX_PYATTRIBUTE_INT_RW("time",0,1000,true,KX_TrackToActuator,m_time), - KX_PYATTRIBUTE_BOOL_RW("use3D",KX_TrackToActuator,m_allow3D), - KX_PYATTRIBUTE_INT_RW("upAxis", 0, 2, true, KX_TrackToActuator,m_upflag), - KX_PYATTRIBUTE_INT_RW("trackAxis", 0, 5, true, KX_TrackToActuator,m_trackflag), - KX_PYATTRIBUTE_RW_FUNCTION("object", KX_TrackToActuator, pyattr_get_object, pyattr_set_object), - - { NULL } //Sentinel -}; - -PyObject *KX_TrackToActuator::pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_TrackToActuator* actuator = static_cast(self); - if (!actuator->m_object) - Py_RETURN_NONE; - else - return actuator->m_object->GetProxy(); -} - -int KX_TrackToActuator::pyattr_set_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_TrackToActuator* actuator = static_cast(self); - KX_GameObject *gameobj; - - if (!ConvertPythonToGameObject(actuator->GetLogicManager(), value, &gameobj, true, "actuator.object = value: KX_TrackToActuator")) - return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error - - if (actuator->m_object != NULL) - actuator->m_object->UnregisterActuator(actuator); - - actuator->m_object = (SCA_IObject*) gameobj; - - if (actuator->m_object) - actuator->m_object->RegisterActuator(actuator); - - return PY_SET_ATTR_SUCCESS; -} - -#endif // WITH_PYTHON - -/* eof */ diff --git a/source/gameengine/Ketsji/KX_TrackToActuator.h b/source/gameengine/Ketsji/KX_TrackToActuator.h deleted file mode 100644 index 124014eede2..00000000000 --- a/source/gameengine/Ketsji/KX_TrackToActuator.h +++ /dev/null @@ -1,98 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_TrackToActuator.h - * \ingroup ketsji - */ - -#ifndef __KX_TRACKTOACTUATOR_H__ -#define __KX_TRACKTOACTUATOR_H__ - -#include "SCA_IActuator.h" -#include "SCA_IObject.h" -#include "MT_Matrix3x3.h" -#include "KX_GameObject.h" - - -class KX_TrackToActuator : public SCA_IActuator -{ - Py_Header - // Object reference. Actually, we use the object's 'life' - SCA_IObject* m_object; - // 3d toggle - bool m_allow3D; - // time field - int m_time; - int m_trackflag; - int m_upflag; - - MT_Matrix3x3 m_parentlocalmat; - KX_GameObject* m_parentobj; - - public: - KX_TrackToActuator(SCA_IObject* gameobj, SCA_IObject *ob, int time, - bool threedee,int trackflag,int upflag); - virtual ~KX_TrackToActuator(); - virtual CValue* GetReplica() { - KX_TrackToActuator* replica = new KX_TrackToActuator(*this); - replica->ProcessReplica(); - return replica; - }; - - virtual void ProcessReplica(); - virtual bool UnlinkObject(SCA_IObject* clientobj); - virtual void Relink(CTR_Map *obj_map); - virtual bool Update(double curtime, bool frame); - - //Python Interface - enum UpAxis { - KX_TRACK_UPAXIS_POS_X = 0, - KX_TRACK_UPAXIS_POS_Y, - KX_TRACK_UPAXIS_POS_Z - }; - enum TrackAxis { - KX_TRACK_TRAXIS_POS_X = 0, - KX_TRACK_TRAXIS_POS_Y, - KX_TRACK_TRAXIS_POS_Z, - KX_TRACK_TRAXIS_NEG_X, - KX_TRACK_TRAXIS_NEG_Y, - KX_TRACK_TRAXIS_NEG_Z - }; - -#ifdef WITH_PYTHON - - /* Python part */ - - /* These are used to get and set m_ob */ - static PyObject *pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - -#endif /* WITH_PYTHON */ - -}; /* end of class KX_TrackToActuator : public KX_EditObjectActuator */ - -#endif /* __KX_TRACKTOACTUATOR_H__ */ diff --git a/source/gameengine/Ketsji/KX_VehicleWrapper.cpp b/source/gameengine/Ketsji/KX_VehicleWrapper.cpp deleted file mode 100644 index ddae645802c..00000000000 --- a/source/gameengine/Ketsji/KX_VehicleWrapper.cpp +++ /dev/null @@ -1,380 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_VehicleWrapper.cpp - * \ingroup ketsji - */ - -#include "EXP_PyObjectPlus.h" - -#include "KX_VehicleWrapper.h" -#include "PHY_IPhysicsEnvironment.h" -#include "PHY_IVehicle.h" -#include "KX_PyMath.h" -#include "KX_GameObject.h" -#include "KX_MotionState.h" -#include "KX_PythonInit.h" - -KX_VehicleWrapper::KX_VehicleWrapper( - PHY_IVehicle* vehicle, - PHY_IPhysicsEnvironment* physenv) : - PyObjectPlus(), - m_vehicle(vehicle), - m_physenv(physenv) -{ -} - -KX_VehicleWrapper::~KX_VehicleWrapper() -{ - int numMotion = m_motionStates.size(); - for (int i=0;i= vehicle->GetNumWheels()) { - PyErr_Format(PyExc_ValueError, - "%s(...): wheel index %d out of range (0 to %d).", method, i, vehicle->GetNumWheels() - 1); - return true; - } - else { - return false; - } -} - -#define WHEEL_INDEX_CHECK_OR_RETURN(i, method) \ - if (raise_exc_wheel(m_vehicle, i, method)) {return NULL;} (void)0 - - -PyObject *KX_VehicleWrapper::PyAddWheel(PyObject *args) -{ - - PyObject *pylistPos,*pylistDir,*pylistAxleDir; - PyObject *wheelGameObject; - float suspensionRestLength,wheelRadius; - int hasSteering; - - - if (PyArg_ParseTuple(args,"OOOOffi:addWheel",&wheelGameObject,&pylistPos,&pylistDir,&pylistAxleDir,&suspensionRestLength,&wheelRadius,&hasSteering)) - { - KX_GameObject *gameOb; - if (!ConvertPythonToGameObject(KX_GetActiveScene()->GetLogicManager(), wheelGameObject, &gameOb, false, "vehicle.addWheel(...): KX_VehicleWrapper (first argument)")) - return NULL; - - if (gameOb->GetSGNode()) - { - MT_Vector3 attachPos,attachDir,attachAxle; - if (!PyVecTo(pylistPos,attachPos)) { - PyErr_SetString(PyExc_AttributeError, - "addWheel(...) Unable to add wheel. attachPos must be a vector with 3 elements."); - return NULL; - } - if (!PyVecTo(pylistDir,attachDir)) { - PyErr_SetString(PyExc_AttributeError, - "addWheel(...) Unable to add wheel. downDir must be a vector with 3 elements."); - return NULL; - } - if (!PyVecTo(pylistAxleDir,attachAxle)) { - PyErr_SetString(PyExc_AttributeError, - "addWheel(...) Unable to add wheel. axleDir must be a vector with 3 elements."); - return NULL; - } - - //someone reverse some conventions inside Bullet (axle winding) - attachAxle = -attachAxle; - - if (wheelRadius <= 0) { - PyErr_SetString(PyExc_AttributeError, - "addWheel(...) Unable to add wheel. wheelRadius must be positive."); - return NULL; - } - - PHY_IMotionState *motionState = new KX_MotionState(gameOb->GetSGNode()); - m_vehicle->AddWheel(motionState,attachPos,attachDir,attachAxle,suspensionRestLength,wheelRadius,hasSteering); - } - - } else { - return NULL; - } - Py_RETURN_NONE; -} - - -PyObject *KX_VehicleWrapper::PyGetWheelPosition(PyObject *args) -{ - - int wheelIndex; - - if (PyArg_ParseTuple(args,"i:getWheelPosition",&wheelIndex)) - { - float position[3]; - WHEEL_INDEX_CHECK_OR_RETURN(wheelIndex, "getWheelPosition"); - - m_vehicle->GetWheelPosition(wheelIndex,position[0],position[1],position[2]); - MT_Vector3 pos(position[0],position[1],position[2]); - return PyObjectFrom(pos); - } - return NULL; -} - -PyObject *KX_VehicleWrapper::PyGetWheelRotation(PyObject *args) -{ - int wheelIndex; - if (PyArg_ParseTuple(args,"i:getWheelRotation",&wheelIndex)) - { - WHEEL_INDEX_CHECK_OR_RETURN(wheelIndex, "getWheelRotation"); - - return PyFloat_FromDouble(m_vehicle->GetWheelRotation(wheelIndex)); - } - return NULL; -} - -PyObject *KX_VehicleWrapper::PyGetWheelOrientationQuaternion(PyObject *args) -{ - int wheelIndex; - if (PyArg_ParseTuple(args,"i:getWheelOrientationQuaternion",&wheelIndex)) - { - float orn[4]; - WHEEL_INDEX_CHECK_OR_RETURN(wheelIndex, "getWheelOrientationQuaternion"); - - m_vehicle->GetWheelOrientationQuaternion(wheelIndex,orn[0],orn[1],orn[2],orn[3]); - MT_Quaternion quatorn(orn[0],orn[1],orn[2],orn[3]); - MT_Matrix3x3 ornmat(quatorn); - return PyObjectFrom(ornmat); - } - return NULL; - -} - - -PyObject *KX_VehicleWrapper::PyGetNumWheels(PyObject *args) -{ - return PyLong_FromLong(m_vehicle->GetNumWheels()); -} - - -PyObject *KX_VehicleWrapper::PyGetConstraintId(PyObject *args) -{ - return PyLong_FromLong(m_vehicle->GetUserConstraintId()); -} - - -PyObject *KX_VehicleWrapper::PyApplyEngineForce(PyObject *args) -{ - float force; - int wheelIndex; - - if (PyArg_ParseTuple(args,"fi:applyEngineForce",&force,&wheelIndex)) - { - WHEEL_INDEX_CHECK_OR_RETURN(wheelIndex, "applyEngineForce"); - - force *= -1.f;//someone reverse some conventions inside Bullet (axle winding) - m_vehicle->ApplyEngineForce(force,wheelIndex); - } - else { - return NULL; - } - Py_RETURN_NONE; -} - -PyObject *KX_VehicleWrapper::PySetTyreFriction(PyObject *args) -{ - float wheelFriction; - int wheelIndex; - - if (PyArg_ParseTuple(args,"fi:setTyreFriction",&wheelFriction,&wheelIndex)) - { - WHEEL_INDEX_CHECK_OR_RETURN(wheelIndex, "setTyreFriction"); - - m_vehicle->SetWheelFriction(wheelFriction,wheelIndex); - } - else { - return NULL; - } - Py_RETURN_NONE; -} - -PyObject *KX_VehicleWrapper::PySetSuspensionStiffness(PyObject *args) -{ - float suspensionStiffness; - int wheelIndex; - - if (PyArg_ParseTuple(args,"fi:setSuspensionStiffness",&suspensionStiffness,&wheelIndex)) - { - WHEEL_INDEX_CHECK_OR_RETURN(wheelIndex, "setSuspensionStiffness"); - - m_vehicle->SetSuspensionStiffness(suspensionStiffness,wheelIndex); - } - else { - return NULL; - } - Py_RETURN_NONE; -} - -PyObject *KX_VehicleWrapper::PySetSuspensionDamping(PyObject *args) -{ - float suspensionDamping; - int wheelIndex; - - if (PyArg_ParseTuple(args,"fi:setSuspensionDamping",&suspensionDamping,&wheelIndex)) - { - WHEEL_INDEX_CHECK_OR_RETURN(wheelIndex, "setSuspensionDamping"); - - m_vehicle->SetSuspensionDamping(suspensionDamping,wheelIndex); - } else { - return NULL; - } - Py_RETURN_NONE; -} - -PyObject *KX_VehicleWrapper::PySetSuspensionCompression(PyObject *args) -{ - float suspensionCompression; - int wheelIndex; - - if (PyArg_ParseTuple(args,"fi:setSuspensionCompression",&suspensionCompression,&wheelIndex)) - { - WHEEL_INDEX_CHECK_OR_RETURN(wheelIndex, "setSuspensionCompression"); - - m_vehicle->SetSuspensionCompression(suspensionCompression,wheelIndex); - } else { - return NULL; - } - Py_RETURN_NONE; -} - -PyObject *KX_VehicleWrapper::PySetRollInfluence(PyObject *args) -{ - float rollInfluence; - int wheelIndex; - - if (PyArg_ParseTuple(args,"fi:setRollInfluence",&rollInfluence,&wheelIndex)) - { - WHEEL_INDEX_CHECK_OR_RETURN(wheelIndex, "setRollInfluence"); - - m_vehicle->SetRollInfluence(rollInfluence,wheelIndex); - } - else { - return NULL; - } - Py_RETURN_NONE; -} - - -PyObject *KX_VehicleWrapper::PyApplyBraking(PyObject *args) -{ - float braking; - int wheelIndex; - - if (PyArg_ParseTuple(args,"fi:applyBraking",&braking,&wheelIndex)) - { - WHEEL_INDEX_CHECK_OR_RETURN(wheelIndex, "applyBraking"); - - m_vehicle->ApplyBraking(braking,wheelIndex); - } - else { - return NULL; - } - Py_RETURN_NONE; -} - - -PyObject *KX_VehicleWrapper::PySetSteeringValue(PyObject *args) -{ - float steeringValue; - int wheelIndex; - - if (PyArg_ParseTuple(args,"fi:setSteeringValue",&steeringValue,&wheelIndex)) - { - WHEEL_INDEX_CHECK_OR_RETURN(wheelIndex, "setSteeringValue"); - - m_vehicle->SetSteeringValue(steeringValue,wheelIndex); - } - else { - return NULL; - } - Py_RETURN_NONE; -} - - -PyObject *KX_VehicleWrapper::PyGetConstraintType(PyObject *args) -{ - return PyLong_FromLong(m_vehicle->GetUserConstraintType()); -} - - - - - -//python specific stuff -PyTypeObject KX_VehicleWrapper::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_VehicleWrapper", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &PyObjectPlus::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_VehicleWrapper::Methods[] = { - {"addWheel",(PyCFunction) KX_VehicleWrapper::sPyAddWheel, METH_VARARGS}, - {"getNumWheels",(PyCFunction) KX_VehicleWrapper::sPyGetNumWheels, METH_VARARGS}, - {"getWheelOrientationQuaternion",(PyCFunction) KX_VehicleWrapper::sPyGetWheelOrientationQuaternion, METH_VARARGS}, - {"getWheelRotation",(PyCFunction) KX_VehicleWrapper::sPyGetWheelRotation, METH_VARARGS}, - {"getWheelPosition",(PyCFunction) KX_VehicleWrapper::sPyGetWheelPosition, METH_VARARGS}, - {"getConstraintId",(PyCFunction) KX_VehicleWrapper::sPyGetConstraintId, METH_VARARGS}, - {"getConstraintType",(PyCFunction) KX_VehicleWrapper::sPyGetConstraintType, METH_VARARGS}, - {"setSteeringValue",(PyCFunction) KX_VehicleWrapper::sPySetSteeringValue, METH_VARARGS}, - {"applyEngineForce",(PyCFunction) KX_VehicleWrapper::sPyApplyEngineForce, METH_VARARGS}, - {"applyBraking",(PyCFunction) KX_VehicleWrapper::sPyApplyBraking, METH_VARARGS}, - {"setTyreFriction",(PyCFunction) KX_VehicleWrapper::sPySetTyreFriction, METH_VARARGS}, - {"setSuspensionStiffness",(PyCFunction) KX_VehicleWrapper::sPySetSuspensionStiffness, METH_VARARGS}, - {"setSuspensionDamping",(PyCFunction) KX_VehicleWrapper::sPySetSuspensionDamping, METH_VARARGS}, - {"setSuspensionCompression",(PyCFunction) KX_VehicleWrapper::sPySetSuspensionCompression, METH_VARARGS}, - {"setRollInfluence",(PyCFunction) KX_VehicleWrapper::sPySetRollInfluence, METH_VARARGS}, - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_VehicleWrapper::Attributes[] = { - { NULL } //Sentinel -}; - -#endif // WITH_PYTHON diff --git a/source/gameengine/Ketsji/KX_VehicleWrapper.h b/source/gameengine/Ketsji/KX_VehicleWrapper.h deleted file mode 100644 index 22b9591f48b..00000000000 --- a/source/gameengine/Ketsji/KX_VehicleWrapper.h +++ /dev/null @@ -1,61 +0,0 @@ - -/** \file KX_VehicleWrapper.h - * \ingroup ketsji - */ - -#ifndef __KX_VEHICLEWRAPPER_H__ -#define __KX_VEHICLEWRAPPER_H__ - -#include "EXP_Value.h" -class PHY_IVehicle; -class PHY_IMotionState; - -#include - -///Python interface to physics vehicles (primarily 4-wheel cars and 2wheel bikes) -class KX_VehicleWrapper : public PyObjectPlus -{ - Py_Header - - std::vector m_motionStates; - -public: - KX_VehicleWrapper(PHY_IVehicle* vehicle,class PHY_IPhysicsEnvironment* physenv); - virtual ~KX_VehicleWrapper (); - int getConstraintId(); - -#ifdef WITH_PYTHON - - KX_PYMETHOD_VARARGS(KX_VehicleWrapper,AddWheel); - KX_PYMETHOD_VARARGS(KX_VehicleWrapper,GetNumWheels); - KX_PYMETHOD_VARARGS(KX_VehicleWrapper,GetWheelOrientationQuaternion); - KX_PYMETHOD_VARARGS(KX_VehicleWrapper,GetWheelRotation); - - KX_PYMETHOD_VARARGS(KX_VehicleWrapper,GetWheelPosition); - - KX_PYMETHOD_VARARGS(KX_VehicleWrapper,GetConstraintId); - KX_PYMETHOD_VARARGS(KX_VehicleWrapper,GetConstraintType); - - KX_PYMETHOD_VARARGS(KX_VehicleWrapper,SetSteeringValue); - - KX_PYMETHOD_VARARGS(KX_VehicleWrapper,ApplyEngineForce); - - KX_PYMETHOD_VARARGS(KX_VehicleWrapper,ApplyBraking); - - KX_PYMETHOD_VARARGS(KX_VehicleWrapper,SetTyreFriction); - - KX_PYMETHOD_VARARGS(KX_VehicleWrapper,SetSuspensionStiffness); - - KX_PYMETHOD_VARARGS(KX_VehicleWrapper,SetSuspensionDamping); - - KX_PYMETHOD_VARARGS(KX_VehicleWrapper,SetSuspensionCompression); - - KX_PYMETHOD_VARARGS(KX_VehicleWrapper,SetRollInfluence); -#endif /* WITH_PYTHON */ - -private: - PHY_IVehicle* m_vehicle; - PHY_IPhysicsEnvironment* m_physenv; -}; - -#endif /* __KX_VEHICLEWRAPPER_H__ */ diff --git a/source/gameengine/Ketsji/KX_VertexProxy.cpp b/source/gameengine/Ketsji/KX_VertexProxy.cpp deleted file mode 100644 index 40f4c462801..00000000000 --- a/source/gameengine/Ketsji/KX_VertexProxy.cpp +++ /dev/null @@ -1,595 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_VertexProxy.cpp - * \ingroup ketsji - */ - - -#ifdef WITH_PYTHON - -#include "KX_VertexProxy.h" -#include "KX_MeshProxy.h" -#include "RAS_TexVert.h" - -#include "KX_PyMath.h" - -PyTypeObject KX_VertexProxy::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_VertexProxy", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &CValue::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_VertexProxy::Methods[] = { - {"getXYZ", (PyCFunction)KX_VertexProxy::sPyGetXYZ,METH_NOARGS}, - {"setXYZ", (PyCFunction)KX_VertexProxy::sPySetXYZ,METH_O}, - {"getUV", (PyCFunction)KX_VertexProxy::sPyGetUV1, METH_NOARGS}, - {"setUV", (PyCFunction)KX_VertexProxy::sPySetUV1, METH_O}, - - {"getUV2", (PyCFunction)KX_VertexProxy::sPyGetUV2,METH_NOARGS}, - {"setUV2", (PyCFunction)KX_VertexProxy::sPySetUV2,METH_VARARGS}, - - {"getRGBA", (PyCFunction)KX_VertexProxy::sPyGetRGBA,METH_NOARGS}, - {"setRGBA", (PyCFunction)KX_VertexProxy::sPySetRGBA,METH_O}, - {"getNormal", (PyCFunction)KX_VertexProxy::sPyGetNormal,METH_NOARGS}, - {"setNormal", (PyCFunction)KX_VertexProxy::sPySetNormal,METH_O}, - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_VertexProxy::Attributes[] = { - KX_PYATTRIBUTE_RW_FUNCTION("x", KX_VertexProxy, pyattr_get_x, pyattr_set_x), - KX_PYATTRIBUTE_RW_FUNCTION("y", KX_VertexProxy, pyattr_get_y, pyattr_set_y), - KX_PYATTRIBUTE_RW_FUNCTION("z", KX_VertexProxy, pyattr_get_z, pyattr_set_z), - - KX_PYATTRIBUTE_RW_FUNCTION("r", KX_VertexProxy, pyattr_get_r, pyattr_set_r), - KX_PYATTRIBUTE_RW_FUNCTION("g", KX_VertexProxy, pyattr_get_g, pyattr_set_g), - KX_PYATTRIBUTE_RW_FUNCTION("b", KX_VertexProxy, pyattr_get_b, pyattr_set_b), - KX_PYATTRIBUTE_RW_FUNCTION("a", KX_VertexProxy, pyattr_get_a, pyattr_set_a), - - KX_PYATTRIBUTE_RW_FUNCTION("u", KX_VertexProxy, pyattr_get_u, pyattr_set_u), - KX_PYATTRIBUTE_RW_FUNCTION("v", KX_VertexProxy, pyattr_get_v, pyattr_set_v), - - KX_PYATTRIBUTE_RW_FUNCTION("u2", KX_VertexProxy, pyattr_get_u2, pyattr_set_u2), - KX_PYATTRIBUTE_RW_FUNCTION("v2", KX_VertexProxy, pyattr_get_v2, pyattr_set_v2), - - KX_PYATTRIBUTE_RW_FUNCTION("XYZ", KX_VertexProxy, pyattr_get_XYZ, pyattr_set_XYZ), - KX_PYATTRIBUTE_RW_FUNCTION("UV", KX_VertexProxy, pyattr_get_UV, pyattr_set_UV), - KX_PYATTRIBUTE_RW_FUNCTION("uvs", KX_VertexProxy, pyattr_get_uvs, pyattr_set_uvs), - - KX_PYATTRIBUTE_RW_FUNCTION("color", KX_VertexProxy, pyattr_get_color, pyattr_set_color), - KX_PYATTRIBUTE_RW_FUNCTION("normal", KX_VertexProxy, pyattr_get_normal, pyattr_set_normal), - - { NULL } //Sentinel -}; - -PyObject *KX_VertexProxy::pyattr_get_x(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_VertexProxy* self = static_cast(self_v); - return PyFloat_FromDouble(self->m_vertex->getXYZ()[0]); -} - -PyObject *KX_VertexProxy::pyattr_get_y(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_VertexProxy* self = static_cast(self_v); - return PyFloat_FromDouble(self->m_vertex->getXYZ()[1]); -} - -PyObject *KX_VertexProxy::pyattr_get_z(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_VertexProxy* self = static_cast(self_v); - return PyFloat_FromDouble(self->m_vertex->getXYZ()[2]); -} - -PyObject *KX_VertexProxy::pyattr_get_r(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_VertexProxy* self = static_cast(self_v); - return PyFloat_FromDouble(self->m_vertex->getRGBA()[0]/255.0); -} - -PyObject *KX_VertexProxy::pyattr_get_g(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_VertexProxy* self = static_cast(self_v); - return PyFloat_FromDouble(self->m_vertex->getRGBA()[1]/255.0); -} - -PyObject *KX_VertexProxy::pyattr_get_b(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_VertexProxy* self = static_cast(self_v); - return PyFloat_FromDouble(self->m_vertex->getRGBA()[2]/255.0); -} - -PyObject *KX_VertexProxy::pyattr_get_a(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_VertexProxy* self = static_cast(self_v); - return PyFloat_FromDouble(self->m_vertex->getRGBA()[3]/255.0); -} - -PyObject *KX_VertexProxy::pyattr_get_u(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_VertexProxy* self = static_cast(self_v); - return PyFloat_FromDouble(self->m_vertex->getUV(0)[0]); -} - -PyObject *KX_VertexProxy::pyattr_get_v(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_VertexProxy* self = static_cast(self_v); - return PyFloat_FromDouble(self->m_vertex->getUV(0)[1]); -} - -PyObject *KX_VertexProxy::pyattr_get_u2(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_VertexProxy* self = static_cast(self_v); - return PyFloat_FromDouble(self->m_vertex->getUV(1)[0]); -} - -PyObject *KX_VertexProxy::pyattr_get_v2(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_VertexProxy* self = static_cast(self_v); - return PyFloat_FromDouble(self->m_vertex->getUV(1)[1]); -} - -PyObject *KX_VertexProxy::pyattr_get_XYZ(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_VertexProxy* self = static_cast(self_v); - return PyObjectFrom(MT_Vector3(self->m_vertex->getXYZ())); -} - -PyObject *KX_VertexProxy::pyattr_get_UV(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_VertexProxy* self = static_cast(self_v); - return PyObjectFrom(MT_Point2(self->m_vertex->getUV(0))); -} - -PyObject *KX_VertexProxy::pyattr_get_uvs(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_VertexProxy* self= static_cast(self_v); - - PyObject* uvlist = PyList_New(RAS_TexVert::MAX_UNIT); - for (int i=0; im_vertex->getUV(i)))); - } - - return uvlist; -} - -PyObject *KX_VertexProxy::pyattr_get_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_VertexProxy* self = static_cast(self_v); - const unsigned char *colp = self->m_vertex->getRGBA(); - MT_Vector4 color(colp[0], colp[1], colp[2], colp[3]); - color /= 255.0f; - return PyObjectFrom(color); -} - -PyObject *KX_VertexProxy::pyattr_get_normal(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_VertexProxy* self = static_cast(self_v); - return PyObjectFrom(MT_Vector3(self->m_vertex->getNormal())); -} - -int KX_VertexProxy::pyattr_set_x(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_VertexProxy* self = static_cast(self_v); - if (PyFloat_Check(value)) - { - float val = PyFloat_AsDouble(value); - MT_Point3 pos(self->m_vertex->getXYZ()); - pos.x() = val; - self->m_vertex->SetXYZ(pos); - self->m_mesh->SetMeshModified(true); - return PY_SET_ATTR_SUCCESS; - } - return PY_SET_ATTR_FAIL; -} - -int KX_VertexProxy::pyattr_set_y(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_VertexProxy* self = static_cast(self_v); - if (PyFloat_Check(value)) - { - float val = PyFloat_AsDouble(value); - MT_Point3 pos(self->m_vertex->getXYZ()); - pos.y() = val; - self->m_vertex->SetXYZ(pos); - self->m_mesh->SetMeshModified(true); - return PY_SET_ATTR_SUCCESS; - } - return PY_SET_ATTR_FAIL; -} - -int KX_VertexProxy::pyattr_set_z(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_VertexProxy* self = static_cast(self_v); - if (PyFloat_Check(value)) - { - float val = PyFloat_AsDouble(value); - MT_Point3 pos(self->m_vertex->getXYZ()); - pos.z() = val; - self->m_vertex->SetXYZ(pos); - self->m_mesh->SetMeshModified(true); - return PY_SET_ATTR_SUCCESS; - } - return PY_SET_ATTR_FAIL; -} - -int KX_VertexProxy::pyattr_set_u(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_VertexProxy* self = static_cast(self_v); - if (PyFloat_Check(value)) - { - float val = PyFloat_AsDouble(value); - MT_Point2 uv = self->m_vertex->getUV(0); - uv[0] = val; - self->m_vertex->SetUV(0, uv); - self->m_mesh->SetMeshModified(true); - return PY_SET_ATTR_SUCCESS; - } - return PY_SET_ATTR_FAIL; -} - -int KX_VertexProxy::pyattr_set_v(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_VertexProxy* self = static_cast(self_v); - if (PyFloat_Check(value)) - { - float val = PyFloat_AsDouble(value); - MT_Point2 uv = self->m_vertex->getUV(0); - uv[1] = val; - self->m_vertex->SetUV(0, uv); - self->m_mesh->SetMeshModified(true); - return PY_SET_ATTR_SUCCESS; - } - return PY_SET_ATTR_FAIL; -} - -int KX_VertexProxy::pyattr_set_u2(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_VertexProxy* self = static_cast(self_v); - if (PyFloat_Check(value)) - { - float val = PyFloat_AsDouble(value); - MT_Point2 uv = self->m_vertex->getUV(1); - uv[0] = val; - self->m_vertex->SetUV(1, uv); - self->m_mesh->SetMeshModified(true); - return PY_SET_ATTR_SUCCESS; - } - return PY_SET_ATTR_FAIL; -} - -int KX_VertexProxy::pyattr_set_v2(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_VertexProxy* self = static_cast(self_v); - if (PyFloat_Check(value)) - { - float val = PyFloat_AsDouble(value); - MT_Point2 uv = self->m_vertex->getUV(1); - uv[1] = val; - self->m_vertex->SetUV(1, uv); - self->m_mesh->SetMeshModified(true); - return PY_SET_ATTR_SUCCESS; - } - return PY_SET_ATTR_FAIL; -} - -int KX_VertexProxy::pyattr_set_r(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_VertexProxy* self = static_cast(self_v); - if (PyFloat_Check(value)) - { - float val = PyFloat_AsDouble(value); - unsigned int icol = *((const unsigned int *)self->m_vertex->getRGBA()); - unsigned char *cp = (unsigned char*) &icol; - val *= 255.0f; - cp[0] = (unsigned char) val; - self->m_vertex->SetRGBA(icol); - self->m_mesh->SetMeshModified(true); - return PY_SET_ATTR_SUCCESS; - } - return PY_SET_ATTR_FAIL; -} - -int KX_VertexProxy::pyattr_set_g(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_VertexProxy* self = static_cast(self_v); - if (PyFloat_Check(value)) - { - float val = PyFloat_AsDouble(value); - unsigned int icol = *((const unsigned int *)self->m_vertex->getRGBA()); - unsigned char *cp = (unsigned char*) &icol; - val *= 255.0f; - cp[1] = (unsigned char) val; - self->m_vertex->SetRGBA(icol); - self->m_mesh->SetMeshModified(true); - return PY_SET_ATTR_SUCCESS; - } - return PY_SET_ATTR_FAIL; -} - -int KX_VertexProxy::pyattr_set_b(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_VertexProxy* self = static_cast(self_v); - if (PyFloat_Check(value)) - { - float val = PyFloat_AsDouble(value); - unsigned int icol = *((const unsigned int *)self->m_vertex->getRGBA()); - unsigned char *cp = (unsigned char*) &icol; - val *= 255.0f; - cp[2] = (unsigned char) val; - self->m_vertex->SetRGBA(icol); - self->m_mesh->SetMeshModified(true); - return PY_SET_ATTR_SUCCESS; - } - return PY_SET_ATTR_FAIL; -} - -int KX_VertexProxy::pyattr_set_a(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_VertexProxy* self = static_cast(self_v); - if (PyFloat_Check(value)) - { - float val = PyFloat_AsDouble(value); - unsigned int icol = *((const unsigned int *)self->m_vertex->getRGBA()); - unsigned char *cp = (unsigned char*) &icol; - val *= 255.0f; - cp[3] = (unsigned char) val; - self->m_vertex->SetRGBA(icol); - self->m_mesh->SetMeshModified(true); - return PY_SET_ATTR_SUCCESS; - } - return PY_SET_ATTR_FAIL; -} - -int KX_VertexProxy::pyattr_set_XYZ(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_VertexProxy* self = static_cast(self_v); - if (PySequence_Check(value)) - { - MT_Point3 vec; - if (PyVecTo(value, vec)) - { - self->m_vertex->SetXYZ(vec); - self->m_mesh->SetMeshModified(true); - return PY_SET_ATTR_SUCCESS; - } - } - return PY_SET_ATTR_FAIL; -} - -int KX_VertexProxy::pyattr_set_UV(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_VertexProxy* self = static_cast(self_v); - if (PySequence_Check(value)) - { - MT_Point2 vec; - if (PyVecTo(value, vec)) { - self->m_vertex->SetUV(0, vec); - self->m_mesh->SetMeshModified(true); - return PY_SET_ATTR_SUCCESS; - } - } - return PY_SET_ATTR_FAIL; -} - -int KX_VertexProxy::pyattr_set_uvs(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_VertexProxy* self= static_cast(self_v); - if (PySequence_Check(value)) - { - MT_Point2 vec; - for (int i=0; im_vertex->SetUV(i, vec); - self->m_mesh->SetMeshModified(true); - } - else - { - PyErr_SetString(PyExc_AttributeError, STR_String().Format("list[%d] was not a vector", i).ReadPtr()); - return PY_SET_ATTR_FAIL; - } - } - - self->m_mesh->SetMeshModified(true); - return PY_SET_ATTR_SUCCESS; - } - return PY_SET_ATTR_FAIL; -} - -int KX_VertexProxy::pyattr_set_color(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_VertexProxy* self = static_cast(self_v); - if (PySequence_Check(value)) - { - MT_Vector4 vec; - if (PyVecTo(value, vec)) - { - self->m_vertex->SetRGBA(vec); - self->m_mesh->SetMeshModified(true); - return PY_SET_ATTR_SUCCESS; - } - } - return PY_SET_ATTR_FAIL; -} - -int KX_VertexProxy::pyattr_set_normal(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_VertexProxy* self = static_cast(self_v); - if (PySequence_Check(value)) - { - MT_Vector3 vec; - if (PyVecTo(value, vec)) - { - self->m_vertex->SetNormal(vec); - self->m_mesh->SetMeshModified(true); - return PY_SET_ATTR_SUCCESS; - } - } - return PY_SET_ATTR_FAIL; -} - -KX_VertexProxy::KX_VertexProxy(KX_MeshProxy*mesh, RAS_TexVert* vertex) -: m_vertex(vertex), - m_mesh(mesh) -{ - /* see bug [#27071] */ - Py_INCREF(m_mesh->GetProxy()); -} - -KX_VertexProxy::~KX_VertexProxy() -{ - /* see bug [#27071] */ - Py_DECREF(m_mesh->GetProxy()); -} - - - -// stuff for cvalue related things -CValue* KX_VertexProxy::Calc(VALUE_OPERATOR, CValue *) { return NULL;} -CValue* KX_VertexProxy::CalcFinal(VALUE_DATA_TYPE, VALUE_OPERATOR, CValue *) { return NULL;} -static STR_String sVertexName = "vertex"; -const STR_String & KX_VertexProxy::GetText() {return sVertexName;}; -double KX_VertexProxy::GetNumber() { return -1;} -STR_String& KX_VertexProxy::GetName() { return sVertexName;} -void KX_VertexProxy::SetName(const char *) { }; -CValue* KX_VertexProxy::GetReplica() { return NULL;} - -// stuff for python integration - -PyObject *KX_VertexProxy::PyGetXYZ() -{ - return PyObjectFrom(MT_Point3(m_vertex->getXYZ())); -} - -PyObject *KX_VertexProxy::PySetXYZ(PyObject *value) -{ - MT_Point3 vec; - if (!PyVecTo(value, vec)) - return NULL; - - m_vertex->SetXYZ(vec); - m_mesh->SetMeshModified(true); - Py_RETURN_NONE; -} - -PyObject *KX_VertexProxy::PyGetNormal() -{ - return PyObjectFrom(MT_Vector3(m_vertex->getNormal())); -} - -PyObject *KX_VertexProxy::PySetNormal(PyObject *value) -{ - MT_Vector3 vec; - if (!PyVecTo(value, vec)) - return NULL; - - m_vertex->SetNormal(vec); - m_mesh->SetMeshModified(true); - Py_RETURN_NONE; -} - - -PyObject *KX_VertexProxy::PyGetRGBA() -{ - int *rgba = (int *) m_vertex->getRGBA(); - return PyLong_FromLong(*rgba); -} - -PyObject *KX_VertexProxy::PySetRGBA(PyObject *value) -{ - if (PyLong_Check(value)) { - int rgba = PyLong_AsLong(value); - m_vertex->SetRGBA(rgba); - m_mesh->SetMeshModified(true); - Py_RETURN_NONE; - } - else { - MT_Vector4 vec; - if (PyVecTo(value, vec)) - { - m_vertex->SetRGBA(vec); - m_mesh->SetMeshModified(true); - Py_RETURN_NONE; - } - } - - PyErr_SetString(PyExc_TypeError, "vert.setRGBA(value): KX_VertexProxy, expected a 4D vector or an int"); - return NULL; -} - - -PyObject *KX_VertexProxy::PyGetUV1() -{ - return PyObjectFrom(MT_Vector2(m_vertex->getUV(0))); -} - -PyObject *KX_VertexProxy::PySetUV1(PyObject *value) -{ - MT_Point2 vec; - if (!PyVecTo(value, vec)) - return NULL; - - m_vertex->SetUV(0, vec); - m_mesh->SetMeshModified(true); - Py_RETURN_NONE; -} - -PyObject *KX_VertexProxy::PyGetUV2() -{ - return PyObjectFrom(MT_Vector2(m_vertex->getUV(1))); -} - -PyObject *KX_VertexProxy::PySetUV2(PyObject *args) -{ - MT_Point2 vec; - if (!PyVecTo(args, vec)) - return NULL; - - m_vertex->SetUV(1, vec); - m_mesh->SetMeshModified(true); - Py_RETURN_NONE; -} - -#endif // WITH_PYTHON diff --git a/source/gameengine/Ketsji/KX_VertexProxy.h b/source/gameengine/Ketsji/KX_VertexProxy.h deleted file mode 100644 index 8070825ad11..00000000000 --- a/source/gameengine/Ketsji/KX_VertexProxy.h +++ /dev/null @@ -1,112 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_VertexProxy.h - * \ingroup ketsji - */ - -#ifndef __KX_VERTEXPROXY_H__ -#define __KX_VERTEXPROXY_H__ - -#ifdef WITH_PYTHON - -#include "SCA_IObject.h" - -class KX_VertexProxy : public CValue -{ - Py_Header -protected: - - class RAS_TexVert* m_vertex; - class KX_MeshProxy* m_mesh; -public: - KX_VertexProxy(class KX_MeshProxy*mesh, class RAS_TexVert* vertex); - virtual ~KX_VertexProxy(); - - // stuff for cvalue related things - CValue* Calc(VALUE_OPERATOR op, CValue *val); - CValue* CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val); - const STR_String & GetText(); - double GetNumber(); - STR_String& GetName(); - void SetName(const char *name); // Set the name of the value - CValue* GetReplica(); - - -// stuff for python integration - - static PyObject *pyattr_get_x(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_y(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_z(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_r(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_g(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_b(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_a(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_u(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_v(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_u2(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_v2(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_XYZ(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_UV(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_normal(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_uvs(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_x(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static int pyattr_set_y(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static int pyattr_set_z(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static int pyattr_set_u(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static int pyattr_set_v(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static int pyattr_set_u2(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static int pyattr_set_v2(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static int pyattr_set_r(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static int pyattr_set_g(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static int pyattr_set_b(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static int pyattr_set_a(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static int pyattr_set_XYZ(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static int pyattr_set_UV(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static int pyattr_set_color(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static int pyattr_set_normal(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static int pyattr_set_uvs(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - - KX_PYMETHOD_NOARGS(KX_VertexProxy,GetXYZ); - KX_PYMETHOD_O(KX_VertexProxy,SetXYZ); - KX_PYMETHOD_NOARGS(KX_VertexProxy,GetUV1); - KX_PYMETHOD_O(KX_VertexProxy,SetUV1); - - KX_PYMETHOD_NOARGS(KX_VertexProxy,GetUV2); - KX_PYMETHOD_VARARGS(KX_VertexProxy,SetUV2); - - KX_PYMETHOD_NOARGS(KX_VertexProxy,GetRGBA); - KX_PYMETHOD_O(KX_VertexProxy,SetRGBA); - KX_PYMETHOD_NOARGS(KX_VertexProxy,GetNormal); - KX_PYMETHOD_O(KX_VertexProxy,SetNormal); - -}; - -#endif /* WITH_PYTHON */ - -#endif /* __KX_VERTEXPROXY_H__ */ diff --git a/source/gameengine/Ketsji/KX_VisibilityActuator.cpp b/source/gameengine/Ketsji/KX_VisibilityActuator.cpp deleted file mode 100644 index 6f689e228b9..00000000000 --- a/source/gameengine/Ketsji/KX_VisibilityActuator.cpp +++ /dev/null @@ -1,127 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - * Actuator to toggle visibility/invisibility of objects - */ - -/** \file gameengine/Ketsji/KX_VisibilityActuator.cpp - * \ingroup ketsji - */ - - -#include "KX_VisibilityActuator.h" -#include "KX_GameObject.h" - -KX_VisibilityActuator::KX_VisibilityActuator( - SCA_IObject* gameobj, - bool visible, - bool occlusion, - bool recursive - ) - : SCA_IActuator(gameobj, KX_ACT_VISIBILITY), - m_visible(visible), - m_occlusion(occlusion), - m_recursive(recursive) -{ - // intentionally empty -} - -KX_VisibilityActuator::~KX_VisibilityActuator( - void - ) -{ - // intentionally empty -} - -CValue* -KX_VisibilityActuator::GetReplica( - void - ) -{ - KX_VisibilityActuator* replica = new KX_VisibilityActuator(*this); - replica->ProcessReplica(); - return replica; -} - -bool -KX_VisibilityActuator::Update() -{ - bool bNegativeEvent = IsNegativeEvent(); - - RemoveAllEvents(); - if (bNegativeEvent) return false; - - KX_GameObject *obj = (KX_GameObject*) GetParent(); - - obj->SetVisible(m_visible, m_recursive); - obj->SetOccluder(m_occlusion, m_recursive); - obj->UpdateBuckets(m_recursive); - - return false; -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - - - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject KX_VisibilityActuator::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_VisibilityActuator", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &SCA_IActuator::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_VisibilityActuator::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef KX_VisibilityActuator::Attributes[] = { - KX_PYATTRIBUTE_BOOL_RW("visibility", KX_VisibilityActuator, m_visible), - KX_PYATTRIBUTE_BOOL_RW("useOcclusion", KX_VisibilityActuator, m_occlusion), - KX_PYATTRIBUTE_BOOL_RW("useRecursion", KX_VisibilityActuator, m_recursive), - { NULL } //Sentinel -}; - -#endif // WITH_PYTHON diff --git a/source/gameengine/Ketsji/KX_VisibilityActuator.h b/source/gameengine/Ketsji/KX_VisibilityActuator.h deleted file mode 100644 index a207844db74..00000000000 --- a/source/gameengine/Ketsji/KX_VisibilityActuator.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_VisibilityActuator.h - * \ingroup ketsji - * \brief Actuator to toggle visibility/invisibility of objects - */ - -#ifndef __KX_VISIBILITYACTUATOR_H__ -#define __KX_VISIBILITYACTUATOR_H__ - -#include "SCA_IActuator.h" - -class KX_VisibilityActuator : public SCA_IActuator -{ - Py_Header - - /** Make visible? */ - bool m_visible; - bool m_occlusion; - bool m_recursive; - - public: - - KX_VisibilityActuator( - SCA_IObject* gameobj, - bool visible, - bool occlusion, - bool recursive); - - virtual - ~KX_VisibilityActuator( - void - ); - - virtual CValue* - GetReplica( - void - ); - - virtual bool - Update(); - - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - -}; - -#endif - diff --git a/source/gameengine/Ketsji/KX_WorldInfo.cpp b/source/gameengine/Ketsji/KX_WorldInfo.cpp deleted file mode 100644 index be8b1ce92fc..00000000000 --- a/source/gameengine/Ketsji/KX_WorldInfo.cpp +++ /dev/null @@ -1,494 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_WorldInfo.cpp - * \ingroup ketsji - */ - - -#include "KX_WorldInfo.h" -#include "KX_PythonInit.h" -#include "KX_PyMath.h" -#include "RAS_IRasterizer.h" -#include "GPU_material.h" - -/* This little block needed for linking to Blender... */ -#ifdef WIN32 -#include "BLI_winstuff.h" -#endif - -/* This list includes only data type definitions */ -#include "DNA_scene_types.h" -#include "DNA_world_types.h" - -#include "BLI_math.h" - -#include "BKE_global.h" -#include "BKE_scene.h" -/* end of blender include block */ - - -KX_WorldInfo::KX_WorldInfo(Scene *blenderscene, World *blenderworld) -{ - if (blenderworld) { - m_name = blenderworld->id.name + 2; - m_do_color_management = BKE_scene_check_color_management_enabled(blenderscene); - m_hasworld = true; - m_hasmist = ((blenderworld->mode) & WO_MIST ? true : false); - m_misttype = blenderworld->mistype; - m_miststart = blenderworld->miststa; - m_mistdistance = blenderworld->mistdist; - m_mistintensity = blenderworld->misi; - setMistColor(blenderworld->horr, blenderworld->horg, blenderworld->horb); - setBackColor(blenderworld->horr, blenderworld->horg, blenderworld->horb); - setAmbientColor(blenderworld->ambr, blenderworld->ambg, blenderworld->ambb); - } - else { - m_hasworld = false; - } -} - -KX_WorldInfo::~KX_WorldInfo() -{ -} - -const STR_String& KX_WorldInfo::GetName() -{ - return m_name; -} - -bool KX_WorldInfo::hasWorld() -{ - return m_hasworld; -} - -void KX_WorldInfo::setBackColor(float r, float g, float b) -{ - m_backgroundcolor[0] = r; - m_backgroundcolor[1] = g; - m_backgroundcolor[2] = b; - - if (m_do_color_management) { - linearrgb_to_srgb_v3_v3(m_con_backgroundcolor, m_backgroundcolor); - } - else { - copy_v3_v3(m_con_backgroundcolor, m_backgroundcolor); - } -} - -const float *KX_WorldInfo::getBackColorConverted() const -{ - return m_con_backgroundcolor; -} - -void KX_WorldInfo::setMistType(short type) -{ - m_misttype = type; -} - -void KX_WorldInfo::setUseMist(bool enable) -{ - m_hasmist = enable; -} - -void KX_WorldInfo::setMistStart(float d) -{ - m_miststart = d; -} - -void KX_WorldInfo::setMistDistance(float d) -{ - m_mistdistance = d; -} - -void KX_WorldInfo::setMistIntensity(float intensity) -{ - m_mistintensity = intensity; -} -void KX_WorldInfo::setMistColor(float r, float g, float b) -{ - m_mistcolor[0] = r; - m_mistcolor[1] = g; - m_mistcolor[2] = b; - - if (m_do_color_management) { - linearrgb_to_srgb_v3_v3(m_con_mistcolor, m_mistcolor); - } - else { - copy_v3_v3(m_con_mistcolor, m_mistcolor); - } -} - -void KX_WorldInfo::setAmbientColor(float r, float g, float b) -{ - m_ambientcolor[0] = r; - m_ambientcolor[1] = g; - m_ambientcolor[2] = b; - - if (m_do_color_management) { - linearrgb_to_srgb_v3_v3(m_con_ambientcolor, m_ambientcolor); - } - else { - copy_v3_v3(m_con_ambientcolor, m_ambientcolor); - } -} - -void KX_WorldInfo::UpdateBackGround() -{ - if (m_hasworld) { - RAS_IRasterizer *m_rasterizer = KX_GetActiveEngine()->GetRasterizer(); - - if (m_rasterizer->GetDrawingMode() >= RAS_IRasterizer::KX_SOLID) { - m_rasterizer->SetBackColor(m_con_backgroundcolor); - GPU_horizon_update_color(m_backgroundcolor); - } - } -} - -void KX_WorldInfo::UpdateWorldSettings() -{ - if (m_hasworld) { - RAS_IRasterizer *m_rasterizer = KX_GetActiveEngine()->GetRasterizer(); - - if (m_rasterizer->GetDrawingMode() >= RAS_IRasterizer::KX_SOLID) { - m_rasterizer->SetAmbientColor(m_con_ambientcolor); - GPU_ambient_update_color(m_ambientcolor); - - if (m_hasmist) { - m_rasterizer->SetFog(m_misttype, m_miststart, m_mistdistance, m_mistintensity, m_con_mistcolor); - GPU_mist_update_values(m_misttype, m_miststart, m_mistdistance, m_mistintensity, m_mistcolor); - m_rasterizer->EnableFog(true); - GPU_mist_update_enable(true); - } - else { - m_rasterizer->EnableFog(false); - GPU_mist_update_enable(false); - } - } - } -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- - * Python functions - * ------------------------------------------------------------------------- */ -PyObject *KX_WorldInfo::py_repr(void) -{ - return PyUnicode_From_STR_String(GetName()); -} - -/* ------------------------------------------------------------------------- - * Python Integration Hooks - * ------------------------------------------------------------------------- */ -PyTypeObject KX_WorldInfo::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_WorldInfo", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0,0,0,0,0,0,0,0,0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - 0,0,0,0,0,0,0, - Methods, - 0, - 0, - &PyObjectPlus::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef KX_WorldInfo::Methods[] = { - {NULL,NULL} /* Sentinel */ -}; - -PyAttributeDef KX_WorldInfo::Attributes[] = { - KX_PYATTRIBUTE_BOOL_RW("mistEnable", KX_WorldInfo, m_hasmist), - KX_PYATTRIBUTE_FLOAT_RW("mistStart", 0.0f, 10000.0f, KX_WorldInfo, m_miststart), - KX_PYATTRIBUTE_FLOAT_RW("mistDistance", 0.001f, 10000.0f, KX_WorldInfo, m_mistdistance), - KX_PYATTRIBUTE_FLOAT_RW("mistIntensity", 0.0f, 1.0f, KX_WorldInfo, m_mistintensity), - KX_PYATTRIBUTE_SHORT_RW("mistType", 0, 2, true, KX_WorldInfo, m_misttype), - KX_PYATTRIBUTE_RO_FUNCTION("KX_MIST_QUADRATIC", KX_WorldInfo, pyattr_get_mist_typeconst), - KX_PYATTRIBUTE_RO_FUNCTION("KX_MIST_LINEAR", KX_WorldInfo, pyattr_get_mist_typeconst), - KX_PYATTRIBUTE_RO_FUNCTION("KX_MIST_INV_QUADRATIC", KX_WorldInfo, pyattr_get_mist_typeconst), - KX_PYATTRIBUTE_RW_FUNCTION("mistColor", KX_WorldInfo, pyattr_get_mist_color, pyattr_set_mist_color), - KX_PYATTRIBUTE_RW_FUNCTION("backgroundColor", KX_WorldInfo, pyattr_get_back_color, pyattr_set_back_color), - KX_PYATTRIBUTE_RW_FUNCTION("ambientColor", KX_WorldInfo, pyattr_get_ambient_color, pyattr_set_ambient_color), - { NULL } /* Sentinel */ -}; - -/* Attribute get/set functions */ - -#ifdef USE_MATHUTILS - -/*----------------------mathutils callbacks ----------------------------*/ - -/* subtype */ -#define MATHUTILS_COL_CB_MIST_COLOR 1 -#define MATHUTILS_COL_CB_BACK_COLOR 2 -#define MATHUTILS_COL_CB_AMBIENT_COLOR 3 - -static unsigned char mathutils_world_color_cb_index = -1; /* index for our callbacks */ - -static int mathutils_world_generic_check(BaseMathObject *bmo) -{ - KX_WorldInfo *self = static_castBGE_PROXY_REF(bmo->cb_user); - if (self == NULL) - return -1; - - return 0; -} - -static int mathutils_world_color_get(BaseMathObject *bmo, int subtype) -{ - KX_WorldInfo *self = static_castBGE_PROXY_REF(bmo->cb_user); - if (self == NULL) - return -1; - - switch (subtype) { - case MATHUTILS_COL_CB_MIST_COLOR: - copy_v3_v3(bmo->data, self->m_mistcolor); - break; - case MATHUTILS_COL_CB_BACK_COLOR: - copy_v3_v3(bmo->data, self->m_backgroundcolor); - break; - case MATHUTILS_COL_CB_AMBIENT_COLOR: - copy_v3_v3(bmo->data, self->m_ambientcolor); - break; - default: - return -1; - } - return 0; -} - -static int mathutils_world_color_set(BaseMathObject *bmo, int subtype) -{ - KX_WorldInfo *self = static_castBGE_PROXY_REF(bmo->cb_user); - - if (self == NULL) - return -1; - - switch (subtype) { - case MATHUTILS_COL_CB_MIST_COLOR: - self->setMistColor(bmo->data[0], bmo->data[1], bmo->data[2]); - break; - case MATHUTILS_COL_CB_BACK_COLOR: - self->setBackColor(bmo->data[0], bmo->data[1], bmo->data[2]); - break; - case MATHUTILS_COL_CB_AMBIENT_COLOR: - self->setAmbientColor(bmo->data[0], bmo->data[1], bmo->data[2]); - break; - default: - return -1; - } - return 0; -} - -static int mathutils_world_color_get_index(BaseMathObject *bmo, int subtype, int index) -{ - KX_WorldInfo *self = static_castBGE_PROXY_REF(bmo->cb_user); - - if (self == NULL) - return -1; - - switch (subtype) { - case MATHUTILS_COL_CB_MIST_COLOR: - { - const float *color = self->m_mistcolor; - bmo->data[index] = color[index]; - } - break; - case MATHUTILS_COL_CB_BACK_COLOR: - { - const float *color = self->m_backgroundcolor; - bmo->data[index] = color[index]; - } - break; - case MATHUTILS_COL_CB_AMBIENT_COLOR: - { - const float *color = self->m_ambientcolor; - bmo->data[index] = color[index]; - } - break; - default: - return -1; - } - return 0; -} - -static int mathutils_world_color_set_index(BaseMathObject *bmo, int subtype, int index) -{ - KX_WorldInfo *self = static_castBGE_PROXY_REF(bmo->cb_user); - - if (self == NULL) - return -1; - - float color[4]; - switch (subtype) { - case MATHUTILS_COL_CB_MIST_COLOR: - copy_v3_v3(color, self->m_mistcolor); - color[index] = bmo->data[index]; - self->setMistColor(color[0], color[1], color[2]); - break; - case MATHUTILS_COL_CB_BACK_COLOR: - copy_v3_v3(color, self->m_backgroundcolor); - color[index] = bmo->data[index]; - self->setBackColor(color[0], color[1], color[2]); - break; - case MATHUTILS_COL_CB_AMBIENT_COLOR: - copy_v3_v3(color, self->m_ambientcolor); - color[index] = bmo->data[index]; - self->setAmbientColor(color[0], color[1], color[2]); - break; - default: - return -1; - } - return 0; -} - -static Mathutils_Callback mathutils_world_color_cb = { - mathutils_world_generic_check, - mathutils_world_color_get, - mathutils_world_color_set, - mathutils_world_color_get_index, - mathutils_world_color_set_index -}; - -void KX_WorldInfo_Mathutils_Callback_Init() -{ - // register mathutils callbacks, ok to run more than once. - mathutils_world_color_cb_index = Mathutils_RegisterCallback(&mathutils_world_color_cb); -} -#endif // USE_MATHUTILS - - -PyObject *KX_WorldInfo::pyattr_get_mist_typeconst(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - PyObject *retvalue; - - const char* type = attrdef->m_name; - - if (!strcmp(type, "KX_MIST_QUADRATIC")) { - retvalue = PyLong_FromLong(KX_MIST_QUADRATIC); - } - else if (!strcmp(type, "KX_MIST_LINEAR")) { - retvalue = PyLong_FromLong(KX_MIST_LINEAR); - } - else if (!strcmp(type, "KX_MIST_INV_QUADRATIC")) { - retvalue = PyLong_FromLong(KX_MIST_INV_QUADRATIC); - } - else { - /* should never happen */ - PyErr_SetString(PyExc_TypeError, "invalid mist type"); - retvalue = NULL; - } - - return retvalue; -} - -PyObject *KX_WorldInfo::pyattr_get_mist_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ -#ifdef USE_MATHUTILS - return Color_CreatePyObject_cb( - BGE_PROXY_FROM_REF_BORROW(self_v), - mathutils_world_color_cb_index, MATHUTILS_COL_CB_MIST_COLOR); -#else - KX_WorldInfo *self = static_cast(self_v); - return PyObjectFrom(MT_Vector3(self->m_mistcolor)); -#endif -} - -int KX_WorldInfo::pyattr_set_mist_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_WorldInfo *self = static_cast(self_v); - - MT_Vector3 color; - if (PyVecTo(value, color)) - { - self->setMistColor(color[0], color[1], color[2]); - return PY_SET_ATTR_SUCCESS; - } - return PY_SET_ATTR_FAIL; -} - -PyObject *KX_WorldInfo::pyattr_get_back_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - -#ifdef USE_MATHUTILS - return Color_CreatePyObject_cb( - BGE_PROXY_FROM_REF_BORROW(self_v), - mathutils_world_color_cb_index, MATHUTILS_COL_CB_BACK_COLOR); -#else - KX_WorldInfo *self = static_cast(self_v); - return PyObjectFrom(MT_Vector3(self->m_backgroundcolor)); -#endif -} - -int KX_WorldInfo::pyattr_set_back_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_WorldInfo *self = static_cast(self_v); - - MT_Vector3 color; - if (PyVecTo(value, color)) - { - self->setBackColor(color[0], color[1], color[2]); - return PY_SET_ATTR_SUCCESS; - } - return PY_SET_ATTR_FAIL; -} - -PyObject *KX_WorldInfo::pyattr_get_ambient_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ -#ifdef USE_MATHUTILS - return Color_CreatePyObject_cb( - BGE_PROXY_FROM_REF_BORROW(self_v), - mathutils_world_color_cb_index, MATHUTILS_COL_CB_AMBIENT_COLOR); -#else - KX_WorldInfo *self = static_cast(self_v); - return PyObjectFrom(MT_Vector3(self->m_ambientcolor)); -#endif -} - -int KX_WorldInfo::pyattr_set_ambient_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_WorldInfo *self = static_cast(self_v); - - MT_Vector3 color; - if (PyVecTo(value, color)) - { - self->setAmbientColor(color[0], color[1], color[2]); - return PY_SET_ATTR_SUCCESS; - } - return PY_SET_ATTR_FAIL; -} - -#endif /* WITH_PYTHON */ diff --git a/source/gameengine/Ketsji/KX_WorldInfo.h b/source/gameengine/Ketsji/KX_WorldInfo.h deleted file mode 100644 index b155faf2837..00000000000 --- a/source/gameengine/Ketsji/KX_WorldInfo.h +++ /dev/null @@ -1,105 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_WorldInfo.h - * \ingroup ketsji - */ - -#ifndef __KX_WORLDINFO_H__ -#define __KX_WORLDINFO_H__ - -#include "MT_Scalar.h" -#include "KX_KetsjiEngine.h" -#include "EXP_PyObjectPlus.h" - -#ifdef USE_MATHUTILS -void KX_WorldInfo_Mathutils_Callback_Init(void); -#endif - -struct Scene; -struct World; - -class KX_WorldInfo : public PyObjectPlus -{ - Py_Header - - STR_String m_name; - bool m_do_color_management; - bool m_hasworld; - bool m_hasmist; - short m_misttype; - float m_miststart; - float m_mistdistance; - float m_mistintensity; - float m_mistcolor[3]; - float m_backgroundcolor[3]; - float m_ambientcolor[3]; - float m_con_mistcolor[3]; - float m_con_backgroundcolor[3]; - float m_con_ambientcolor[3]; - -public: - /** - * Mist options - */ - enum MistType { - KX_MIST_QUADRATIC, - KX_MIST_LINEAR, - KX_MIST_INV_QUADRATIC, - }; - - KX_WorldInfo(Scene *blenderscene, World *blenderworld); - ~KX_WorldInfo(); - - const STR_String &GetName(); - bool hasWorld(); - void setUseMist(bool enable); - void setMistType(short type); - void setMistStart(float d); - void setMistDistance(float d); - void setMistIntensity(float intensity); - void setMistColor(float r, float g, float b); - void setBackColor(float r, float g, float b); - const float *getBackColorConverted() const; - void setAmbientColor(float r, float g, float b); - void UpdateBackGround(); - void UpdateWorldSettings(); - -#ifdef WITH_PYTHON - /* attributes */ - static PyObject *pyattr_get_mist_typeconst(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_mist_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_mist_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject *pyattr_get_back_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_back_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject *pyattr_get_ambient_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_ambient_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - virtual PyObject *py_repr(void); -#endif -}; - -#endif /* __KX_WORLDINFO_H__ */ diff --git a/source/gameengine/Ketsji/KX_WorldIpoController.cpp b/source/gameengine/Ketsji/KX_WorldIpoController.cpp deleted file mode 100644 index 1123e07ebcc..00000000000 --- a/source/gameengine/Ketsji/KX_WorldIpoController.cpp +++ /dev/null @@ -1,125 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Ketsji/KX_WorldIpoController.cpp - * \ingroup ketsji - */ - - -#include "KX_WorldIpoController.h" -#include "KX_ScalarInterpolator.h" -#include "KX_WorldInfo.h" -#include "KX_PythonInit.h" -#include "KX_Scene.h" - -#if defined(_WIN64) -typedef unsigned __int64 uint_ptr; -#else -typedef unsigned long uint_ptr; -#endif - -bool KX_WorldIpoController::Update(double currentTime) -{ - if (m_modified) { - T_InterpolatorList::iterator i; - for (i = m_interpolators.begin(); !(i == m_interpolators.end()); ++i) { - (*i)->Execute(m_ipotime); - } - - KX_WorldInfo *world = KX_GetActiveScene()->GetWorldInfo(); - - if (m_modify_mist_start) { - world->setMistStart(m_mist_start); - } - - if (m_modify_mist_dist) { - world->setMistDistance(m_mist_dist); - } - - if (m_modify_mist_intensity) { - world->setMistIntensity(m_mist_intensity); - } - - if (m_modify_horizon_color) { - world->setBackColor(m_hori_rgb[0], m_hori_rgb[1], m_hori_rgb[2]); - world->setMistColor(m_hori_rgb[0], m_hori_rgb[1], m_hori_rgb[2]); - } - - if (m_modify_ambient_color) { - world->setAmbientColor(m_ambi_rgb[0], m_ambi_rgb[1], m_ambi_rgb[2]); - } - - m_modified = false; - } - return false; -} - - -void KX_WorldIpoController::AddInterpolator(KX_IInterpolator* interp) -{ - this->m_interpolators.push_back(interp); -} - - -SG_Controller* KX_WorldIpoController::GetReplica(class SG_Node* destnode) -{ - KX_WorldIpoController* iporeplica = new KX_WorldIpoController(*this); - // clear object that ipo acts on - iporeplica->ClearObject(); - - // dirty hack, ask Gino for a better solution in the ipo implementation - // hacken en zagen, in what we call datahiding, not written for replication :( - - T_InterpolatorList oldlist = m_interpolators; - iporeplica->m_interpolators.clear(); - - T_InterpolatorList::iterator i; - for (i = oldlist.begin(); !(i == oldlist.end()); ++i) { - KX_ScalarInterpolator* copyipo = new KX_ScalarInterpolator(*((KX_ScalarInterpolator*)*i)); - iporeplica->AddInterpolator(copyipo); - - MT_Scalar* scaal = ((KX_ScalarInterpolator*)*i)->GetTarget(); - uint_ptr orgbase = (uint_ptr)this; - uint_ptr orgloc = (uint_ptr)scaal; - uint_ptr offset = orgloc-orgbase; - uint_ptr newaddrbase = (uint_ptr)iporeplica + offset; - MT_Scalar* blaptr = (MT_Scalar*) newaddrbase; - copyipo->SetNewTarget((MT_Scalar*)blaptr); - } - - return iporeplica; -} - -KX_WorldIpoController::~KX_WorldIpoController() -{ - - T_InterpolatorList::iterator i; - for (i = m_interpolators.begin(); !(i == m_interpolators.end()); ++i) { - delete (*i); - } - -} diff --git a/source/gameengine/Ketsji/KX_WorldIpoController.h b/source/gameengine/Ketsji/KX_WorldIpoController.h deleted file mode 100644 index 704f421573e..00000000000 --- a/source/gameengine/Ketsji/KX_WorldIpoController.h +++ /dev/null @@ -1,117 +0,0 @@ -/* - * ***** BEGIN GPL LICENSE BLOCK ***** - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_WorldIpoController.h - * \ingroup ketsji - */ - -#ifndef __KX_WORLDIPOCONTROLLER_H__ -#define __KX_WORLDIPOCONTROLLER_H__ - -#include "SG_Controller.h" -#include "SG_Spatial.h" -#include "KX_IInterpolator.h" - -class KX_WorldIpoController : public SG_Controller -{ -public: - MT_Scalar m_mist_start; - MT_Scalar m_mist_dist; - MT_Scalar m_mist_intensity; - MT_Scalar m_hori_rgb[3]; - MT_Scalar m_ambi_rgb[3]; - -private: - T_InterpolatorList m_interpolators; - unsigned short m_modify_mist_start : 1; - unsigned short m_modify_mist_dist : 1; - unsigned short m_modify_mist_intensity : 1; - unsigned short m_modify_horizon_color : 1; - unsigned short m_modify_ambient_color : 1; - bool m_modified; - - double m_ipotime; - -public: - KX_WorldIpoController() : - m_modify_mist_start(false), - m_modify_mist_dist(false), - m_modify_mist_intensity(false), - m_modify_horizon_color(false), - m_modify_ambient_color(false), - m_modified(true), - m_ipotime(0.0) - {} - - virtual ~KX_WorldIpoController(); - - virtual SG_Controller* GetReplica(class SG_Node* destnode); - - virtual bool Update(double time); - - virtual void SetSimulatedTime(double time) { - m_ipotime = time; - m_modified = true; - } - - void SetModifyMistStart(bool modify) { - m_modify_mist_start = modify; - } - - void SetModifyMistDist(bool modify) { - m_modify_mist_dist = modify; - } - - void SetModifyMistIntensity(bool modify) { - m_modify_mist_intensity = modify; - } - - void SetModifyHorizonColor(bool modify) { - m_modify_horizon_color = modify; - } - - void SetModifyAmbientColor(bool modify) { - m_modify_ambient_color = modify; - } - - void - SetOption( - int option, - int value - ) { - // intentionally empty - }; - - void AddInterpolator(KX_IInterpolator* interp); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_WorldIpoController") -#endif -}; - -#endif /* __KX_WORLDIPOCONTROLLER_H__ */ -- cgit v1.2.3