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/CMakeLists.txt | 4 - source/blender/CMakeLists.txt | 4 - source/blender/blenkernel/BKE_DerivedMesh.h | 7 - source/blender/blenkernel/BKE_action.h | 3 - source/blender/blenkernel/BKE_blender_version.h | 2 +- source/blender/blenkernel/BKE_bullet.h | 44 - source/blender/blenkernel/BKE_context.h | 1 - source/blender/blenkernel/BKE_global.h | 11 - source/blender/blenkernel/BKE_navmesh_conversion.h | 67 - source/blender/blenkernel/BKE_object.h | 11 - source/blender/blenkernel/BKE_property.h | 53 - source/blender/blenkernel/BKE_sca.h | 92 - source/blender/blenkernel/BKE_scene.h | 2 - source/blender/blenkernel/CMakeLists.txt | 18 - source/blender/blenkernel/intern/DerivedMesh.c | 237 +- source/blender/blenkernel/intern/action.c | 52 - source/blender/blenkernel/intern/blendfile.c | 2 +- source/blender/blenkernel/intern/bullet.c | 99 - source/blender/blenkernel/intern/constraint.c | 62 +- source/blender/blenkernel/intern/context.c | 8 - source/blender/blenkernel/intern/ipo.c | 18 - source/blender/blenkernel/intern/library_query.c | 39 +- source/blender/blenkernel/intern/library_remap.c | 5 - source/blender/blenkernel/intern/material.c | 8 +- .../blender/blenkernel/intern/navmesh_conversion.c | 502 --- source/blender/blenkernel/intern/object.c | 190 +- source/blender/blenkernel/intern/property.c | 267 -- source/blender/blenkernel/intern/rigidbody.c | 4 +- source/blender/blenkernel/intern/sca.c | 1179 ------ source/blender/blenkernel/intern/scene.c | 66 - source/blender/blenkernel/intern/text.c | 2 - source/blender/blenlib/BLI_callbacks.h | 2 - source/blender/blenloader/intern/readfile.c | 294 +- source/blender/blenloader/intern/versioning_250.c | 256 +- source/blender/blenloader/intern/versioning_260.c | 162 - source/blender/blenloader/intern/versioning_270.c | 47 - source/blender/blenloader/intern/versioning_280.c | 33 +- .../blenloader/intern/versioning_defaults.c | 3 - .../blender/blenloader/intern/versioning_legacy.c | 465 --- source/blender/blenloader/intern/writefile.c | 186 - source/blender/editors/CMakeLists.txt | 1 - source/blender/editors/include/ED_screen.h | 1 - source/blender/editors/include/UI_interface.h | 14 - source/blender/editors/interface/interface.c | 254 -- .../blender/editors/interface/interface_handlers.c | 269 +- .../blender/editors/interface/interface_intern.h | 5 - .../editors/interface/interface_templates.c | 75 +- .../blender/editors/interface/interface_widgets.c | 57 +- source/blender/editors/interface/resources.c | 17 - source/blender/editors/mesh/CMakeLists.txt | 12 - source/blender/editors/mesh/mesh_intern.h | 8 - source/blender/editors/mesh/mesh_navmesh.c | 736 ---- source/blender/editors/mesh/mesh_ops.c | 8 - source/blender/editors/object/CMakeLists.txt | 5 - source/blender/editors/object/object_add.c | 37 - source/blender/editors/object/object_constraint.c | 9 - source/blender/editors/object/object_edit.c | 521 +-- source/blender/editors/object/object_intern.h | 8 - source/blender/editors/object/object_lod.c | 114 - source/blender/editors/object/object_ops.c | 14 - source/blender/editors/object/object_relations.c | 5 - source/blender/editors/object/object_select.c | 38 +- source/blender/editors/screen/screen_ops.c | 5 - .../editors/sculpt_paint/paint_image_proj.c | 4 +- source/blender/editors/sculpt_paint/paint_utils.c | 10 +- source/blender/editors/space_api/spacetypes.c | 2 - source/blender/editors/space_logic/CMakeLists.txt | 58 - source/blender/editors/space_logic/logic_buttons.c | 166 - source/blender/editors/space_logic/logic_intern.h | 55 - source/blender/editors/space_logic/logic_ops.c | 753 ---- source/blender/editors/space_logic/logic_window.c | 2594 ------------ source/blender/editors/space_logic/space_logic.c | 377 -- source/blender/editors/space_view3d/CMakeLists.txt | 7 - source/blender/editors/space_view3d/drawmesh.c | 2 - source/blender/editors/space_view3d/drawobject.c | 191 +- .../editors/space_view3d/view3d_draw_legacy.c | 33 +- .../blender/editors/space_view3d/view3d_intern.h | 2 - source/blender/editors/space_view3d/view3d_ops.c | 1 - source/blender/editors/space_view3d/view3d_view.c | 219 - source/blender/gpu/CMakeLists.txt | 4 - source/blender/gpu/GPU_draw.h | 15 +- source/blender/gpu/intern/gpu_draw.c | 157 +- source/blender/gpu/intern/gpu_lamp.c | 6 +- source/blender/gpu/intern/gpu_material.c | 51 +- source/blender/ikplugin/intern/itasc_plugin.cpp | 39 +- source/blender/imbuf/intern/indexer.c | 2 +- source/blender/makesdna/DNA_action_types.h | 3 +- source/blender/makesdna/DNA_actuator_types.h | 583 --- source/blender/makesdna/DNA_constraint_types.h | 6 +- source/blender/makesdna/DNA_controller_types.h | 95 - source/blender/makesdna/DNA_material_types.h | 36 - source/blender/makesdna/DNA_object_force_types.h | 53 - source/blender/makesdna/DNA_object_types.h | 132 +- source/blender/makesdna/DNA_property_types.h | 65 - source/blender/makesdna/DNA_scene_types.h | 188 - source/blender/makesdna/DNA_sensor_types.h | 334 -- source/blender/makesdna/DNA_space_types.h | 23 +- source/blender/makesdna/DNA_userdef_types.h | 14 +- source/blender/makesdna/DNA_view3d_types.h | 2 +- source/blender/makesdna/DNA_world_types.h | 29 +- source/blender/makesdna/intern/makesdna.c | 8 - source/blender/makesrna/RNA_access.h | 10 - source/blender/makesrna/RNA_enum_types.h | 2 - source/blender/makesrna/intern/CMakeLists.txt | 11 - source/blender/makesrna/intern/makesrna.c | 4 - source/blender/makesrna/intern/rna_actuator.c | 2220 ----------- source/blender/makesrna/intern/rna_actuator_api.c | 77 - source/blender/makesrna/intern/rna_armature.c | 12 - source/blender/makesrna/intern/rna_constraint.c | 179 +- source/blender/makesrna/intern/rna_controller.c | 327 -- .../blender/makesrna/intern/rna_controller_api.c | 86 - source/blender/makesrna/intern/rna_internal.h | 1 - source/blender/makesrna/intern/rna_layer.c | 17 - source/blender/makesrna/intern/rna_material.c | 125 - source/blender/makesrna/intern/rna_object.c | 649 --- source/blender/makesrna/intern/rna_object_force.c | 73 - source/blender/makesrna/intern/rna_property.c | 203 - source/blender/makesrna/intern/rna_scene.c | 634 --- source/blender/makesrna/intern/rna_sensor.c | 939 ----- source/blender/makesrna/intern/rna_sensor_api.c | 79 - source/blender/makesrna/intern/rna_sound.c | 1 - source/blender/makesrna/intern/rna_space.c | 73 - source/blender/makesrna/intern/rna_userdef.c | 38 - source/blender/nodes/shader/node_shader_tree.c | 1 - .../blender/python/generic/bpy_internal_import.c | 10 - .../blender/python/generic/bpy_internal_import.h | 5 - source/blender/python/generic/py_capi_utils.h | 2 +- source/blender/python/intern/CMakeLists.txt | 8 - .../blender/python/intern/bpy_app_build_options.c | 14 - source/blender/python/intern/bpy_app_handlers.c | 2 - source/blender/python/intern/bpy_rna_callback.c | 1 - source/blender/python/mathutils/mathutils.h | 2 +- source/blender/render/CMakeLists.txt | 4 - source/blender/render/extern/include/RE_engine.h | 2 +- .../blender/render/intern/source/external_engine.c | 14 - source/blender/render/intern/source/pipeline.c | 4 +- source/blender/windowmanager/CMakeLists.txt | 5 - source/blender/windowmanager/WM_api.h | 1 - source/blender/windowmanager/intern/wm_files.c | 7 +- source/blender/windowmanager/intern/wm_init_exit.c | 102 +- source/blenderplayer/CMakeLists.txt | 274 -- .../bad_level_call_stubs/CMakeLists.txt | 79 - source/blenderplayer/bad_level_call_stubs/stubs.c | 871 ---- source/creator/CMakeLists.txt | 53 - source/creator/creator.c | 31 +- source/creator/creator_args.c | 108 +- source/creator/creator_intern.h | 2 +- source/creator/creator_signals.c | 7 - .../BlenderRoutines/BL_KetsjiEmbedStart.cpp | 683 ---- source/gameengine/BlenderRoutines/BL_System.cpp | 102 - source/gameengine/BlenderRoutines/BL_System.h | 70 - source/gameengine/BlenderRoutines/CMakeLists.txt | 78 - .../BlenderRoutines/KX_BlenderCanvas.cpp | 352 -- .../gameengine/BlenderRoutines/KX_BlenderCanvas.h | 222 -- .../BlenderRoutines/KX_BlenderInputDevice.cpp | 33 - .../BlenderRoutines/KX_BlenderInputDevice.h | 80 - .../BlenderRoutines/KX_BlenderKeyboardDevice.cpp | 169 - .../BlenderRoutines/KX_BlenderKeyboardDevice.h | 62 - .../BlenderRoutines/KX_BlenderMouseDevice.cpp | 192 - .../BlenderRoutines/KX_BlenderMouseDevice.h | 58 - .../BlenderRoutines/KX_BlenderSystem.cpp | 59 - .../gameengine/BlenderRoutines/KX_BlenderSystem.h | 56 - source/gameengine/CMakeLists.txt | 57 - source/gameengine/Converter/BL_ActionActuator.cpp | 664 ---- source/gameengine/Converter/BL_ActionActuator.h | 158 - .../gameengine/Converter/BL_ArmatureActuator.cpp | 271 -- source/gameengine/Converter/BL_ArmatureActuator.h | 96 - source/gameengine/Converter/BL_ArmatureChannel.cpp | 469 --- source/gameengine/Converter/BL_ArmatureChannel.h | 101 - .../gameengine/Converter/BL_ArmatureConstraint.cpp | 456 --- .../gameengine/Converter/BL_ArmatureConstraint.h | 125 - source/gameengine/Converter/BL_ArmatureObject.cpp | 691 ---- source/gameengine/Converter/BL_ArmatureObject.h | 145 - .../Converter/BL_BlenderDataConversion.cpp | 2473 ------------ .../Converter/BL_BlenderDataConversion.h | 56 - .../Converter/BL_DeformableGameObject.cpp | 116 - .../gameengine/Converter/BL_DeformableGameObject.h | 107 - source/gameengine/Converter/BL_MeshDeformer.cpp | 239 -- source/gameengine/Converter/BL_MeshDeformer.h | 98 - .../gameengine/Converter/BL_ModifierDeformer.cpp | 227 -- source/gameengine/Converter/BL_ModifierDeformer.h | 115 - .../Converter/BL_ShapeActionActuator.cpp | 563 --- .../gameengine/Converter/BL_ShapeActionActuator.h | 144 - source/gameengine/Converter/BL_ShapeDeformer.cpp | 237 -- source/gameengine/Converter/BL_ShapeDeformer.h | 86 - source/gameengine/Converter/BL_SkinDeformer.cpp | 384 -- source/gameengine/Converter/BL_SkinDeformer.h | 125 - source/gameengine/Converter/CMakeLists.txt | 123 - .../Converter/KX_BlenderScalarInterpolator.cpp | 81 - .../Converter/KX_BlenderScalarInterpolator.h | 76 - .../Converter/KX_BlenderSceneConverter.cpp | 1477 ------- .../Converter/KX_BlenderSceneConverter.h | 232 -- .../gameengine/Converter/KX_ConvertActuators.cpp | 1146 ------ source/gameengine/Converter/KX_ConvertActuators.h | 45 - .../gameengine/Converter/KX_ConvertControllers.cpp | 250 -- .../gameengine/Converter/KX_ConvertControllers.h | 47 - .../gameengine/Converter/KX_ConvertProperties.cpp | 243 -- source/gameengine/Converter/KX_ConvertProperties.h | 41 - source/gameengine/Converter/KX_ConvertSensors.cpp | 663 --- source/gameengine/Converter/KX_ConvertSensors.h | 45 - source/gameengine/Converter/KX_LibLoadStatus.cpp | 255 -- source/gameengine/Converter/KX_LibLoadStatus.h | 93 - .../gameengine/Converter/KX_SoftBodyDeformer.cpp | 121 - source/gameengine/Converter/KX_SoftBodyDeformer.h | 102 - source/gameengine/Expressions/CMakeLists.txt | 91 - source/gameengine/Expressions/EXP_BoolValue.h | 65 - source/gameengine/Expressions/EXP_ConstExpr.h | 54 - source/gameengine/Expressions/EXP_EmptyValue.h | 49 - source/gameengine/Expressions/EXP_ErrorValue.h | 47 - source/gameengine/Expressions/EXP_Expression.h | 149 - source/gameengine/Expressions/EXP_FloatValue.h | 58 - source/gameengine/Expressions/EXP_HashedPtr.h | 59 - source/gameengine/Expressions/EXP_IdentifierExpr.h | 59 - source/gameengine/Expressions/EXP_IfExpr.h | 54 - source/gameengine/Expressions/EXP_InputParser.h | 118 - source/gameengine/Expressions/EXP_IntValue.h | 73 - source/gameengine/Expressions/EXP_ListValue.h | 92 - source/gameengine/Expressions/EXP_ListWrapper.h | 109 - source/gameengine/Expressions/EXP_Operator1Expr.h | 59 - source/gameengine/Expressions/EXP_Operator2Expr.h | 66 - source/gameengine/Expressions/EXP_PyObjectPlus.h | 648 --- source/gameengine/Expressions/EXP_Python.h | 82 - source/gameengine/Expressions/EXP_PythonCallBack.h | 40 - source/gameengine/Expressions/EXP_StringValue.h | 61 - source/gameengine/Expressions/EXP_Value.h | 432 -- source/gameengine/Expressions/EXP_VectorValue.h | 94 - source/gameengine/Expressions/EXP_VoidValue.h | 81 - source/gameengine/Expressions/intern/BoolValue.cpp | 216 - source/gameengine/Expressions/intern/ConstExpr.cpp | 131 - .../gameengine/Expressions/intern/EmptyValue.cpp | 133 - .../gameengine/Expressions/intern/ErrorValue.cpp | 131 - .../gameengine/Expressions/intern/Expression.cpp | 77 - .../gameengine/Expressions/intern/FloatValue.cpp | 329 -- source/gameengine/Expressions/intern/HashedPtr.cpp | 57 - .../Expressions/intern/IdentifierExpr.cpp | 103 - source/gameengine/Expressions/intern/IfExpr.cpp | 144 - .../gameengine/Expressions/intern/InputParser.cpp | 669 ---- source/gameengine/Expressions/intern/IntValue.cpp | 344 -- source/gameengine/Expressions/intern/ListValue.cpp | 702 ---- .../gameengine/Expressions/intern/ListWrapper.cpp | 424 -- .../Expressions/intern/Operator1Expr.cpp | 151 - .../Expressions/intern/Operator2Expr.cpp | 276 -- .../gameengine/Expressions/intern/PyObjectPlus.cpp | 1226 ------ .../Expressions/intern/PythonCallBack.cpp | 119 - .../gameengine/Expressions/intern/StringValue.cpp | 147 - source/gameengine/Expressions/intern/Value.cpp | 672 ---- .../gameengine/Expressions/intern/VectorValue.cpp | 225 -- source/gameengine/GameLogic/CMakeLists.txt | 147 - .../gameengine/GameLogic/Joystick/SCA_Joystick.cpp | 382 -- .../gameengine/GameLogic/Joystick/SCA_Joystick.h | 214 - .../GameLogic/Joystick/SCA_JoystickDefines.h | 56 - .../GameLogic/Joystick/SCA_JoystickEvents.cpp | 137 - .../GameLogic/Joystick/SCA_JoystickPrivate.h | 52 - .../gameengine/GameLogic/SCA_2DFilterActuator.cpp | 153 - source/gameengine/GameLogic/SCA_2DFilterActuator.h | 71 - source/gameengine/GameLogic/SCA_ANDController.cpp | 131 - source/gameengine/GameLogic/SCA_ANDController.h | 51 - .../GameLogic/SCA_ActuatorEventManager.cpp | 68 - .../GameLogic/SCA_ActuatorEventManager.h | 56 - source/gameengine/GameLogic/SCA_ActuatorSensor.cpp | 171 - source/gameengine/GameLogic/SCA_ActuatorSensor.h | 70 - .../GameLogic/SCA_AlwaysEventManager.cpp | 59 - .../gameengine/GameLogic/SCA_AlwaysEventManager.h | 50 - source/gameengine/GameLogic/SCA_AlwaysSensor.cpp | 139 - source/gameengine/GameLogic/SCA_AlwaysSensor.h | 53 - .../gameengine/GameLogic/SCA_BasicEventManager.cpp | 61 - .../gameengine/GameLogic/SCA_BasicEventManager.h | 57 - source/gameengine/GameLogic/SCA_DelaySensor.cpp | 170 - source/gameengine/GameLogic/SCA_DelaySensor.h | 66 - source/gameengine/GameLogic/SCA_EventManager.cpp | 83 - source/gameengine/GameLogic/SCA_EventManager.h | 91 - .../GameLogic/SCA_ExpressionController.cpp | 159 - .../GameLogic/SCA_ExpressionController.h | 66 - source/gameengine/GameLogic/SCA_IActuator.cpp | 140 - source/gameengine/GameLogic/SCA_IActuator.h | 168 - source/gameengine/GameLogic/SCA_IController.cpp | 298 -- source/gameengine/GameLogic/SCA_IController.h | 112 - source/gameengine/GameLogic/SCA_IInputDevice.cpp | 139 - source/gameengine/GameLogic/SCA_IInputDevice.h | 334 -- source/gameengine/GameLogic/SCA_ILogicBrick.cpp | 271 -- source/gameengine/GameLogic/SCA_ILogicBrick.h | 167 - source/gameengine/GameLogic/SCA_IObject.cpp | 349 -- source/gameengine/GameLogic/SCA_IObject.h | 229 -- source/gameengine/GameLogic/SCA_IScene.cpp | 145 - source/gameengine/GameLogic/SCA_IScene.h | 87 - source/gameengine/GameLogic/SCA_ISensor.cpp | 471 --- source/gameengine/GameLogic/SCA_ISensor.h | 220 - .../gameengine/GameLogic/SCA_JoystickManager.cpp | 92 - source/gameengine/GameLogic/SCA_JoystickManager.h | 59 - source/gameengine/GameLogic/SCA_JoystickSensor.cpp | 428 -- source/gameengine/GameLogic/SCA_JoystickSensor.h | 168 - .../gameengine/GameLogic/SCA_KeyboardManager.cpp | 80 - source/gameengine/GameLogic/SCA_KeyboardManager.h | 66 - source/gameengine/GameLogic/SCA_KeyboardSensor.cpp | 668 ---- source/gameengine/GameLogic/SCA_KeyboardSensor.h | 141 - source/gameengine/GameLogic/SCA_LogicManager.cpp | 342 -- source/gameengine/GameLogic/SCA_LogicManager.h | 154 - source/gameengine/GameLogic/SCA_MouseManager.cpp | 112 - source/gameengine/GameLogic/SCA_MouseManager.h | 75 - source/gameengine/GameLogic/SCA_MouseSensor.cpp | 317 -- source/gameengine/GameLogic/SCA_MouseSensor.h | 120 - source/gameengine/GameLogic/SCA_NANDController.cpp | 133 - source/gameengine/GameLogic/SCA_NANDController.h | 52 - source/gameengine/GameLogic/SCA_NORController.cpp | 133 - source/gameengine/GameLogic/SCA_NORController.h | 48 - source/gameengine/GameLogic/SCA_ORController.cpp | 129 - source/gameengine/GameLogic/SCA_ORController.h | 49 - .../gameengine/GameLogic/SCA_PropertyActuator.cpp | 293 -- source/gameengine/GameLogic/SCA_PropertyActuator.h | 90 - .../GameLogic/SCA_PropertyEventManager.cpp | 57 - .../GameLogic/SCA_PropertyEventManager.h | 55 - source/gameengine/GameLogic/SCA_PropertySensor.cpp | 332 -- source/gameengine/GameLogic/SCA_PropertySensor.h | 98 - .../gameengine/GameLogic/SCA_PythonController.cpp | 539 --- source/gameengine/GameLogic/SCA_PythonController.h | 118 - source/gameengine/GameLogic/SCA_PythonJoystick.cpp | 188 - source/gameengine/GameLogic/SCA_PythonJoystick.h | 56 - source/gameengine/GameLogic/SCA_PythonKeyboard.cpp | 153 - source/gameengine/GameLogic/SCA_PythonKeyboard.h | 50 - source/gameengine/GameLogic/SCA_PythonMouse.cpp | 206 - source/gameengine/GameLogic/SCA_PythonMouse.h | 59 - source/gameengine/GameLogic/SCA_RandomActuator.cpp | 543 --- source/gameengine/GameLogic/SCA_RandomActuator.h | 120 - .../GameLogic/SCA_RandomEventManager.cpp | 58 - .../gameengine/GameLogic/SCA_RandomEventManager.h | 54 - .../GameLogic/SCA_RandomNumberGenerator.cpp | 133 - .../GameLogic/SCA_RandomNumberGenerator.h | 85 - source/gameengine/GameLogic/SCA_RandomSensor.cpp | 187 - source/gameengine/GameLogic/SCA_RandomSensor.h | 71 - .../gameengine/GameLogic/SCA_TimeEventManager.cpp | 120 - source/gameengine/GameLogic/SCA_TimeEventManager.h | 62 - source/gameengine/GameLogic/SCA_XNORController.cpp | 137 - source/gameengine/GameLogic/SCA_XNORController.h | 53 - source/gameengine/GameLogic/SCA_XORController.cpp | 136 - source/gameengine/GameLogic/SCA_XORController.h | 48 - source/gameengine/GamePlayer/CMakeLists.txt | 27 - source/gameengine/GamePlayer/common/CMakeLists.txt | 75 - source/gameengine/GamePlayer/common/GPC_Canvas.cpp | 168 - source/gameengine/GamePlayer/common/GPC_Canvas.h | 147 - .../GamePlayer/common/GPC_KeyboardDevice.cpp | 128 - .../GamePlayer/common/GPC_KeyboardDevice.h | 90 - .../GamePlayer/common/GPC_MouseDevice.cpp | 214 - .../gameengine/GamePlayer/common/GPC_MouseDevice.h | 103 - source/gameengine/GamePlayer/ghost/CMakeLists.txt | 112 - .../GamePlayer/ghost/GPG_Application.cpp | 998 ----- .../gameengine/GamePlayer/ghost/GPG_Application.h | 181 - source/gameengine/GamePlayer/ghost/GPG_Canvas.cpp | 177 - source/gameengine/GamePlayer/ghost/GPG_Canvas.h | 76 - .../GamePlayer/ghost/GPG_KeyboardDevice.cpp | 165 - .../GamePlayer/ghost/GPG_KeyboardDevice.h | 56 - source/gameengine/GamePlayer/ghost/GPG_System.cpp | 53 - source/gameengine/GamePlayer/ghost/GPG_System.h | 54 - source/gameengine/GamePlayer/ghost/GPG_ghost.cpp | 1228 ------ 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 - source/gameengine/Network/CMakeLists.txt | 48 - .../Network/LoopBackNetwork/CMakeLists.txt | 43 - .../NG_LoopBackNetworkDeviceInterface.cpp | 112 - .../NG_LoopBackNetworkDeviceInterface.h | 63 - .../gameengine/Network/NG_NetworkDeviceInterface.h | 82 - source/gameengine/Network/NG_NetworkMessage.cpp | 55 - source/gameengine/Network/NG_NetworkMessage.h | 138 - source/gameengine/Network/NG_NetworkObject.cpp | 46 - source/gameengine/Network/NG_NetworkObject.h | 55 - source/gameengine/Network/NG_NetworkScene.cpp | 272 -- source/gameengine/Network/NG_NetworkScene.h | 118 - source/gameengine/Physics/Bullet/CMakeLists.txt | 73 - .../Physics/Bullet/CcdGraphicController.cpp | 152 - .../Physics/Bullet/CcdGraphicController.h | 90 - .../Physics/Bullet/CcdPhysicsController.cpp | 2668 ------------- .../Physics/Bullet/CcdPhysicsController.h | 832 ---- .../Physics/Bullet/CcdPhysicsEnvironment.cpp | 3795 ------------------ .../Physics/Bullet/CcdPhysicsEnvironment.h | 345 -- source/gameengine/Physics/Dummy/CMakeLists.txt | 41 - .../Physics/Dummy/DummyPhysicsEnvironment.cpp | 121 - .../Physics/Dummy/DummyPhysicsEnvironment.h | 134 - .../gameengine/Physics/common/PHY_DynamicTypes.h | 91 - source/gameengine/Physics/common/PHY_ICharacter.h | 39 - source/gameengine/Physics/common/PHY_IController.h | 63 - .../Physics/common/PHY_IGraphicController.h | 60 - .../gameengine/Physics/common/PHY_IMotionState.h | 68 - .../Physics/common/PHY_IPhysicsController.h | 154 - .../Physics/common/PHY_IPhysicsEnvironment.h | 226 -- source/gameengine/Physics/common/PHY_IVehicle.h | 69 - source/gameengine/Physics/common/PHY_Pro.h | 68 - source/gameengine/Rasterizer/CMakeLists.txt | 92 - .../gameengine/Rasterizer/RAS_2DFilterManager.cpp | 562 --- source/gameengine/Rasterizer/RAS_2DFilterManager.h | 114 - source/gameengine/Rasterizer/RAS_BucketManager.cpp | 380 -- source/gameengine/Rasterizer/RAS_BucketManager.h | 93 - source/gameengine/Rasterizer/RAS_CameraData.h | 79 - source/gameengine/Rasterizer/RAS_Deformer.h | 103 - .../gameengine/Rasterizer/RAS_FramingManager.cpp | 425 -- source/gameengine/Rasterizer/RAS_FramingManager.h | 316 -- source/gameengine/Rasterizer/RAS_ICanvas.cpp | 128 - source/gameengine/Rasterizer/RAS_ICanvas.h | 287 -- source/gameengine/Rasterizer/RAS_ILightObject.h | 95 - source/gameengine/Rasterizer/RAS_IOffScreen.h | 84 - .../gameengine/Rasterizer/RAS_IPolygonMaterial.cpp | 292 -- .../gameengine/Rasterizer/RAS_IPolygonMaterial.h | 206 - source/gameengine/Rasterizer/RAS_IRasterizer.h | 506 --- source/gameengine/Rasterizer/RAS_ISync.h | 48 - .../gameengine/Rasterizer/RAS_MaterialBucket.cpp | 679 ---- source/gameengine/Rasterizer/RAS_MaterialBucket.h | 267 -- source/gameengine/Rasterizer/RAS_MeshObject.cpp | 573 --- source/gameengine/Rasterizer/RAS_MeshObject.h | 161 - source/gameengine/Rasterizer/RAS_ObjectColor.h | 41 - .../RAS_OpenGLFilters/RAS_Blur2DFilter.h | 55 - .../RAS_OpenGLFilters/RAS_Dilation2DFilter.h | 55 - .../RAS_OpenGLFilters/RAS_Erosion2DFilter.h | 54 - .../RAS_OpenGLFilters/RAS_GrayScale2DFilter.h | 45 - .../RAS_OpenGLFilters/RAS_Invert2DFilter.h | 45 - .../RAS_OpenGLFilters/RAS_Laplacian2DFilter.h | 57 - .../RAS_OpenGLFilters/RAS_Prewitt2DFilter.h | 62 - .../RAS_OpenGLFilters/RAS_Sepia2DFilter.h | 45 - .../RAS_OpenGLFilters/RAS_Sharpen2DFilter.h | 55 - .../RAS_OpenGLFilters/RAS_Sobel2DFilter.h | 61 - .../Rasterizer/RAS_OpenGLRasterizer/CMakeLists.txt | 72 - .../Rasterizer/RAS_OpenGLRasterizer/RAS_IStorage.h | 56 - .../RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp | 278 -- .../RAS_OpenGLRasterizer/RAS_ListRasterizer.h | 77 - .../RAS_OpenGLRasterizer/RAS_OpenGLLight.cpp | 300 -- .../RAS_OpenGLRasterizer/RAS_OpenGLLight.h | 56 - .../RAS_OpenGLRasterizer/RAS_OpenGLOffScreen.cpp | 347 -- .../RAS_OpenGLRasterizer/RAS_OpenGLOffScreen.h | 65 - .../RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp | 1694 -------- .../RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h | 343 -- .../RAS_OpenGLRasterizer/RAS_OpenGLSync.cpp | 82 - .../RAS_OpenGLRasterizer/RAS_OpenGLSync.h | 50 - .../RAS_OpenGLRasterizer/RAS_StorageVA.cpp | 260 -- .../RAS_OpenGLRasterizer/RAS_StorageVA.h | 77 - .../RAS_OpenGLRasterizer/RAS_StorageVBO.cpp | 227 -- .../RAS_OpenGLRasterizer/RAS_StorageVBO.h | 100 - source/gameengine/Rasterizer/RAS_Polygon.cpp | 123 - source/gameengine/Rasterizer/RAS_Polygon.h | 101 - source/gameengine/Rasterizer/RAS_Rect.h | 104 - source/gameengine/Rasterizer/RAS_TexMatrix.h | 42 - source/gameengine/Rasterizer/RAS_TexVert.cpp | 164 - source/gameengine/Rasterizer/RAS_TexVert.h | 146 - source/gameengine/Rasterizer/RAS_texmatrix.cpp | 131 - source/gameengine/SceneGraph/CMakeLists.txt | 53 - source/gameengine/SceneGraph/SG_BBox.cpp | 262 -- source/gameengine/SceneGraph/SG_BBox.h | 143 - source/gameengine/SceneGraph/SG_Controller.cpp | 46 - source/gameengine/SceneGraph/SG_Controller.h | 124 - source/gameengine/SceneGraph/SG_DList.h | 251 -- source/gameengine/SceneGraph/SG_IObject.cpp | 111 - source/gameengine/SceneGraph/SG_IObject.h | 374 -- source/gameengine/SceneGraph/SG_Node.cpp | 227 -- source/gameengine/SceneGraph/SG_Node.h | 278 -- source/gameengine/SceneGraph/SG_ParentRelation.h | 139 - source/gameengine/SceneGraph/SG_QList.h | 164 - source/gameengine/SceneGraph/SG_Spatial.cpp | 217 - source/gameengine/SceneGraph/SG_Spatial.h | 294 -- source/gameengine/SceneGraph/SG_Tree.cpp | 422 -- source/gameengine/SceneGraph/SG_Tree.h | 163 - source/gameengine/VideoTexture/BlendType.h | 86 - source/gameengine/VideoTexture/CMakeLists.txt | 119 - source/gameengine/VideoTexture/Common.h | 64 - source/gameengine/VideoTexture/DeckLink.cpp | 813 ---- source/gameengine/VideoTexture/DeckLink.h | 86 - source/gameengine/VideoTexture/Exception.cpp | 241 -- source/gameengine/VideoTexture/Exception.h | 239 -- source/gameengine/VideoTexture/FilterBase.cpp | 160 - source/gameengine/VideoTexture/FilterBase.h | 161 - .../gameengine/VideoTexture/FilterBlueScreen.cpp | 190 - source/gameengine/VideoTexture/FilterBlueScreen.h | 105 - source/gameengine/VideoTexture/FilterColor.cpp | 354 -- source/gameengine/VideoTexture/FilterColor.h | 176 - source/gameengine/VideoTexture/FilterNormal.cpp | 173 - source/gameengine/VideoTexture/FilterNormal.h | 115 - source/gameengine/VideoTexture/FilterSource.cpp | 176 - source/gameengine/VideoTexture/FilterSource.h | 352 -- source/gameengine/VideoTexture/ImageBase.cpp | 834 ---- source/gameengine/VideoTexture/ImageBase.h | 392 -- source/gameengine/VideoTexture/ImageBuff.cpp | 424 -- source/gameengine/VideoTexture/ImageBuff.h | 69 - source/gameengine/VideoTexture/ImageMix.cpp | 216 - source/gameengine/VideoTexture/ImageMix.h | 131 - source/gameengine/VideoTexture/ImageRender.cpp | 946 ----- source/gameengine/VideoTexture/ImageRender.h | 125 - source/gameengine/VideoTexture/ImageViewport.cpp | 467 --- source/gameengine/VideoTexture/ImageViewport.h | 113 - source/gameengine/VideoTexture/PyTypeList.cpp | 97 - source/gameengine/VideoTexture/PyTypeList.h | 100 - source/gameengine/VideoTexture/Texture.cpp | 533 --- source/gameengine/VideoTexture/Texture.h | 99 - source/gameengine/VideoTexture/VideoBase.cpp | 254 -- source/gameengine/VideoTexture/VideoBase.h | 207 - source/gameengine/VideoTexture/VideoDeckLink.cpp | 1228 ------ source/gameengine/VideoTexture/VideoDeckLink.h | 256 -- source/gameengine/VideoTexture/VideoFFmpeg.cpp | 1392 ------- source/gameengine/VideoTexture/VideoFFmpeg.h | 219 - source/gameengine/VideoTexture/blendVideoTex.cpp | 266 -- 651 files changed, 122 insertions(+), 146479 deletions(-) delete mode 100644 source/blender/blenkernel/BKE_bullet.h delete mode 100644 source/blender/blenkernel/BKE_navmesh_conversion.h delete mode 100644 source/blender/blenkernel/BKE_property.h delete mode 100644 source/blender/blenkernel/BKE_sca.h delete mode 100644 source/blender/blenkernel/intern/bullet.c delete mode 100644 source/blender/blenkernel/intern/navmesh_conversion.c delete mode 100644 source/blender/blenkernel/intern/property.c delete mode 100644 source/blender/blenkernel/intern/sca.c delete mode 100644 source/blender/editors/mesh/mesh_navmesh.c delete mode 100644 source/blender/editors/object/object_lod.c delete mode 100644 source/blender/editors/space_logic/CMakeLists.txt delete mode 100644 source/blender/editors/space_logic/logic_buttons.c delete mode 100644 source/blender/editors/space_logic/logic_intern.h delete mode 100644 source/blender/editors/space_logic/logic_ops.c delete mode 100644 source/blender/editors/space_logic/logic_window.c delete mode 100644 source/blender/editors/space_logic/space_logic.c delete mode 100644 source/blender/makesdna/DNA_actuator_types.h delete mode 100644 source/blender/makesdna/DNA_controller_types.h delete mode 100644 source/blender/makesdna/DNA_property_types.h delete mode 100644 source/blender/makesdna/DNA_sensor_types.h delete mode 100644 source/blender/makesrna/intern/rna_actuator.c delete mode 100644 source/blender/makesrna/intern/rna_actuator_api.c delete mode 100644 source/blender/makesrna/intern/rna_controller.c delete mode 100644 source/blender/makesrna/intern/rna_controller_api.c delete mode 100644 source/blender/makesrna/intern/rna_property.c delete mode 100644 source/blender/makesrna/intern/rna_sensor.c delete mode 100644 source/blender/makesrna/intern/rna_sensor_api.c delete mode 100644 source/blenderplayer/CMakeLists.txt delete mode 100644 source/blenderplayer/bad_level_call_stubs/CMakeLists.txt delete mode 100644 source/blenderplayer/bad_level_call_stubs/stubs.c delete mode 100644 source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp delete mode 100644 source/gameengine/BlenderRoutines/BL_System.cpp delete mode 100644 source/gameengine/BlenderRoutines/BL_System.h delete mode 100644 source/gameengine/BlenderRoutines/CMakeLists.txt delete mode 100644 source/gameengine/BlenderRoutines/KX_BlenderCanvas.cpp delete mode 100644 source/gameengine/BlenderRoutines/KX_BlenderCanvas.h delete mode 100644 source/gameengine/BlenderRoutines/KX_BlenderInputDevice.cpp delete mode 100644 source/gameengine/BlenderRoutines/KX_BlenderInputDevice.h delete mode 100644 source/gameengine/BlenderRoutines/KX_BlenderKeyboardDevice.cpp delete mode 100644 source/gameengine/BlenderRoutines/KX_BlenderKeyboardDevice.h delete mode 100644 source/gameengine/BlenderRoutines/KX_BlenderMouseDevice.cpp delete mode 100644 source/gameengine/BlenderRoutines/KX_BlenderMouseDevice.h delete mode 100644 source/gameengine/BlenderRoutines/KX_BlenderSystem.cpp delete mode 100644 source/gameengine/BlenderRoutines/KX_BlenderSystem.h delete mode 100644 source/gameengine/CMakeLists.txt delete mode 100644 source/gameengine/Converter/BL_ActionActuator.cpp delete mode 100644 source/gameengine/Converter/BL_ActionActuator.h delete mode 100644 source/gameengine/Converter/BL_ArmatureActuator.cpp delete mode 100644 source/gameengine/Converter/BL_ArmatureActuator.h delete mode 100644 source/gameengine/Converter/BL_ArmatureChannel.cpp delete mode 100644 source/gameengine/Converter/BL_ArmatureChannel.h delete mode 100644 source/gameengine/Converter/BL_ArmatureConstraint.cpp delete mode 100644 source/gameengine/Converter/BL_ArmatureConstraint.h delete mode 100644 source/gameengine/Converter/BL_ArmatureObject.cpp delete mode 100644 source/gameengine/Converter/BL_ArmatureObject.h delete mode 100644 source/gameengine/Converter/BL_BlenderDataConversion.cpp delete mode 100644 source/gameengine/Converter/BL_BlenderDataConversion.h delete mode 100644 source/gameengine/Converter/BL_DeformableGameObject.cpp delete mode 100644 source/gameengine/Converter/BL_DeformableGameObject.h delete mode 100644 source/gameengine/Converter/BL_MeshDeformer.cpp delete mode 100644 source/gameengine/Converter/BL_MeshDeformer.h delete mode 100644 source/gameengine/Converter/BL_ModifierDeformer.cpp delete mode 100644 source/gameengine/Converter/BL_ModifierDeformer.h delete mode 100644 source/gameengine/Converter/BL_ShapeActionActuator.cpp delete mode 100644 source/gameengine/Converter/BL_ShapeActionActuator.h delete mode 100644 source/gameengine/Converter/BL_ShapeDeformer.cpp delete mode 100644 source/gameengine/Converter/BL_ShapeDeformer.h delete mode 100644 source/gameengine/Converter/BL_SkinDeformer.cpp delete mode 100644 source/gameengine/Converter/BL_SkinDeformer.h delete mode 100644 source/gameengine/Converter/CMakeLists.txt delete mode 100644 source/gameengine/Converter/KX_BlenderScalarInterpolator.cpp delete mode 100644 source/gameengine/Converter/KX_BlenderScalarInterpolator.h delete mode 100644 source/gameengine/Converter/KX_BlenderSceneConverter.cpp delete mode 100644 source/gameengine/Converter/KX_BlenderSceneConverter.h delete mode 100644 source/gameengine/Converter/KX_ConvertActuators.cpp delete mode 100644 source/gameengine/Converter/KX_ConvertActuators.h delete mode 100644 source/gameengine/Converter/KX_ConvertControllers.cpp delete mode 100644 source/gameengine/Converter/KX_ConvertControllers.h delete mode 100644 source/gameengine/Converter/KX_ConvertProperties.cpp delete mode 100644 source/gameengine/Converter/KX_ConvertProperties.h delete mode 100644 source/gameengine/Converter/KX_ConvertSensors.cpp delete mode 100644 source/gameengine/Converter/KX_ConvertSensors.h delete mode 100644 source/gameengine/Converter/KX_LibLoadStatus.cpp delete mode 100644 source/gameengine/Converter/KX_LibLoadStatus.h delete mode 100644 source/gameengine/Converter/KX_SoftBodyDeformer.cpp delete mode 100644 source/gameengine/Converter/KX_SoftBodyDeformer.h delete mode 100644 source/gameengine/Expressions/CMakeLists.txt delete mode 100644 source/gameengine/Expressions/EXP_BoolValue.h delete mode 100644 source/gameengine/Expressions/EXP_ConstExpr.h delete mode 100644 source/gameengine/Expressions/EXP_EmptyValue.h delete mode 100644 source/gameengine/Expressions/EXP_ErrorValue.h delete mode 100644 source/gameengine/Expressions/EXP_Expression.h delete mode 100644 source/gameengine/Expressions/EXP_FloatValue.h delete mode 100644 source/gameengine/Expressions/EXP_HashedPtr.h delete mode 100644 source/gameengine/Expressions/EXP_IdentifierExpr.h delete mode 100644 source/gameengine/Expressions/EXP_IfExpr.h delete mode 100644 source/gameengine/Expressions/EXP_InputParser.h delete mode 100644 source/gameengine/Expressions/EXP_IntValue.h delete mode 100644 source/gameengine/Expressions/EXP_ListValue.h delete mode 100644 source/gameengine/Expressions/EXP_ListWrapper.h delete mode 100644 source/gameengine/Expressions/EXP_Operator1Expr.h delete mode 100644 source/gameengine/Expressions/EXP_Operator2Expr.h delete mode 100644 source/gameengine/Expressions/EXP_PyObjectPlus.h delete mode 100644 source/gameengine/Expressions/EXP_Python.h delete mode 100644 source/gameengine/Expressions/EXP_PythonCallBack.h delete mode 100644 source/gameengine/Expressions/EXP_StringValue.h delete mode 100644 source/gameengine/Expressions/EXP_Value.h delete mode 100644 source/gameengine/Expressions/EXP_VectorValue.h delete mode 100644 source/gameengine/Expressions/EXP_VoidValue.h delete mode 100644 source/gameengine/Expressions/intern/BoolValue.cpp delete mode 100644 source/gameengine/Expressions/intern/ConstExpr.cpp delete mode 100644 source/gameengine/Expressions/intern/EmptyValue.cpp delete mode 100644 source/gameengine/Expressions/intern/ErrorValue.cpp delete mode 100644 source/gameengine/Expressions/intern/Expression.cpp delete mode 100644 source/gameengine/Expressions/intern/FloatValue.cpp delete mode 100644 source/gameengine/Expressions/intern/HashedPtr.cpp delete mode 100644 source/gameengine/Expressions/intern/IdentifierExpr.cpp delete mode 100644 source/gameengine/Expressions/intern/IfExpr.cpp delete mode 100644 source/gameengine/Expressions/intern/InputParser.cpp delete mode 100644 source/gameengine/Expressions/intern/IntValue.cpp delete mode 100644 source/gameengine/Expressions/intern/ListValue.cpp delete mode 100644 source/gameengine/Expressions/intern/ListWrapper.cpp delete mode 100644 source/gameengine/Expressions/intern/Operator1Expr.cpp delete mode 100644 source/gameengine/Expressions/intern/Operator2Expr.cpp delete mode 100644 source/gameengine/Expressions/intern/PyObjectPlus.cpp delete mode 100644 source/gameengine/Expressions/intern/PythonCallBack.cpp delete mode 100644 source/gameengine/Expressions/intern/StringValue.cpp delete mode 100644 source/gameengine/Expressions/intern/Value.cpp delete mode 100644 source/gameengine/Expressions/intern/VectorValue.cpp delete mode 100644 source/gameengine/GameLogic/CMakeLists.txt delete mode 100644 source/gameengine/GameLogic/Joystick/SCA_Joystick.cpp delete mode 100644 source/gameengine/GameLogic/Joystick/SCA_Joystick.h delete mode 100644 source/gameengine/GameLogic/Joystick/SCA_JoystickDefines.h delete mode 100644 source/gameengine/GameLogic/Joystick/SCA_JoystickEvents.cpp delete mode 100644 source/gameengine/GameLogic/Joystick/SCA_JoystickPrivate.h delete mode 100644 source/gameengine/GameLogic/SCA_2DFilterActuator.cpp delete mode 100644 source/gameengine/GameLogic/SCA_2DFilterActuator.h delete mode 100644 source/gameengine/GameLogic/SCA_ANDController.cpp delete mode 100644 source/gameengine/GameLogic/SCA_ANDController.h delete mode 100644 source/gameengine/GameLogic/SCA_ActuatorEventManager.cpp delete mode 100644 source/gameengine/GameLogic/SCA_ActuatorEventManager.h delete mode 100644 source/gameengine/GameLogic/SCA_ActuatorSensor.cpp delete mode 100644 source/gameengine/GameLogic/SCA_ActuatorSensor.h delete mode 100644 source/gameengine/GameLogic/SCA_AlwaysEventManager.cpp delete mode 100644 source/gameengine/GameLogic/SCA_AlwaysEventManager.h delete mode 100644 source/gameengine/GameLogic/SCA_AlwaysSensor.cpp delete mode 100644 source/gameengine/GameLogic/SCA_AlwaysSensor.h delete mode 100644 source/gameengine/GameLogic/SCA_BasicEventManager.cpp delete mode 100644 source/gameengine/GameLogic/SCA_BasicEventManager.h delete mode 100644 source/gameengine/GameLogic/SCA_DelaySensor.cpp delete mode 100644 source/gameengine/GameLogic/SCA_DelaySensor.h delete mode 100644 source/gameengine/GameLogic/SCA_EventManager.cpp delete mode 100644 source/gameengine/GameLogic/SCA_EventManager.h delete mode 100644 source/gameengine/GameLogic/SCA_ExpressionController.cpp delete mode 100644 source/gameengine/GameLogic/SCA_ExpressionController.h delete mode 100644 source/gameengine/GameLogic/SCA_IActuator.cpp delete mode 100644 source/gameengine/GameLogic/SCA_IActuator.h delete mode 100644 source/gameengine/GameLogic/SCA_IController.cpp delete mode 100644 source/gameengine/GameLogic/SCA_IController.h delete mode 100644 source/gameengine/GameLogic/SCA_IInputDevice.cpp delete mode 100644 source/gameengine/GameLogic/SCA_IInputDevice.h delete mode 100644 source/gameengine/GameLogic/SCA_ILogicBrick.cpp delete mode 100644 source/gameengine/GameLogic/SCA_ILogicBrick.h delete mode 100644 source/gameengine/GameLogic/SCA_IObject.cpp delete mode 100644 source/gameengine/GameLogic/SCA_IObject.h delete mode 100644 source/gameengine/GameLogic/SCA_IScene.cpp delete mode 100644 source/gameengine/GameLogic/SCA_IScene.h delete mode 100644 source/gameengine/GameLogic/SCA_ISensor.cpp delete mode 100644 source/gameengine/GameLogic/SCA_ISensor.h delete mode 100644 source/gameengine/GameLogic/SCA_JoystickManager.cpp delete mode 100644 source/gameengine/GameLogic/SCA_JoystickManager.h delete mode 100644 source/gameengine/GameLogic/SCA_JoystickSensor.cpp delete mode 100644 source/gameengine/GameLogic/SCA_JoystickSensor.h delete mode 100644 source/gameengine/GameLogic/SCA_KeyboardManager.cpp delete mode 100644 source/gameengine/GameLogic/SCA_KeyboardManager.h delete mode 100644 source/gameengine/GameLogic/SCA_KeyboardSensor.cpp delete mode 100644 source/gameengine/GameLogic/SCA_KeyboardSensor.h delete mode 100644 source/gameengine/GameLogic/SCA_LogicManager.cpp delete mode 100644 source/gameengine/GameLogic/SCA_LogicManager.h delete mode 100644 source/gameengine/GameLogic/SCA_MouseManager.cpp delete mode 100644 source/gameengine/GameLogic/SCA_MouseManager.h delete mode 100644 source/gameengine/GameLogic/SCA_MouseSensor.cpp delete mode 100644 source/gameengine/GameLogic/SCA_MouseSensor.h delete mode 100644 source/gameengine/GameLogic/SCA_NANDController.cpp delete mode 100644 source/gameengine/GameLogic/SCA_NANDController.h delete mode 100644 source/gameengine/GameLogic/SCA_NORController.cpp delete mode 100644 source/gameengine/GameLogic/SCA_NORController.h delete mode 100644 source/gameengine/GameLogic/SCA_ORController.cpp delete mode 100644 source/gameengine/GameLogic/SCA_ORController.h delete mode 100644 source/gameengine/GameLogic/SCA_PropertyActuator.cpp delete mode 100644 source/gameengine/GameLogic/SCA_PropertyActuator.h delete mode 100644 source/gameengine/GameLogic/SCA_PropertyEventManager.cpp delete mode 100644 source/gameengine/GameLogic/SCA_PropertyEventManager.h delete mode 100644 source/gameengine/GameLogic/SCA_PropertySensor.cpp delete mode 100644 source/gameengine/GameLogic/SCA_PropertySensor.h delete mode 100644 source/gameengine/GameLogic/SCA_PythonController.cpp delete mode 100644 source/gameengine/GameLogic/SCA_PythonController.h delete mode 100644 source/gameengine/GameLogic/SCA_PythonJoystick.cpp delete mode 100644 source/gameengine/GameLogic/SCA_PythonJoystick.h delete mode 100644 source/gameengine/GameLogic/SCA_PythonKeyboard.cpp delete mode 100644 source/gameengine/GameLogic/SCA_PythonKeyboard.h delete mode 100644 source/gameengine/GameLogic/SCA_PythonMouse.cpp delete mode 100644 source/gameengine/GameLogic/SCA_PythonMouse.h delete mode 100644 source/gameengine/GameLogic/SCA_RandomActuator.cpp delete mode 100644 source/gameengine/GameLogic/SCA_RandomActuator.h delete mode 100644 source/gameengine/GameLogic/SCA_RandomEventManager.cpp delete mode 100644 source/gameengine/GameLogic/SCA_RandomEventManager.h delete mode 100644 source/gameengine/GameLogic/SCA_RandomNumberGenerator.cpp delete mode 100644 source/gameengine/GameLogic/SCA_RandomNumberGenerator.h delete mode 100644 source/gameengine/GameLogic/SCA_RandomSensor.cpp delete mode 100644 source/gameengine/GameLogic/SCA_RandomSensor.h delete mode 100644 source/gameengine/GameLogic/SCA_TimeEventManager.cpp delete mode 100644 source/gameengine/GameLogic/SCA_TimeEventManager.h delete mode 100644 source/gameengine/GameLogic/SCA_XNORController.cpp delete mode 100644 source/gameengine/GameLogic/SCA_XNORController.h delete mode 100644 source/gameengine/GameLogic/SCA_XORController.cpp delete mode 100644 source/gameengine/GameLogic/SCA_XORController.h delete mode 100644 source/gameengine/GamePlayer/CMakeLists.txt delete mode 100644 source/gameengine/GamePlayer/common/CMakeLists.txt delete mode 100644 source/gameengine/GamePlayer/common/GPC_Canvas.cpp delete mode 100644 source/gameengine/GamePlayer/common/GPC_Canvas.h delete mode 100644 source/gameengine/GamePlayer/common/GPC_KeyboardDevice.cpp delete mode 100644 source/gameengine/GamePlayer/common/GPC_KeyboardDevice.h delete mode 100644 source/gameengine/GamePlayer/common/GPC_MouseDevice.cpp delete mode 100644 source/gameengine/GamePlayer/common/GPC_MouseDevice.h delete mode 100644 source/gameengine/GamePlayer/ghost/CMakeLists.txt delete mode 100644 source/gameengine/GamePlayer/ghost/GPG_Application.cpp delete mode 100644 source/gameengine/GamePlayer/ghost/GPG_Application.h delete mode 100644 source/gameengine/GamePlayer/ghost/GPG_Canvas.cpp delete mode 100644 source/gameengine/GamePlayer/ghost/GPG_Canvas.h delete mode 100644 source/gameengine/GamePlayer/ghost/GPG_KeyboardDevice.cpp delete mode 100644 source/gameengine/GamePlayer/ghost/GPG_KeyboardDevice.h delete mode 100644 source/gameengine/GamePlayer/ghost/GPG_System.cpp delete mode 100644 source/gameengine/GamePlayer/ghost/GPG_System.h delete mode 100644 source/gameengine/GamePlayer/ghost/GPG_ghost.cpp 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 delete mode 100644 source/gameengine/Network/CMakeLists.txt delete mode 100644 source/gameengine/Network/LoopBackNetwork/CMakeLists.txt delete mode 100644 source/gameengine/Network/LoopBackNetwork/NG_LoopBackNetworkDeviceInterface.cpp delete mode 100644 source/gameengine/Network/LoopBackNetwork/NG_LoopBackNetworkDeviceInterface.h delete mode 100644 source/gameengine/Network/NG_NetworkDeviceInterface.h delete mode 100644 source/gameengine/Network/NG_NetworkMessage.cpp delete mode 100644 source/gameengine/Network/NG_NetworkMessage.h delete mode 100644 source/gameengine/Network/NG_NetworkObject.cpp delete mode 100644 source/gameengine/Network/NG_NetworkObject.h delete mode 100644 source/gameengine/Network/NG_NetworkScene.cpp delete mode 100644 source/gameengine/Network/NG_NetworkScene.h delete mode 100644 source/gameengine/Physics/Bullet/CMakeLists.txt delete mode 100644 source/gameengine/Physics/Bullet/CcdGraphicController.cpp delete mode 100644 source/gameengine/Physics/Bullet/CcdGraphicController.h delete mode 100644 source/gameengine/Physics/Bullet/CcdPhysicsController.cpp delete mode 100644 source/gameengine/Physics/Bullet/CcdPhysicsController.h delete mode 100644 source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp delete mode 100644 source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h delete mode 100644 source/gameengine/Physics/Dummy/CMakeLists.txt delete mode 100644 source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.cpp delete mode 100644 source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.h delete mode 100644 source/gameengine/Physics/common/PHY_DynamicTypes.h delete mode 100644 source/gameengine/Physics/common/PHY_ICharacter.h delete mode 100644 source/gameengine/Physics/common/PHY_IController.h delete mode 100644 source/gameengine/Physics/common/PHY_IGraphicController.h delete mode 100644 source/gameengine/Physics/common/PHY_IMotionState.h delete mode 100644 source/gameengine/Physics/common/PHY_IPhysicsController.h delete mode 100644 source/gameengine/Physics/common/PHY_IPhysicsEnvironment.h delete mode 100644 source/gameengine/Physics/common/PHY_IVehicle.h delete mode 100644 source/gameengine/Physics/common/PHY_Pro.h delete mode 100644 source/gameengine/Rasterizer/CMakeLists.txt delete mode 100644 source/gameengine/Rasterizer/RAS_2DFilterManager.cpp delete mode 100644 source/gameengine/Rasterizer/RAS_2DFilterManager.h delete mode 100644 source/gameengine/Rasterizer/RAS_BucketManager.cpp delete mode 100644 source/gameengine/Rasterizer/RAS_BucketManager.h delete mode 100644 source/gameengine/Rasterizer/RAS_CameraData.h delete mode 100644 source/gameengine/Rasterizer/RAS_Deformer.h delete mode 100644 source/gameengine/Rasterizer/RAS_FramingManager.cpp delete mode 100644 source/gameengine/Rasterizer/RAS_FramingManager.h delete mode 100644 source/gameengine/Rasterizer/RAS_ICanvas.cpp delete mode 100644 source/gameengine/Rasterizer/RAS_ICanvas.h delete mode 100644 source/gameengine/Rasterizer/RAS_ILightObject.h delete mode 100644 source/gameengine/Rasterizer/RAS_IOffScreen.h delete mode 100644 source/gameengine/Rasterizer/RAS_IPolygonMaterial.cpp delete mode 100644 source/gameengine/Rasterizer/RAS_IPolygonMaterial.h delete mode 100644 source/gameengine/Rasterizer/RAS_IRasterizer.h delete mode 100644 source/gameengine/Rasterizer/RAS_ISync.h delete mode 100644 source/gameengine/Rasterizer/RAS_MaterialBucket.cpp delete mode 100644 source/gameengine/Rasterizer/RAS_MaterialBucket.h delete mode 100644 source/gameengine/Rasterizer/RAS_MeshObject.cpp delete mode 100644 source/gameengine/Rasterizer/RAS_MeshObject.h delete mode 100644 source/gameengine/Rasterizer/RAS_ObjectColor.h delete mode 100644 source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Blur2DFilter.h delete mode 100644 source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Dilation2DFilter.h delete mode 100644 source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Erosion2DFilter.h delete mode 100644 source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_GrayScale2DFilter.h delete mode 100644 source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Invert2DFilter.h delete mode 100644 source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Laplacian2DFilter.h delete mode 100644 source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Prewitt2DFilter.h delete mode 100644 source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sepia2DFilter.h delete mode 100644 source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sharpen2DFilter.h delete mode 100644 source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sobel2DFilter.h delete mode 100644 source/gameengine/Rasterizer/RAS_OpenGLRasterizer/CMakeLists.txt delete mode 100644 source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_IStorage.h delete mode 100644 source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp delete mode 100644 source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.h delete mode 100644 source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLLight.cpp delete mode 100644 source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLLight.h delete mode 100644 source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLOffScreen.cpp delete mode 100644 source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLOffScreen.h delete mode 100644 source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp delete mode 100644 source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h delete mode 100644 source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLSync.cpp delete mode 100644 source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLSync.h delete mode 100644 source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVA.cpp delete mode 100644 source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVA.h delete mode 100644 source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVBO.cpp delete mode 100644 source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVBO.h delete mode 100644 source/gameengine/Rasterizer/RAS_Polygon.cpp delete mode 100644 source/gameengine/Rasterizer/RAS_Polygon.h delete mode 100644 source/gameengine/Rasterizer/RAS_Rect.h delete mode 100644 source/gameengine/Rasterizer/RAS_TexMatrix.h delete mode 100644 source/gameengine/Rasterizer/RAS_TexVert.cpp delete mode 100644 source/gameengine/Rasterizer/RAS_TexVert.h delete mode 100644 source/gameengine/Rasterizer/RAS_texmatrix.cpp delete mode 100644 source/gameengine/SceneGraph/CMakeLists.txt delete mode 100644 source/gameengine/SceneGraph/SG_BBox.cpp delete mode 100644 source/gameengine/SceneGraph/SG_BBox.h delete mode 100644 source/gameengine/SceneGraph/SG_Controller.cpp delete mode 100644 source/gameengine/SceneGraph/SG_Controller.h delete mode 100644 source/gameengine/SceneGraph/SG_DList.h delete mode 100644 source/gameengine/SceneGraph/SG_IObject.cpp delete mode 100644 source/gameengine/SceneGraph/SG_IObject.h delete mode 100644 source/gameengine/SceneGraph/SG_Node.cpp delete mode 100644 source/gameengine/SceneGraph/SG_Node.h delete mode 100644 source/gameengine/SceneGraph/SG_ParentRelation.h delete mode 100644 source/gameengine/SceneGraph/SG_QList.h delete mode 100644 source/gameengine/SceneGraph/SG_Spatial.cpp delete mode 100644 source/gameengine/SceneGraph/SG_Spatial.h delete mode 100644 source/gameengine/SceneGraph/SG_Tree.cpp delete mode 100644 source/gameengine/SceneGraph/SG_Tree.h delete mode 100644 source/gameengine/VideoTexture/BlendType.h delete mode 100644 source/gameengine/VideoTexture/CMakeLists.txt delete mode 100644 source/gameengine/VideoTexture/Common.h delete mode 100644 source/gameengine/VideoTexture/DeckLink.cpp delete mode 100644 source/gameengine/VideoTexture/DeckLink.h delete mode 100644 source/gameengine/VideoTexture/Exception.cpp delete mode 100644 source/gameengine/VideoTexture/Exception.h delete mode 100644 source/gameengine/VideoTexture/FilterBase.cpp delete mode 100644 source/gameengine/VideoTexture/FilterBase.h delete mode 100644 source/gameengine/VideoTexture/FilterBlueScreen.cpp delete mode 100644 source/gameengine/VideoTexture/FilterBlueScreen.h delete mode 100644 source/gameengine/VideoTexture/FilterColor.cpp delete mode 100644 source/gameengine/VideoTexture/FilterColor.h delete mode 100644 source/gameengine/VideoTexture/FilterNormal.cpp delete mode 100644 source/gameengine/VideoTexture/FilterNormal.h delete mode 100644 source/gameengine/VideoTexture/FilterSource.cpp delete mode 100644 source/gameengine/VideoTexture/FilterSource.h delete mode 100644 source/gameengine/VideoTexture/ImageBase.cpp delete mode 100644 source/gameengine/VideoTexture/ImageBase.h delete mode 100644 source/gameengine/VideoTexture/ImageBuff.cpp delete mode 100644 source/gameengine/VideoTexture/ImageBuff.h delete mode 100644 source/gameengine/VideoTexture/ImageMix.cpp delete mode 100644 source/gameengine/VideoTexture/ImageMix.h delete mode 100644 source/gameengine/VideoTexture/ImageRender.cpp delete mode 100644 source/gameengine/VideoTexture/ImageRender.h delete mode 100644 source/gameengine/VideoTexture/ImageViewport.cpp delete mode 100644 source/gameengine/VideoTexture/ImageViewport.h delete mode 100644 source/gameengine/VideoTexture/PyTypeList.cpp delete mode 100644 source/gameengine/VideoTexture/PyTypeList.h delete mode 100644 source/gameengine/VideoTexture/Texture.cpp delete mode 100644 source/gameengine/VideoTexture/Texture.h delete mode 100644 source/gameengine/VideoTexture/VideoBase.cpp delete mode 100644 source/gameengine/VideoTexture/VideoBase.h delete mode 100644 source/gameengine/VideoTexture/VideoDeckLink.cpp delete mode 100644 source/gameengine/VideoTexture/VideoDeckLink.h delete mode 100644 source/gameengine/VideoTexture/VideoFFmpeg.cpp delete mode 100644 source/gameengine/VideoTexture/VideoFFmpeg.h delete mode 100644 source/gameengine/VideoTexture/blendVideoTex.cpp (limited to 'source') diff --git a/source/CMakeLists.txt b/source/CMakeLists.txt index 4e4724771f3..f9260ecebc5 100644 --- a/source/CMakeLists.txt +++ b/source/CMakeLists.txt @@ -29,7 +29,3 @@ endif() add_subdirectory(blender) -if(WITH_GAMEENGINE) - add_subdirectory(gameengine) -endif() - diff --git a/source/blender/CMakeLists.txt b/source/blender/CMakeLists.txt index 316ab531a05..5709ac723f4 100644 --- a/source/blender/CMakeLists.txt +++ b/source/blender/CMakeLists.txt @@ -26,7 +26,6 @@ set(SRC_DNA_INC ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_ID.h ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_action_types.h - ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_actuator_types.h ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_anim_types.h ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_armature_types.h ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_boid_types.h @@ -36,7 +35,6 @@ set(SRC_DNA_INC ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_cloth_types.h ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_color_types.h ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_constraint_types.h - ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_controller_types.h ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_curve_types.h ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_customdata_types.h ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_defs.h @@ -72,12 +70,10 @@ set(SRC_DNA_INC ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_outliner_types.h ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_packedFile_types.h ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_particle_types.h - ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_property_types.h ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_rigidbody_types.h ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_scene_types.h ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_screen_types.h ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_sdna_types.h - ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_sensor_types.h ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_sequence_types.h ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_smoke_types.h ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_sound_types.h diff --git a/source/blender/blenkernel/BKE_DerivedMesh.h b/source/blender/blenkernel/BKE_DerivedMesh.h index d269a2fb63b..b038559e717 100644 --- a/source/blender/blenkernel/BKE_DerivedMesh.h +++ b/source/blender/blenkernel/BKE_DerivedMesh.h @@ -695,13 +695,6 @@ DerivedMesh *mesh_create_derived_no_deform_render( struct Depsgraph *depsgraph, struct Scene *scene, struct Object *ob, float (*vertCos)[3], CustomDataMask dataMask); -/* for gameengine */ -DerivedMesh *mesh_create_derived_no_virtual( - struct Depsgraph *depsgraph, struct Scene *scene, struct Object *ob, - float (*vertCos)[3], CustomDataMask dataMask); -DerivedMesh *mesh_create_derived_physics( - struct Depsgraph *depsgraph, struct Scene *scene, struct Object *ob, - float (*vertCos)[3], CustomDataMask dataMask); DerivedMesh *editbmesh_get_derived_base( struct Object *ob, struct BMEditMesh *em, CustomDataMask data_mask); diff --git a/source/blender/blenkernel/BKE_action.h b/source/blender/blenkernel/BKE_action.h index f7ebe85bcef..a203b76ea26 100644 --- a/source/blender/blenkernel/BKE_action.h +++ b/source/blender/blenkernel/BKE_action.h @@ -163,9 +163,6 @@ struct bPoseChannel *BKE_pose_channel_get_mirrored(const struct bPose *pose, con bool BKE_pose_channels_is_valid(const struct bPose *pose); #endif -/* Copy the data from the action-pose (src) into the pose */ -void extract_pose_from_pose(struct bPose *pose, const struct bPose *src); - /* sets constraint flags */ void BKE_pose_update_constraint_flags(struct bPose *pose); diff --git a/source/blender/blenkernel/BKE_blender_version.h b/source/blender/blenkernel/BKE_blender_version.h index 901f9e6d3ac..1e970291c01 100644 --- a/source/blender/blenkernel/BKE_blender_version.h +++ b/source/blender/blenkernel/BKE_blender_version.h @@ -28,7 +28,7 @@ * and keep comment above the defines. * Use STRINGIFY() rather than defining with quotes */ #define BLENDER_VERSION 280 -#define BLENDER_SUBVERSION 5 +#define BLENDER_SUBVERSION 6 /* Several breakages with 270, e.g. constraint deg vs rad */ #define BLENDER_MINVERSION 270 #define BLENDER_MINSUBVERSION 6 diff --git a/source/blender/blenkernel/BKE_bullet.h b/source/blender/blenkernel/BKE_bullet.h deleted file mode 100644 index dc522d1b22c..00000000000 --- a/source/blender/blenkernel/BKE_bullet.h +++ /dev/null @@ -1,44 +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 ***** - */ -#ifndef __BKE_BULLET_H__ -#define __BKE_BULLET_H__ - -/** \file BKE_bullet.h - * \ingroup bke - */ - -struct BulletSoftBody; - - -/* allocates and initializes general main data */ -extern struct BulletSoftBody *bsbNew(void); - -/* frees internal data and softbody itself */ -extern void bsbFree(struct BulletSoftBody *sb); - -#endif - diff --git a/source/blender/blenkernel/BKE_context.h b/source/blender/blenkernel/BKE_context.h index 5057168b9f6..3d722f5324e 100644 --- a/source/blender/blenkernel/BKE_context.h +++ b/source/blender/blenkernel/BKE_context.h @@ -173,7 +173,6 @@ struct SpaceOops *CTX_wm_space_outliner(const bContext *C); struct SpaceNla *CTX_wm_space_nla(const bContext *C); struct SpaceTime *CTX_wm_space_time(const bContext *C); struct SpaceNode *CTX_wm_space_node(const bContext *C); -struct SpaceLogic *CTX_wm_space_logic(const bContext *C); struct SpaceIpo *CTX_wm_space_graph(const bContext *C); struct SpaceAction *CTX_wm_space_action(const bContext *C); struct SpaceInfo *CTX_wm_space_info(const bContext *C); diff --git a/source/blender/blenkernel/BKE_global.h b/source/blender/blenkernel/BKE_global.h index c1b437661c5..e184fd3796b 100644 --- a/source/blender/blenkernel/BKE_global.h +++ b/source/blender/blenkernel/BKE_global.h @@ -102,7 +102,6 @@ typedef struct Global { /* G.f */ #define G_RENDER_OGL (1 << 0) #define G_SWAP_EXCHANGE (1 << 1) -/* also uses G_FILE_AUTOPLAY */ /* #define G_RENDER_SHADOW (1 << 3) */ /* temp flag, removed */ #define G_BACKBUFSEL (1 << 4) #define G_PICKSEL (1 << 5) @@ -154,16 +153,6 @@ enum { #define G_AUTOPACK (1 << 0) #define G_FILE_COMPRESS (1 << 1) -#define G_FILE_AUTOPLAY (1 << 2) - -#ifdef DNA_DEPRECATED_ALLOW -#define G_FILE_ENABLE_ALL_FRAMES (1 << 3) /* deprecated */ -#define G_FILE_SHOW_DEBUG_PROPS (1 << 4) /* deprecated */ -#define G_FILE_SHOW_FRAMERATE (1 << 5) /* deprecated */ -/* #define G_FILE_SHOW_PROFILE (1 << 6) */ /* deprecated */ -/* #define G_FILE_LOCK (1 << 7) */ /* deprecated */ -/* #define G_FILE_SIGN (1 << 8) */ /* deprecated */ -#endif /* DNA_DEPRECATED_ALLOW */ #define G_FILE_USERPREFS (1 << 9) #define G_FILE_NO_UI (1 << 10) diff --git a/source/blender/blenkernel/BKE_navmesh_conversion.h b/source/blender/blenkernel/BKE_navmesh_conversion.h deleted file mode 100644 index 3be363f4d7b..00000000000 --- a/source/blender/blenkernel/BKE_navmesh_conversion.h +++ /dev/null @@ -1,67 +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 ***** - */ - -#ifndef __BKE_NAVMESH_CONVERSION_H__ -#define __BKE_NAVMESH_CONVERSION_H__ - -/** \file BKE_navmesh_conversion.h - * \ingroup bke - */ - -struct DerivedMesh; - -/* navmesh_conversion.c */ -int buildNavMeshDataByDerivedMesh(struct DerivedMesh *dm, int *vertsPerPoly, - int *nverts, float **verts, - int *ndtris, unsigned short **dtris, - int *npolys, unsigned short **dmeshes, - unsigned short **polys, int **dtrisToPolysMap, - int **dtrisToTrisMap, int **trisToFacesMap); - -int buildRawVertIndicesData(struct DerivedMesh *dm, int *nverts, float **verts, - int *ntris, unsigned short **tris, int **trisToFacesMap, - int **recastData); - -int buildNavMeshData(const int nverts, const float *verts, - const int ntris, const unsigned short *tris, - const int *recastData, const int *trisToFacesMap, - int *ndtris, unsigned short **dtris, - int *npolys, unsigned short **dmeshes, unsigned short **polys, - int *vertsPerPoly, int **dtrisToPolysMap, int **dtrisToTrisMap); - -int buildPolygonsByDetailedMeshes(const int vertsPerPoly, const int npolys, - unsigned short *polys, const unsigned short *dmeshes, - const float *verts, const unsigned short *dtris, - const int *dtrisToPolysMap); - -int polyNumVerts(const unsigned short *p, const int vertsPerPoly); -int polyIsConvex(const unsigned short *p, const int vertsPerPoly, const float *verts); -int polyFindVertex(const unsigned short *p, const int vertsPerPoly, unsigned short vertexIdx); -float distPointToSegmentSq(const float *point, const float *a, const float *b); - - -#endif /* NAVMESH_CONVERSION_H */ diff --git a/source/blender/blenkernel/BKE_object.h b/source/blender/blenkernel/BKE_object.h index b51c4e17394..ce918826938 100644 --- a/source/blender/blenkernel/BKE_object.h +++ b/source/blender/blenkernel/BKE_object.h @@ -43,7 +43,6 @@ struct Object; struct BoundBox; struct View3D; struct SoftBody; -struct BulletSoftBody; struct MovieClip; struct Main; struct RigidBodyWorld; @@ -57,13 +56,11 @@ void BKE_object_workob_calc_parent(struct Depsgraph *depsgraph, struct Scene *sc void BKE_object_transform_copy(struct Object *ob_tar, const struct Object *ob_src); struct SoftBody *copy_softbody(const struct SoftBody *sb, const int flag); -struct BulletSoftBody *copy_bulletsoftbody(const struct BulletSoftBody *sb, const int flag); struct ParticleSystem *BKE_object_copy_particlesystem(struct ParticleSystem *psys, const int flag); void BKE_object_copy_particlesystems(struct Object *ob_dst, const struct Object *ob_src, const int flag); void BKE_object_copy_softbody(struct Object *ob_dst, const struct Object *ob_src); void BKE_object_free_particlesystems(struct Object *ob); void BKE_object_free_softbody(struct Object *ob); -void BKE_object_free_bulletsoftbody(struct Object *ob); void BKE_object_free_curve_cache(struct Object *ob); void BKE_object_free(struct Object *ob); @@ -113,14 +110,6 @@ void *BKE_object_obdata_add_from_type( int type, const char *name) ATTR_NONNULL(1); -void BKE_object_lod_add(struct Object *ob); -void BKE_object_lod_sort(struct Object *ob); -bool BKE_object_lod_remove(struct Object *ob, int level); -void BKE_object_lod_update(struct Object *ob, const float camera_position[3]); -bool BKE_object_lod_is_usable(struct Object *ob, struct ViewLayer *view_layer); -struct Object *BKE_object_lod_meshob_get(struct Object *ob, struct ViewLayer *view_layer); -struct Object *BKE_object_lod_matob_get(struct Object *ob, struct ViewLayer *view_layer); - void BKE_object_copy_data(struct Main *bmain, struct Object *ob_dst, const struct Object *ob_src, const int flag); struct Object *BKE_object_copy(struct Main *bmain, const struct Object *ob); void BKE_object_make_local(struct Main *bmain, struct Object *ob, const bool lib_local); diff --git a/source/blender/blenkernel/BKE_property.h b/source/blender/blenkernel/BKE_property.h deleted file mode 100644 index c787e8e8ed1..00000000000 --- a/source/blender/blenkernel/BKE_property.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 ***** - */ -#ifndef __BKE_PROPERTY_H__ -#define __BKE_PROPERTY_H__ - -/** \file BKE_property.h - * \ingroup bke - */ - -struct bProperty; -struct ListBase; -struct Object; - -void BKE_bproperty_free(struct bProperty *prop); -void BKE_bproperty_free_list(struct ListBase *lb); -struct bProperty *BKE_bproperty_copy(const struct bProperty *prop); -void BKE_bproperty_copy_list(struct ListBase *lbn, const struct ListBase *lbo); -void BKE_bproperty_init(struct bProperty *prop); -struct bProperty *BKE_bproperty_new(int type); -void BKE_bproperty_unique(struct bProperty *first, struct bProperty *prop, int force); -struct bProperty *BKE_bproperty_object_get(struct Object *ob, const char *name); -void BKE_bproperty_object_set(struct Object *ob, struct bProperty *propc); -// int BKE_bproperty_cmp(struct bProperty *prop, const char *str); -void BKE_bproperty_set(struct bProperty *prop, const char *str); -void BKE_bproperty_add(struct bProperty *prop, const char *str); -/* should really be called '_get_valstr()' or '_as_string()' */ -void BKE_bproperty_set_valstr(struct bProperty *prop, char str[MAX_PROPSTRING]); - -#endif diff --git a/source/blender/blenkernel/BKE_sca.h b/source/blender/blenkernel/BKE_sca.h deleted file mode 100644 index 35bcd91a9b1..00000000000 --- a/source/blender/blenkernel/BKE_sca.h +++ /dev/null @@ -1,92 +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 ***** - */ -#ifndef __BKE_SCA_H__ -#define __BKE_SCA_H__ - -/** \file BKE_sca.h - * \ingroup bke - */ - -struct Main; -struct Object; -struct bSensor; -struct bController; -struct bActuator; - -void link_logicbricks(void **poin, void ***ppoin, short *tot, short size); -void unlink_logicbricks(void **poin, void ***ppoin, short *tot); - -void unlink_controller(struct bController *cont); -void unlink_controllers(struct ListBase *lb); -void free_controller(struct bController *cont); -void free_controllers(struct ListBase *lb); - -void unlink_actuator(struct bActuator *act); -void unlink_actuators(struct ListBase *lb); -void free_actuator(struct bActuator *act); -void free_actuators(struct ListBase *lb); - -void free_sensor(struct bSensor *sens); -void free_sensors(struct ListBase *lb); -struct bSensor *copy_sensor(struct bSensor *sens, const int flag); -void copy_sensors(struct ListBase *lbn, const struct ListBase *lbo, const int flag); -void init_sensor(struct bSensor *sens); -struct bSensor *new_sensor(int type); -struct bController *copy_controller(struct bController *cont, const int flag); -void copy_controllers(struct ListBase *lbn, const struct ListBase *lbo, const int flag); -void init_controller(struct bController *cont); -struct bController *new_controller(int type); -struct bActuator *copy_actuator(struct bActuator *act, const int flag); -void copy_actuators(struct ListBase *lbn, const struct ListBase *lbo, const int flag); -void init_actuator(struct bActuator *act); -struct bActuator *new_actuator(int type); -void clear_sca_new_poins_ob(struct Object *ob); -void clear_sca_new_poins(void); -void set_sca_new_poins_ob(struct Object *ob); -void set_sca_new_poins(void); - -void BKE_sca_logic_links_remap(struct Main *bmain, struct Object *ob_old, struct Object *ob_new); -void BKE_sca_logic_copy(struct Object *ob_new, const struct Object *ob, const int flag); - -void sca_move_sensor(struct bSensor *sens_to_move, struct Object *ob, int move_up); -void sca_move_controller(struct bController *cont_to_move, struct Object *ob, int move_up); -void sca_move_actuator(struct bActuator *act_to_move, struct Object *ob, int move_up); - -/* Callback format for performing operations on ID-pointers for sensors/controllers/actuators. */ -typedef void (*SCASensorIDFunc)(struct bSensor *sensor, struct ID **idpoin, void *userdata, int cb_flag); -typedef void (*SCAControllerIDFunc)(struct bController *controller, struct ID **idpoin, void *userdata, int cb_flag); -typedef void (*SCAActuatorIDFunc)(struct bActuator *actuator, struct ID **idpoin, void *userdata, int cb_flag); - -void BKE_sca_sensors_id_loop(struct ListBase *senslist, SCASensorIDFunc func, void *userdata); -void BKE_sca_controllers_id_loop(struct ListBase *contlist, SCAControllerIDFunc func, void *userdata); -void BKE_sca_actuators_id_loop(struct ListBase *atclist, SCAActuatorIDFunc func, void *userdata); - - -const char *sca_state_name_get(Object *ob, short bit); - -#endif - diff --git a/source/blender/blenkernel/BKE_scene.h b/source/blender/blenkernel/BKE_scene.h index 8c7c3fb15de..afb77bb5206 100644 --- a/source/blender/blenkernel/BKE_scene.h +++ b/source/blender/blenkernel/BKE_scene.h @@ -159,7 +159,6 @@ bool BKE_scene_use_world_space_shading(struct Scene *scene); bool BKE_scene_use_spherical_stereo(struct Scene *scene); bool BKE_scene_uses_blender_internal(const struct Scene *scene); -bool BKE_scene_uses_blender_game(const struct Scene *scene); bool BKE_scene_uses_blender_eevee(const struct Scene *scene); void BKE_scene_disable_color_management(struct Scene *scene); @@ -182,7 +181,6 @@ bool BKE_viewrender_use_shading_nodes_custom(const struct ViewRender *view_rende bool BKE_viewrender_use_world_space_shading(const struct ViewRender *view_render); bool BKE_viewrender_use_spherical_stereo(const struct ViewRender *view_render); bool BKE_viewrender_uses_blender_internal(const struct ViewRender *view_render); -bool BKE_viewrender_uses_blender_game(const struct ViewRender *view_render); bool BKE_viewrender_uses_blender_eevee(const struct ViewRender *view_render); /**********************************/ diff --git a/source/blender/blenkernel/CMakeLists.txt b/source/blender/blenkernel/CMakeLists.txt index 27c1eeb3d77..6d8419208e8 100644 --- a/source/blender/blenkernel/CMakeLists.txt +++ b/source/blender/blenkernel/CMakeLists.txt @@ -83,7 +83,6 @@ set(SRC intern/boids.c intern/bpath.c intern/brush.c - intern/bullet.c intern/bvhutils.c intern/cachefile.c intern/camera.c @@ -166,13 +165,11 @@ set(SRC intern/pbvh.c intern/pbvh_bmesh.c intern/pointcache.c - intern/property.c intern/layer.c intern/layer_utils.c intern/lightprobe.c intern/report.c intern/rigidbody.c - intern/sca.c intern/scene.c intern/screen.c intern/seqcache.c @@ -222,7 +219,6 @@ set(SRC BKE_boids.h BKE_bpath.h BKE_brush.h - BKE_bullet.h BKE_bvhutils.h BKE_cachefile.h BKE_camera.h @@ -293,12 +289,10 @@ set(SRC BKE_particle.h BKE_pbvh.h BKE_pointcache.h - BKE_property.h BKE_layer.h BKE_lightprobe.h BKE_report.h BKE_rigidbody.h - BKE_sca.h BKE_scene.h BKE_screen.h BKE_sequencer.h @@ -490,18 +484,6 @@ if(WITH_LZMA) add_definitions(-DWITH_LZMA) endif() -if(WITH_GAMEENGINE) - list(APPEND INC_SYS - ../../../extern/recastnavigation - ) - list(APPEND SRC - intern/navmesh_conversion.c - BKE_navmesh_conversion.h - ) - - add_definitions(-DWITH_GAMEENGINE) -endif() - if(WITH_LIBMV) add_definitions(-DWITH_LIBMV) endif() diff --git a/source/blender/blenkernel/intern/DerivedMesh.c b/source/blender/blenkernel/intern/DerivedMesh.c index 879c4900146..bcdcdaa30cc 100644 --- a/source/blender/blenkernel/intern/DerivedMesh.c +++ b/source/blender/blenkernel/intern/DerivedMesh.c @@ -70,11 +70,6 @@ #include "BKE_deform.h" #include "BKE_global.h" /* For debug flag, DM_update_tessface_data() func. */ -#ifdef WITH_GAMEENGINE -#include "BKE_navmesh_conversion.h" -static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm); -#endif - #include "BLI_sys_types.h" /* for intptr_t support */ #include "GPU_buffers.h" @@ -1746,13 +1741,6 @@ static void dm_ensure_display_normals(DerivedMesh *dm) } } -/** - * new value for useDeform -1 (hack for the gameengine): - * - * - apply only the modifier stack of the object, skipping the virtual modifiers, - * - don't apply the key - * - apply deform modifiers and input vertexco - */ static void mesh_calc_modifiers( struct Depsgraph *depsgraph, Scene *scene, Object *ob, float (*inputVertexCos)[3], const bool useRenderParams, int useDeform, @@ -1772,7 +1760,6 @@ static void mesh_calc_modifiers( int numVerts = me->totvert; const int required_mode = useRenderParams ? eModifierMode_Render : eModifierMode_Realtime; bool isPrevDeform = false; - const bool skipVirtualArmature = (useDeform < 0); MultiresModifierData *mmd = get_multires_modifier(scene, ob, 0); const bool has_multires = (mmd && mmd->sculptlvl != 0); bool multires_applied = false; @@ -1806,17 +1793,7 @@ static void mesh_calc_modifiers( if (useDeform) deform_app_flags |= MOD_APPLY_USECACHE; - if (!skipVirtualArmature) { - firstmd = modifiers_getVirtualModifierList(ob, &virtualModifierData); - } - else { - /* game engine exception */ - firstmd = ob->modifiers.first; - if (firstmd && firstmd->type == eModifierType_Armature) - firstmd = firstmd->next; - } - - md = firstmd; + md = firstmd = modifiers_getVirtualModifierList(ob, &virtualModifierData); modifiers_clearErrors(ob); @@ -2246,20 +2223,6 @@ static void mesh_calc_modifiers( CustomData_free_layers(&finaldm->loopData, CD_NORMAL, finaldm->numLoopData); } -#ifdef WITH_GAMEENGINE - /* NavMesh - this is a hack but saves having a NavMesh modifier */ - if ((ob->gameflag & OB_NAVMESH) && (finaldm->type == DM_TYPE_CDDM)) { - DerivedMesh *tdm; - tdm = navmesh_dm_createNavMeshForVisualization(finaldm); - if (finaldm != tdm) { - finaldm->release(finaldm); - finaldm = tdm; - } - - DM_ensure_tessface(finaldm); - } -#endif /* WITH_GAMEENGINE */ - *r_final = finaldm; if (orcodm) @@ -2854,32 +2817,6 @@ DerivedMesh *mesh_create_derived_no_deform( return final; } -DerivedMesh *mesh_create_derived_no_virtual( - struct Depsgraph *depsgraph, Scene *scene, Object *ob, - float (*vertCos)[3], CustomDataMask dataMask) -{ - DerivedMesh *final; - - mesh_calc_modifiers( - depsgraph, scene, ob, vertCos, false, -1, false, dataMask, -1, false, false, false, - NULL, &final); - - return final; -} - -DerivedMesh *mesh_create_derived_physics( - struct Depsgraph *depsgraph, Scene *scene, Object *ob, - float (*vertCos)[3], CustomDataMask dataMask) -{ - DerivedMesh *final; - - mesh_calc_modifiers( - depsgraph, scene, ob, vertCos, false, -1, true, dataMask, -1, false, false, false, - NULL, &final); - - return final; -} - DerivedMesh *mesh_create_derived_no_deform_render( struct Depsgraph *depsgraph, Scene *scene, Object *ob, float (*vertCos)[3], @@ -3520,178 +3457,6 @@ void DM_set_object_boundbox(Object *ob, DerivedMesh *dm) ob->bb->flag &= ~BOUNDBOX_DIRTY; } -/* --- NAVMESH (begin) --- */ -#ifdef WITH_GAMEENGINE - -/* BMESH_TODO, navmesh is not working right currently - * All tools set this as MPoly data, but derived mesh currently draws from MFace (tessface) - * - * Proposed solution, rather then copy CD_RECAST into the MFace array, - * use ORIGINDEX to get the original poly index and then get the CD_RECAST - * data from the original me->mpoly layer. - campbell - */ - - -BLI_INLINE int navmesh_bit(int a, int b) -{ - return (a & (1 << b)) >> b; -} - -BLI_INLINE void navmesh_intToCol(int i, float col[3]) -{ - int r = navmesh_bit(i, 0) + navmesh_bit(i, 3) * 2 + 1; - int g = navmesh_bit(i, 1) + navmesh_bit(i, 4) * 2 + 1; - int b = navmesh_bit(i, 2) + navmesh_bit(i, 5) * 2 + 1; - col[0] = 1 - r * 63.0f / 255.0f; - col[1] = 1 - g * 63.0f / 255.0f; - col[2] = 1 - b * 63.0f / 255.0f; -} - -static void navmesh_drawColored(DerivedMesh *dm) -{ - MVert *mvert = (MVert *)CustomData_get_layer(&dm->vertData, CD_MVERT); - MFace *mface = (MFace *)CustomData_get_layer(&dm->faceData, CD_MFACE); - int *polygonIdx = (int *)CustomData_get_layer(&dm->polyData, CD_RECAST); - float col[3]; - - if (!polygonIdx) - return; - -#if 0 - //UI_ThemeColor(TH_WIRE); - glLineWidth(2.0); - dm->drawEdges(dm, 0, 1); -#endif - - Gwn_VertFormat *format = immVertexFormat(); - unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 3, GWN_FETCH_FLOAT); - unsigned int color = GWN_vertformat_attr_add(format, "color", GWN_COMP_F32, 3, GWN_FETCH_FLOAT); - - immBindBuiltinProgram(GPU_SHADER_3D_FLAT_COLOR); - - /* Note: batch drawing API would let us share vertices */ - immBeginAtMost(GWN_PRIM_TRIS, dm->numTessFaceData * 6); - for (int a = 0; a < dm->numTessFaceData; a++, mface++) { - int pi = polygonIdx[a]; - if (pi <= 0) { - zero_v3(col); - } - else { - navmesh_intToCol(pi, col); - } - - immSkipAttrib(color); - immVertex3fv(pos, mvert[mface->v1].co); - immSkipAttrib(color); - immVertex3fv(pos, mvert[mface->v2].co); - immAttrib3fv(color, col); - immVertex3fv(pos, mvert[mface->v3].co); - - if (mface->v4) { - /* this tess face is a quad, so draw the other triangle */ - immSkipAttrib(color); - immVertex3fv(pos, mvert[mface->v1].co); - immSkipAttrib(color); - immVertex3fv(pos, mvert[mface->v3].co); - immAttrib3fv(color, col); - immVertex3fv(pos, mvert[mface->v4].co); - } - } - immEnd(); - immUnbindProgram(); -} - -static void navmesh_DM_drawFacesSolid( - DerivedMesh *dm, - float (*partial_redraw_planes)[4], - bool UNUSED(fast), DMSetMaterial UNUSED(setMaterial)) -{ - UNUSED_VARS(partial_redraw_planes); - - //drawFacesSolid_original(dm, partial_redraw_planes, fast, setMaterial); - navmesh_drawColored(dm); -} - -static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm) -{ - DerivedMesh *result; - int maxFaces = dm->getNumPolys(dm); - int *recastData; - int vertsPerPoly = 0, nverts = 0, ndtris = 0, npolys = 0; - float *verts = NULL; - unsigned short *dtris = NULL, *dmeshes = NULL, *polys = NULL; - int *dtrisToPolysMap = NULL, *dtrisToTrisMap = NULL, *trisToFacesMap = NULL; - int res; - - result = CDDM_copy(dm); - if (!CustomData_has_layer(&result->polyData, CD_RECAST)) { - int *sourceRecastData = (int *)CustomData_get_layer(&dm->polyData, CD_RECAST); - if (sourceRecastData) { - CustomData_add_layer_named(&result->polyData, CD_RECAST, CD_DUPLICATE, - sourceRecastData, maxFaces, "recastData"); - } - } - recastData = (int *)CustomData_get_layer(&result->polyData, CD_RECAST); - - /* note: This is not good design! - really should not be doing this */ - result->drawFacesSolid = navmesh_DM_drawFacesSolid; - - - /* process mesh */ - res = buildNavMeshDataByDerivedMesh(dm, &vertsPerPoly, &nverts, &verts, &ndtris, &dtris, - &npolys, &dmeshes, &polys, &dtrisToPolysMap, &dtrisToTrisMap, - &trisToFacesMap); - if (res) { - size_t polyIdx; - - /* invalidate concave polygon */ - for (polyIdx = 0; polyIdx < (size_t)npolys; polyIdx++) { - unsigned short *poly = &polys[polyIdx * 2 * vertsPerPoly]; - if (!polyIsConvex(poly, vertsPerPoly, verts)) { - /* set negative polygon idx to all faces */ - unsigned short *dmesh = &dmeshes[4 * polyIdx]; - unsigned short tbase = dmesh[2]; - unsigned short tnum = dmesh[3]; - unsigned short ti; - - for (ti = 0; ti < tnum; ti++) { - unsigned short triidx = dtrisToTrisMap[tbase + ti]; - unsigned short faceidx = trisToFacesMap[triidx]; - if (recastData[faceidx] > 0) { - recastData[faceidx] = -recastData[faceidx]; - } - } - } - } - } - else { - printf("Navmesh: Unable to generate valid Navmesh"); - } - - /* clean up */ - if (verts != NULL) - MEM_freeN(verts); - if (dtris != NULL) - MEM_freeN(dtris); - if (dmeshes != NULL) - MEM_freeN(dmeshes); - if (polys != NULL) - MEM_freeN(polys); - if (dtrisToPolysMap != NULL) - MEM_freeN(dtrisToPolysMap); - if (dtrisToTrisMap != NULL) - MEM_freeN(dtrisToTrisMap); - if (trisToFacesMap != NULL) - MEM_freeN(trisToFacesMap); - - return result; -} - -#endif /* WITH_GAMEENGINE */ - -/* --- NAVMESH (end) --- */ - - void DM_init_origspace(DerivedMesh *dm) { const float default_osf[4][2] = {{0, 0}, {1, 0}, {1, 1}, {0, 1}}; diff --git a/source/blender/blenkernel/intern/action.c b/source/blender/blenkernel/intern/action.c index e47c87c995b..7cceec2c08f 100644 --- a/source/blender/blenkernel/intern/action.c +++ b/source/blender/blenkernel/intern/action.c @@ -855,39 +855,6 @@ void BKE_pose_free(bPose *pose) BKE_pose_free_ex(pose, true); } -static void copy_pose_channel_data(bPoseChannel *pchan, const bPoseChannel *chan) -{ - bConstraint *pcon, *con; - - copy_v3_v3(pchan->loc, chan->loc); - copy_v3_v3(pchan->size, chan->size); - copy_v3_v3(pchan->eul, chan->eul); - copy_v3_v3(pchan->rotAxis, chan->rotAxis); - pchan->rotAngle = chan->rotAngle; - copy_qt_qt(pchan->quat, chan->quat); - pchan->rotmode = chan->rotmode; - copy_m4_m4(pchan->chan_mat, (float(*)[4])chan->chan_mat); - copy_m4_m4(pchan->pose_mat, (float(*)[4])chan->pose_mat); - pchan->flag = chan->flag; - - pchan->roll1 = chan->roll1; - pchan->roll2 = chan->roll2; - pchan->curveInX = chan->curveInX; - pchan->curveInY = chan->curveInY; - pchan->curveOutX = chan->curveOutX; - pchan->curveOutY = chan->curveOutY; - pchan->ease1 = chan->ease1; - pchan->ease2 = chan->ease2; - pchan->scaleIn = chan->scaleIn; - pchan->scaleOut = chan->scaleOut; - - con = chan->constraints.first; - for (pcon = pchan->constraints.first; pcon && con; pcon = pcon->next, con = con->next) { - pcon->enforce = con->enforce; - pcon->headtail = con->headtail; - } -} - /** * Copy the internal members of each pose channel including constraints * and ID-Props, used when duplicating bones in editmode. @@ -1329,25 +1296,6 @@ short action_get_item_transforms(bAction *act, Object *ob, bPoseChannel *pchan, /* ************** Pose Management Tools ****************** */ -/* Copy the data from the action-pose (src) into the pose */ -/* both args are assumed to be valid */ -/* exported to game engine */ -/* Note! this assumes both poses are aligned, this isn't always true when dealing with user poses */ -void extract_pose_from_pose(bPose *pose, const bPose *src) -{ - const bPoseChannel *schan; - bPoseChannel *pchan = pose->chanbase.first; - - if (pose == src) { - printf("extract_pose_from_pose source and target are the same\n"); - return; - } - - for (schan = src->chanbase.first; (schan && pchan); schan = schan->next, pchan = pchan->next) { - copy_pose_channel_data(pchan, schan); - } -} - /* for do_all_pose_actions, clears the pose. Now also exported for proxy and tools */ void BKE_pose_rest(bPose *pose) { diff --git a/source/blender/blenkernel/intern/blendfile.c b/source/blender/blenkernel/intern/blendfile.c index 8d61b6723c6..74e6c996329 100644 --- a/source/blender/blenkernel/intern/blendfile.c +++ b/source/blender/blenkernel/intern/blendfile.c @@ -578,7 +578,7 @@ WorkspaceConfigFileData *BKE_blendfile_workspace_config_read(const char *filepat bool BKE_blendfile_workspace_config_write(Main *bmain, const char *filepath, ReportList *reports) { - int fileflags = G.fileflags & ~(G_FILE_NO_UI | G_FILE_AUTOPLAY | G_FILE_HISTORY); + int fileflags = G.fileflags & ~(G_FILE_NO_UI | G_FILE_HISTORY); bool retval = false; BKE_blendfile_write_partial_begin(bmain); diff --git a/source/blender/blenkernel/intern/bullet.c b/source/blender/blenkernel/intern/bullet.c deleted file mode 100644 index c16c0f7af31..00000000000 --- a/source/blender/blenkernel/intern/bullet.c +++ /dev/null @@ -1,99 +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 blender/blenkernel/intern/bullet.c - * \ingroup bke - */ - - -#include "MEM_guardedalloc.h" - -/* types */ -#include "DNA_object_force_types.h" /* here is the softbody struct */ - -#include "BKE_bullet.h" - - -/* ************ Object level, exported functions *************** */ - -/* allocates and initializes general main data */ -BulletSoftBody *bsbNew(void) -{ - BulletSoftBody *bsb; - - bsb = MEM_callocN(sizeof(BulletSoftBody), "bulletsoftbody"); - - bsb->flag = OB_BSB_BENDING_CONSTRAINTS | OB_BSB_SHAPE_MATCHING | OB_BSB_AERO_VPOINT; - bsb->linStiff = 0.5f; - bsb->angStiff = 1.0f; - bsb->volume = 1.0f; - - - bsb->viterations = 0; - bsb->piterations = 2; - bsb->diterations = 0; - bsb->citerations = 4; - - bsb->kSRHR_CL = 0.1f; - bsb->kSKHR_CL = 1.f; - bsb->kSSHR_CL = 0.5f; - bsb->kSR_SPLT_CL = 0.5f; - - bsb->kSK_SPLT_CL = 0.5f; - bsb->kSS_SPLT_CL = 0.5f; - bsb->kVCF = 1; - bsb->kDP = 0; - - bsb->kDG = 0; - bsb->kLF = 0; - bsb->kPR = 0; - bsb->kVC = 0; - - bsb->kDF = 0.2f; - bsb->kMT = 0.05; - bsb->kCHR = 1.0f; - bsb->kKHR = 0.1f; - - bsb->kSHR = 1.0f; - bsb->kAHR = 0.7f; - - bsb->collisionflags = 0; - //bsb->collisionflags = OB_BSB_COL_CL_RS + OB_BSB_COL_CL_SS; - bsb->numclusteriterations = 64; - bsb->welding = 0.f; - - return bsb; -} - -/* frees all */ -void bsbFree(BulletSoftBody *bsb) -{ - /* no internal data yet */ - MEM_freeN(bsb); -} - - diff --git a/source/blender/blenkernel/intern/constraint.c b/source/blender/blenkernel/intern/constraint.c index eca789b0f87..b58028b4a5d 100644 --- a/source/blender/blenkernel/intern/constraint.c +++ b/source/blender/blenkernel/intern/constraint.c @@ -3028,66 +3028,6 @@ static bConstraintTypeInfo CTI_MINMAX = { minmax_evaluate /* evaluate */ }; -/* ------- RigidBody Joint ---------- */ - -static void rbj_new_data(void *cdata) -{ - bRigidBodyJointConstraint *data = (bRigidBodyJointConstraint *)cdata; - - /* removed code which set target of this constraint */ - data->type = 1; -} - -static void rbj_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) -{ - bRigidBodyJointConstraint *data = con->data; - - /* target only */ - func(con, (ID **)&data->tar, false, userdata); - func(con, (ID **)&data->child, false, userdata); -} - -static int rbj_get_tars(bConstraint *con, ListBase *list) -{ - if (con && list) { - bRigidBodyJointConstraint *data = con->data; - bConstraintTarget *ct; - - /* standard target-getting macro for single-target constraints without subtargets */ - SINGLETARGETNS_GET_TARS(con, data->tar, ct, list); - - return 1; - } - - return 0; -} - -static void rbj_flush_tars(bConstraint *con, ListBase *list, bool no_copy) -{ - if (con && list) { - bRigidBodyJointConstraint *data = con->data; - bConstraintTarget *ct = list->first; - - /* the following macro is used for all standard single-target constraints */ - SINGLETARGETNS_FLUSH_TARS(con, data->tar, ct, list, no_copy); - } -} - -static bConstraintTypeInfo CTI_RIGIDBODYJOINT = { - CONSTRAINT_TYPE_RIGIDBODYJOINT, /* type */ - sizeof(bRigidBodyJointConstraint), /* size */ - "Rigid Body Joint", /* name */ - "bRigidBodyJointConstraint", /* struct name */ - NULL, /* free data */ - rbj_id_looper, /* id looper */ - NULL, /* copy data */ - rbj_new_data, /* new data */ - rbj_get_tars, /* get constraint targets */ - rbj_flush_tars, /* flush constraint targets */ - default_get_tarmat, /* get target matrix */ - NULL /* evaluate - this is not solved here... is just an interface for game-engine */ -}; - /* -------- Clamp To ---------- */ static void clampto_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) @@ -4438,7 +4378,7 @@ static void constraints_init_typeinfo(void) constraintsTypeInfo[14] = &CTI_DISTLIMIT; /* Limit Distance Constraint */ constraintsTypeInfo[15] = &CTI_STRETCHTO; /* StretchTo Constaint */ constraintsTypeInfo[16] = &CTI_MINMAX; /* Floor Constraint */ - constraintsTypeInfo[17] = &CTI_RIGIDBODYJOINT; /* RigidBody Constraint */ + /* constraintsTypeInfo[17] = &CTI_RIGIDBODYJOINT; */ /* RigidBody Constraint - Deprecated */ constraintsTypeInfo[18] = &CTI_CLAMPTO; /* ClampTo Constraint */ constraintsTypeInfo[19] = &CTI_TRANSFORM; /* Transformation Constraint */ constraintsTypeInfo[20] = &CTI_SHRINKWRAP; /* Shrinkwrap Constraint */ diff --git a/source/blender/blenkernel/intern/context.c b/source/blender/blenkernel/intern/context.c index 2bb12725940..351e43706dd 100644 --- a/source/blender/blenkernel/intern/context.c +++ b/source/blender/blenkernel/intern/context.c @@ -791,14 +791,6 @@ struct SpaceNode *CTX_wm_space_node(const bContext *C) return NULL; } -struct SpaceLogic *CTX_wm_space_logic(const bContext *C) -{ - ScrArea *sa = CTX_wm_area(C); - if (sa && sa->spacetype == SPACE_LOGIC) - return sa->spacedata.first; - return NULL; -} - struct SpaceIpo *CTX_wm_space_graph(const bContext *C) { ScrArea *sa = CTX_wm_area(C); diff --git a/source/blender/blenkernel/intern/ipo.c b/source/blender/blenkernel/intern/ipo.c index fcbc25ebad5..c2e9af685a6 100644 --- a/source/blender/blenkernel/intern/ipo.c +++ b/source/blender/blenkernel/intern/ipo.c @@ -46,7 +46,6 @@ /* since we have versioning code here */ #define DNA_DEPRECATED_ALLOW -#include "DNA_actuator_types.h" #include "DNA_anim_types.h" #include "DNA_constraint_types.h" #include "DNA_camera_types.h" @@ -1768,23 +1767,6 @@ void do_versions_ipos_to_animato(Main *main) ipo_to_animdata(id, ob->ipo, NULL, NULL, NULL); id_us_min(&ob->ipo->id); ob->ipo = NULL; - - { - /* If we have any empty action actuators, assume they were - * converted IPO Actuators using the object IPO */ - bActuator *act; - bActionActuator *aa; - - for (act = ob->actuators.first; act; act = act->next) { - /* Any actuators set to ACT_IPO at this point are actually Action Actuators that - * need this converted IPO to finish converting the actuator. */ - if (act->type == ACT_IPO) { - aa = (bActionActuator *)act->data; - aa->act = ob->adt->action; - act->type = ACT_ACTION; - } - } - } } } diff --git a/source/blender/blenkernel/intern/library_query.c b/source/blender/blenkernel/intern/library_query.c index bed2244702f..28e2201ccfa 100644 --- a/source/blender/blenkernel/intern/library_query.c +++ b/source/blender/blenkernel/intern/library_query.c @@ -31,13 +31,11 @@ #include "MEM_guardedalloc.h" -#include "DNA_actuator_types.h" #include "DNA_anim_types.h" #include "DNA_armature_types.h" #include "DNA_brush_types.h" #include "DNA_camera_types.h" #include "DNA_constraint_types.h" -#include "DNA_controller_types.h" #include "DNA_group_types.h" #include "DNA_gpencil_types.h" #include "DNA_key_types.h" @@ -55,7 +53,6 @@ #include "DNA_lightprobe_types.h" #include "DNA_rigidbody_types.h" #include "DNA_scene_types.h" -#include "DNA_sensor_types.h" #include "DNA_sequence_types.h" #include "DNA_screen_types.h" #include "DNA_speaker_types.h" @@ -84,7 +81,6 @@ #include "BKE_node.h" #include "BKE_particle.h" #include "BKE_rigidbody.h" -#include "BKE_sca.h" #include "BKE_sequencer.h" #include "BKE_tracking.h" #include "BKE_workspace.h" @@ -219,33 +215,6 @@ static void library_foreach_particlesystemsObjectLooper( FOREACH_FINALIZE_VOID; } -static void library_foreach_sensorsObjectLooper( - bSensor *UNUSED(sensor), ID **id_pointer, void *user_data, int cb_flag) -{ - LibraryForeachIDData *data = (LibraryForeachIDData *) user_data; - FOREACH_CALLBACK_INVOKE_ID_PP(data, id_pointer, cb_flag); - - FOREACH_FINALIZE_VOID; -} - -static void library_foreach_controllersObjectLooper( - bController *UNUSED(controller), ID **id_pointer, void *user_data, int cb_flag) -{ - LibraryForeachIDData *data = (LibraryForeachIDData *) user_data; - FOREACH_CALLBACK_INVOKE_ID_PP(data, id_pointer, cb_flag); - - FOREACH_FINALIZE_VOID; -} - -static void library_foreach_actuatorsObjectLooper( - bActuator *UNUSED(actuator), ID **id_pointer, void *user_data, int cb_flag) -{ - LibraryForeachIDData *data = (LibraryForeachIDData *) user_data; - FOREACH_CALLBACK_INVOKE_ID_PP(data, id_pointer, cb_flag); - - FOREACH_FINALIZE_VOID; -} - static void library_foreach_nla_strip(LibraryForeachIDData *data, NlaStrip *strip) { NlaStrip *substrip; @@ -506,8 +475,6 @@ void BKE_library_foreach_ID_link(Main *bmain, ID *id, LibraryIDLinkCallback call BKE_rigidbody_world_id_loop(scene->rigidbody_world, library_foreach_rigidbodyworldSceneLooper, &data); } - CALLBACK_INVOKE(scene->gm.dome.warptext, IDWALK_CB_NOP); - break; } @@ -605,10 +572,6 @@ void BKE_library_foreach_ID_link(Main *bmain, ID *id, LibraryIDLinkCallback call CALLBACK_INVOKE(object->soft->effector_weights->group, IDWALK_CB_NOP); } } - - BKE_sca_sensors_id_loop(&object->sensors, library_foreach_sensorsObjectLooper, &data); - BKE_sca_controllers_id_loop(&object->controllers, library_foreach_controllersObjectLooper, &data); - BKE_sca_actuators_id_loop(&object->actuators, library_foreach_actuatorsObjectLooper, &data); break; } @@ -1084,7 +1047,7 @@ bool BKE_library_id_can_use_idtype(ID *id_owner, const short id_type_used) #if 0 return ELEM(id_type_used, ID_ME, ID_CU, ID_MB, ID_LT, ID_SPK, ID_AR, ID_LA, ID_CA, /* obdata */ ID_OB, ID_MA, ID_GD, ID_GR, ID_TE, ID_PA, ID_TXT, ID_SO, ID_MC, ID_IM, ID_AC - /* + constraints, modifiers and game logic ID types... */); + /* + constraints and modifiers ... */); #else return true; #endif diff --git a/source/blender/blenkernel/intern/library_remap.c b/source/blender/blenkernel/intern/library_remap.c index 483500cf67d..f6e03fec380 100644 --- a/source/blender/blenkernel/intern/library_remap.c +++ b/source/blender/blenkernel/intern/library_remap.c @@ -104,7 +104,6 @@ #include "BKE_paint.h" #include "BKE_particle.h" #include "BKE_lightprobe.h" -#include "BKE_sca.h" #include "BKE_speaker.h" #include "BKE_sound.h" #include "BKE_screen.h" @@ -506,10 +505,6 @@ ATTR_NONNULL(1) static void libblock_remap_data( } } - if (old_id && GS(old_id->name) == ID_OB) { - BKE_sca_logic_links_remap(bmain, (Object *)old_id, (Object *)new_id); - } - /* XXX We may not want to always 'transfer' fakeuser from old to new id... Think for now it's desired behavior * though, we can always add an option (flag) to control this later if needed. */ if (old_id && (old_id->flag & LIB_FAKEUSER)) { diff --git a/source/blender/blenkernel/intern/material.c b/source/blender/blenkernel/intern/material.c index f80f726607b..fee91865d35 100644 --- a/source/blender/blenkernel/intern/material.c +++ b/source/blender/blenkernel/intern/material.c @@ -200,11 +200,7 @@ void BKE_material_init(Material *ma) ma->vol.ms_spread = 0.2f; ma->vol.ms_diff = 1.f; ma->vol.ms_intensity = 1.f; - - ma->game.flag = GEMAT_BACKCULL; - ma->game.alpha_blend = 0; - ma->game.face_orientation = 0; - + ma->mode = MA_TRACEBLE | MA_SHADBUF | MA_SHADOW | MA_RAYBIAS | MA_TANGENT_STR | MA_ZTRANSP; ma->mode2 = MA_CASTSHADOW; ma->shade_flag = MA_APPROX_OCCLUSION; @@ -1285,7 +1281,7 @@ void BKE_texpaint_slot_refresh_cache(Scene *scene, Material *ma) short index = 0, i; bool use_nodes = BKE_scene_use_new_shading_nodes(scene); - bool is_bi = BKE_scene_uses_blender_internal(scene) || BKE_scene_uses_blender_game(scene); + bool is_bi = BKE_scene_uses_blender_internal(scene); /* XXX, for 2.8 testing & development its useful to have non Cycles/BI engines use material nodes * In the future we may have some way to check this which each engine can define. diff --git a/source/blender/blenkernel/intern/navmesh_conversion.c b/source/blender/blenkernel/intern/navmesh_conversion.c deleted file mode 100644 index 35bcca52f63..00000000000 --- a/source/blender/blenkernel/intern/navmesh_conversion.c +++ /dev/null @@ -1,502 +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 blender/blenkernel/intern/navmesh_conversion.c - * \ingroup bke - */ - -#include -#include - -#include "MEM_guardedalloc.h" - -#include "DNA_meshdata_types.h" - -#include "BLI_utildefines.h" -#include "BLI_math.h" -#include "BLI_sort.h" - -#include "BKE_navmesh_conversion.h" -#include "BKE_cdderivedmesh.h" - -#include "recast-capi.h" - -BLI_INLINE float area2(const float *a, const float *b, const float *c) -{ - return (b[0] - a[0]) * (c[2] - a[2]) - (c[0] - a[0]) * (b[2] - a[2]); -} - -BLI_INLINE int left(const float *a, const float *b, const float *c) -{ - return area2(a, b, c) < 0; -} - -int polyNumVerts(const unsigned short *p, const int vertsPerPoly) -{ - int i, nv = 0; - for (i = 0; i < vertsPerPoly; i++) { - if (p[i] == 0xffff) - break; - nv++; - } - return nv; -} - -int polyIsConvex(const unsigned short *p, const int vertsPerPoly, const float *verts) -{ - int j, nv = polyNumVerts(p, vertsPerPoly); - if (nv < 3) - return 0; - for (j = 0; j < nv; j++) { - const float *v = &verts[3 * p[j]]; - const float *v_next = &verts[3 * p[(j + 1) % nv]]; - const float *v_prev = &verts[3 * p[(nv + j - 1) % nv]]; - if (!left(v_prev, v, v_next)) - return 0; - - } - return 1; -} - -/* XXX, could replace with #dist_to_line_segment_v3(), or add a squared version */ -float distPointToSegmentSq(const float point[3], const float a[3], const float b[3]) -{ - float abx[3], dx[3]; - float d, t; - - sub_v3_v3v3(abx, b, a); - sub_v3_v3v3(dx, point, a); - - d = abx[0] * abx[0] + abx[2] * abx[2]; - t = abx[0] * dx[0] + abx[2] * dx[2]; - - if (d > 0.0f) - t /= d; - if (t < 0.0f) - t = 0.0f; - else if (t > 1.0f) - t = 1.0f; - dx[0] = a[0] + t * abx[0] - point[0]; - dx[2] = a[2] + t * abx[2] - point[2]; - - return dx[0] * dx[0] + dx[2] * dx[2]; -} - -int buildRawVertIndicesData(DerivedMesh *dm, int *nverts_r, float **verts_r, - int *ntris_r, unsigned short **tris_r, int **trisToFacesMap_r, - int **recastData) -{ - int vi, fi, triIdx; - int nverts, ntris; - int *trisToFacesMap; - float *verts; - unsigned short *tris, *tri; - int nfaces; - MFace *faces; - - nverts = dm->getNumVerts(dm); - if (nverts >= 0xffff) { - printf("Converting navmesh: Error! Too many vertices. Max number of vertices %d\n", 0xffff); - return 0; - } - if (nverts == 0) { - printf("Converting navmesh: Error! There are no vertices!\n"); - return 0; - } - - verts = MEM_mallocN(sizeof(float[3]) * nverts, "buildRawVertIndicesData verts"); - dm->getVertCos(dm, (float(*)[3])verts); - - /* flip coordinates */ - for (vi = 0; vi < nverts; vi++) { - SWAP(float, verts[3 * vi + 1], verts[3 * vi + 2]); - } - - /* calculate number of tris */ - dm->recalcTessellation(dm); - nfaces = dm->getNumTessFaces(dm); - if (nfaces == 0) { - printf("Converting navmesh: Error! There are %i vertices, but no faces!\n", nverts); - return 0; - } - - faces = dm->getTessFaceArray(dm); - ntris = nfaces; - for (fi = 0; fi < nfaces; fi++) { - MFace *face = &faces[fi]; - if (face->v4) - ntris++; - } - - /* copy and transform to triangles (reorder on the run) */ - trisToFacesMap = MEM_callocN(sizeof(int) * ntris, "buildRawVertIndicesData trisToFacesMap"); - tris = MEM_callocN(sizeof(unsigned short) * 3 * ntris, "buildRawVertIndicesData tris"); - tri = tris; - triIdx = 0; - for (fi = 0; fi < nfaces; fi++) { - MFace *face = &faces[fi]; - tri[3 * triIdx + 0] = (unsigned short) face->v1; - tri[3 * triIdx + 1] = (unsigned short) face->v3; - tri[3 * triIdx + 2] = (unsigned short) face->v2; - trisToFacesMap[triIdx++] = fi; - if (face->v4) { - tri[3 * triIdx + 0] = (unsigned short) face->v1; - tri[3 * triIdx + 1] = (unsigned short) face->v4; - tri[3 * triIdx + 2] = (unsigned short) face->v3; - trisToFacesMap[triIdx++] = fi; - } - } - - /* carefully, recast data is just reference to data in derived mesh */ - *recastData = (int *)CustomData_get_layer(&dm->polyData, CD_RECAST); - - *nverts_r = nverts; - *verts_r = verts; - *ntris_r = ntris; - *tris_r = tris; - *trisToFacesMap_r = trisToFacesMap; - - return 1; -} - -int buildPolygonsByDetailedMeshes(const int vertsPerPoly, const int npolys, - unsigned short *polys, const unsigned short *dmeshes, - const float *verts, const unsigned short *dtris, - const int *dtrisToPolysMap) -{ - int polyidx; - int capacity = vertsPerPoly; - unsigned short *newPoly = MEM_callocN(sizeof(unsigned short) * capacity, "buildPolygonsByDetailedMeshes newPoly"); - memset(newPoly, 0xff, sizeof(unsigned short) * capacity); - - for (polyidx = 0; polyidx < npolys; polyidx++) { - size_t i; - int j, k; - int nv = 0; - /* search border */ - int tri, btri = -1; - int edge, bedge = -1; - int dtrisNum = dmeshes[polyidx * 4 + 3]; - int dtrisBase = dmeshes[polyidx * 4 + 2]; - unsigned char *traversedTris = MEM_callocN(sizeof(unsigned char) * dtrisNum, "buildPolygonsByDetailedMeshes traversedTris"); - unsigned short *adjustedPoly; - int adjustedNv; - int allBorderTraversed; - - for (j = 0; j < dtrisNum && btri == -1; j++) { - int curpolytri = dtrisBase + j; - for (k = 0; k < 3; k++) { - unsigned short neighbortri = dtris[curpolytri * 3 * 2 + 3 + k]; - if (neighbortri == 0xffff || dtrisToPolysMap[neighbortri] != polyidx + 1) { - btri = curpolytri; - bedge = k; - break; - } - } - } - if (btri == -1 || bedge == -1) { - /* can't find triangle with border edge */ - MEM_freeN(traversedTris); - MEM_freeN(newPoly); - - return 0; - } - - newPoly[nv++] = dtris[btri * 3 * 2 + bedge]; - tri = btri; - edge = (bedge + 1) % 3; - traversedTris[tri - dtrisBase] = 1; - while (tri != btri || edge != bedge) { - int neighbortri = dtris[tri * 3 * 2 + 3 + edge]; - if (neighbortri == 0xffff || dtrisToPolysMap[neighbortri] != polyidx + 1) { - if (nv == capacity) { - unsigned short *newPolyBig; - capacity += vertsPerPoly; - newPolyBig = MEM_callocN(sizeof(unsigned short) * capacity, "buildPolygonsByDetailedMeshes newPolyBig"); - memset(newPolyBig, 0xff, sizeof(unsigned short) * capacity); - memcpy(newPolyBig, newPoly, sizeof(unsigned short) * nv); - MEM_freeN(newPoly); - newPoly = newPolyBig; - } - newPoly[nv++] = dtris[tri * 3 * 2 + edge]; - /* move to next edge */ - edge = (edge + 1) % 3; - } - else { - /* move to next tri */ - int twinedge = -1; - for (k = 0; k < 3; k++) { - if (dtris[neighbortri * 3 * 2 + 3 + k] == tri) { - twinedge = k; - break; - } - } - if (twinedge == -1) { - printf("Converting navmesh: Error! Can't find neighbor edge - invalid adjacency info\n"); - MEM_freeN(traversedTris); - goto returnLabel; - } - tri = neighbortri; - edge = (twinedge + 1) % 3; - traversedTris[tri - dtrisBase] = 1; - } - } - - adjustedPoly = MEM_callocN(sizeof(unsigned short) * nv, "buildPolygonsByDetailedMeshes adjustedPoly"); - adjustedNv = 0; - for (i = 0; i < nv; i++) { - unsigned short prev = newPoly[(nv + i - 1) % nv]; - unsigned short cur = newPoly[i]; - unsigned short next = newPoly[(i + 1) % nv]; - float distSq = distPointToSegmentSq(&verts[3 * cur], &verts[3 * prev], &verts[3 * next]); - static const float tolerance = 0.001f; - if (distSq > tolerance) - adjustedPoly[adjustedNv++] = cur; - } - memcpy(newPoly, adjustedPoly, adjustedNv * sizeof(unsigned short)); - MEM_freeN(adjustedPoly); - nv = adjustedNv; - - allBorderTraversed = 1; - for (i = 0; i < dtrisNum; i++) { - if (traversedTris[i] == 0) { - /* check whether it has border edges */ - int curpolytri = dtrisBase + i; - for (k = 0; k < 3; k++) { - unsigned short neighbortri = dtris[curpolytri * 3 * 2 + 3 + k]; - if (neighbortri == 0xffff || dtrisToPolysMap[neighbortri] != polyidx + 1) { - allBorderTraversed = 0; - break; - } - } - } - } - - if (nv <= vertsPerPoly && allBorderTraversed) { - for (i = 0; i < nv; i++) { - polys[polyidx * vertsPerPoly * 2 + i] = newPoly[i]; - } - } - - MEM_freeN(traversedTris); - } - -returnLabel: - MEM_freeN(newPoly); - - return 1; -} - -struct SortContext { - const int *recastData; - const int *trisToFacesMap; -}; - -static int compareByData(const void *a, const void *b, void *ctx) -{ - return (((struct SortContext *)ctx)->recastData[((struct SortContext *)ctx)->trisToFacesMap[*(int *)a]] - - ((struct SortContext *)ctx)->recastData[((struct SortContext *)ctx)->trisToFacesMap[*(int *)b]]); -} - -int buildNavMeshData(const int nverts, const float *verts, - const int ntris, const unsigned short *tris, - const int *recastData, const int *trisToFacesMap, - int *ndtris_r, unsigned short **dtris_r, - int *npolys_r, unsigned short **dmeshes_r, unsigned short **polys_r, - int *vertsPerPoly_r, int **dtrisToPolysMap_r, int **dtrisToTrisMap_r) - -{ - int *trisMapping; - int i; - struct SortContext context; - int validTriStart, prevPolyIdx, curPolyIdx, newPolyIdx, prevpolyidx; - unsigned short *dmesh; - - int ndtris, npolys, vertsPerPoly; - unsigned short *dtris, *dmeshes, *polys; - int *dtrisToPolysMap, *dtrisToTrisMap; - - if (!recastData) { - printf("Converting navmesh: Error! Can't find recast custom data\n"); - return 0; - } - - trisMapping = MEM_callocN(sizeof(int) * ntris, "buildNavMeshData trisMapping"); - - /* sort the triangles by polygon idx */ - for (i = 0; i < ntris; i++) - trisMapping[i] = i; - context.recastData = recastData; - context.trisToFacesMap = trisToFacesMap; - BLI_qsort_r(trisMapping, ntris, sizeof(int), compareByData, &context); - - /* search first valid triangle - triangle of convex polygon */ - validTriStart = -1; - for (i = 0; i < ntris; i++) { - if (recastData[trisToFacesMap[trisMapping[i]]] > 0) { - validTriStart = i; - break; - } - } - - if (validTriStart < 0) { - printf("Converting navmesh: Error! No valid polygons in mesh\n"); - MEM_freeN(trisMapping); - return 0; - } - - ndtris = ntris - validTriStart; - /* fill dtris to faces mapping */ - dtrisToTrisMap = MEM_callocN(sizeof(int) * ndtris, "buildNavMeshData dtrisToTrisMap"); - memcpy(dtrisToTrisMap, &trisMapping[validTriStart], ndtris * sizeof(int)); - MEM_freeN(trisMapping); - - /* create detailed mesh triangles - copy only valid triangles - * and reserve memory for adjacency info */ - dtris = MEM_callocN(sizeof(unsigned short) * 3 * 2 * ndtris, "buildNavMeshData dtris"); - memset(dtris, 0xff, sizeof(unsigned short) * 3 * 2 * ndtris); - for (i = 0; i < ndtris; i++) { - memcpy(dtris + 3 * 2 * i, tris + 3 * dtrisToTrisMap[i], sizeof(unsigned short) * 3); - } - - /* create new recast data corresponded to dtris and renumber for continuous indices */ - prevPolyIdx = -1; - newPolyIdx = 0; - dtrisToPolysMap = MEM_callocN(sizeof(int) * ndtris, "buildNavMeshData dtrisToPolysMap"); - for (i = 0; i < ndtris; i++) { - curPolyIdx = recastData[trisToFacesMap[dtrisToTrisMap[i]]]; - if (curPolyIdx != prevPolyIdx) { - newPolyIdx++; - prevPolyIdx = curPolyIdx; - } - dtrisToPolysMap[i] = newPolyIdx; - } - - - /* build adjacency info for detailed mesh triangles */ - if (!recast_buildMeshAdjacency(dtris, ndtris, nverts, 3)) { - printf("Converting navmesh: Error! Unable to build mesh adjacency information\n"); - MEM_freeN(trisMapping); - MEM_freeN(dtrisToPolysMap); - return 0; - } - - /* create detailed mesh description for each navigation polygon */ - npolys = dtrisToPolysMap[ndtris - 1]; - dmeshes = MEM_callocN(sizeof(unsigned short) * npolys * 4, "buildNavMeshData dmeshes"); - memset(dmeshes, 0, npolys * 4 * sizeof(unsigned short)); - dmesh = NULL; - prevpolyidx = 0; - for (i = 0; i < ndtris; i++) { - int curpolyidx = dtrisToPolysMap[i]; - if (curpolyidx != prevpolyidx) { - if (curpolyidx != prevpolyidx + 1) { - printf("Converting navmesh: Error! Wrong order of detailed mesh faces\n"); - goto fail; - } - dmesh = dmesh == NULL ? dmeshes : dmesh + 4; - dmesh[2] = (unsigned short)i; /* tbase */ - dmesh[3] = 0; /* tnum */ - prevpolyidx = curpolyidx; - } - dmesh[3]++; - } - - /* create navigation polygons */ - vertsPerPoly = 6; - polys = MEM_callocN(sizeof(unsigned short) * npolys * vertsPerPoly * 2, "buildNavMeshData polys"); - memset(polys, 0xff, sizeof(unsigned short) * vertsPerPoly * 2 * npolys); - - if (!buildPolygonsByDetailedMeshes(vertsPerPoly, npolys, polys, dmeshes, verts, dtris, dtrisToPolysMap)) { - printf("Converting navmesh: Error! Unable to build polygons from detailed mesh\n"); - goto fail; - } - - *ndtris_r = ndtris; - *npolys_r = npolys; - *vertsPerPoly_r = vertsPerPoly; - *dtris_r = dtris; - *dmeshes_r = dmeshes; - *polys_r = polys; - *dtrisToPolysMap_r = dtrisToPolysMap; - *dtrisToTrisMap_r = dtrisToTrisMap; - - return 1; - -fail: - MEM_freeN(dmeshes); - MEM_freeN(dtrisToPolysMap); - MEM_freeN(dtrisToTrisMap); - return 0; -} - - -int buildNavMeshDataByDerivedMesh(DerivedMesh *dm, int *vertsPerPoly, - int *nverts, float **verts, - int *ndtris, unsigned short **dtris, - int *npolys, unsigned short **dmeshes, - unsigned short **polys, int **dtrisToPolysMap, - int **dtrisToTrisMap, int **trisToFacesMap) -{ - int res; - int ntris = 0, *recastData = NULL; - unsigned short *tris = NULL; - - res = buildRawVertIndicesData(dm, nverts, verts, &ntris, &tris, trisToFacesMap, &recastData); - if (!res) { - printf("Converting navmesh: Error! Can't get raw vertices and indices from mesh\n"); - goto exit; - } - - res = buildNavMeshData(*nverts, *verts, ntris, tris, recastData, *trisToFacesMap, - ndtris, dtris, npolys, dmeshes, polys, vertsPerPoly, - dtrisToPolysMap, dtrisToTrisMap); - if (!res) { - printf("Converting navmesh: Error! Can't build navmesh data from mesh\n"); - goto exit; - } - -exit: - if (tris) - MEM_freeN(tris); - - return res; -} - -int polyFindVertex(const unsigned short *p, const int vertsPerPoly, unsigned short vertexIdx) -{ - int i, res = -1; - for (i = 0; i < vertsPerPoly; i++) { - if (p[i] == 0xffff) - break; - if (p[i] == vertexIdx) { - res = i; - break; - } - } - return res; -} diff --git a/source/blender/blenkernel/intern/object.c b/source/blender/blenkernel/intern/object.c index 8b6ae075f9c..addf84224ac 100644 --- a/source/blender/blenkernel/intern/object.c +++ b/source/blender/blenkernel/intern/object.c @@ -59,7 +59,6 @@ #include "DNA_world_types.h" #include "DNA_object_types.h" #include "DNA_lightprobe_types.h" -#include "DNA_property_types.h" #include "DNA_rigidbody_types.h" #include "BLI_blenlib.h" @@ -77,7 +76,6 @@ #include "BKE_idprop.h" #include "BKE_armature.h" #include "BKE_action.h" -#include "BKE_bullet.h" #include "BKE_deform.h" #include "BKE_DerivedMesh.h" #include "BKE_animsys.h" @@ -109,9 +107,7 @@ #include "BKE_particle.h" #include "BKE_pointcache.h" #include "BKE_lightprobe.h" -#include "BKE_property.h" #include "BKE_rigidbody.h" -#include "BKE_sca.h" #include "BKE_scene.h" #include "BKE_sequencer.h" #include "BKE_speaker.h" @@ -176,14 +172,6 @@ void BKE_object_free_softbody(Object *ob) } } -void BKE_object_free_bulletsoftbody(Object *ob) -{ - if (ob->bsoft) { - bsbFree(ob->bsoft); - ob->bsoft = NULL; - } -} - void BKE_object_free_curve_cache(Object *ob) { if (ob->curve_cache) { @@ -436,11 +424,6 @@ void BKE_object_free(Object *ob) animviz_free_motionpath(ob->mpath); ob->mpath = NULL; } - BKE_bproperty_free_list(&ob->prop); - - free_sensors(&ob->sensors); - free_controllers(&ob->controllers); - free_actuators(&ob->actuators); BKE_constraints_free_ex(&ob->constraints, false); @@ -452,10 +435,6 @@ void BKE_object_free(Object *ob) sbFree(ob->soft); ob->soft = NULL; } - if (ob->bsoft) { - bsbFree(ob->bsoft); - ob->bsoft = NULL; - } GPU_lamp_free(ob); for (ObjectEngineData *oed = ob->drawdata.first; oed; oed = oed->next) { @@ -722,23 +701,6 @@ void BKE_object_init(Object *ob) ob->dupsta = 1; ob->dupend = 100; ob->dupfacesca = 1.0; - /* Game engine defaults*/ - ob->mass = ob->inertia = 1.0f; - ob->formfactor = 0.4f; - ob->damping = 0.04f; - ob->rdamping = 0.1f; - ob->anisotropicFriction[0] = 1.0f; - ob->anisotropicFriction[1] = 1.0f; - ob->anisotropicFriction[2] = 1.0f; - ob->gameflag = OB_PROP | OB_COLLISION; - ob->margin = 0.04f; - ob->init_state = 1; - ob->state = 1; - ob->obstacleRad = 1.0f; - ob->step_height = 0.15f; - ob->jump_speed = 10.0f; - ob->fall_speed = 55.0f; - ob->max_jumps = 1; ob->col_group = 0x01; ob->col_mask = 0xffff; ob->preview = NULL; @@ -834,139 +796,6 @@ Object *BKE_object_add_from( return ob; } -#ifdef WITH_GAMEENGINE - -void BKE_object_lod_add(Object *ob) -{ - LodLevel *lod = MEM_callocN(sizeof(LodLevel), "LoD Level"); - LodLevel *last = ob->lodlevels.last; - - /* If the lod list is empty, initialize it with the base lod level */ - if (!last) { - LodLevel *base = MEM_callocN(sizeof(LodLevel), "Base LoD Level"); - BLI_addtail(&ob->lodlevels, base); - base->flags = OB_LOD_USE_MESH | OB_LOD_USE_MAT; - base->source = ob; - base->obhysteresis = 10; - last = ob->currentlod = base; - } - - lod->distance = last->distance + 25.0f; - lod->obhysteresis = 10; - lod->flags = OB_LOD_USE_MESH | OB_LOD_USE_MAT; - - BLI_addtail(&ob->lodlevels, lod); -} - -static int lod_cmp(const void *a, const void *b) -{ - const LodLevel *loda = a; - const LodLevel *lodb = b; - - if (loda->distance < lodb->distance) return -1; - return loda->distance > lodb->distance; -} - -void BKE_object_lod_sort(Object *ob) -{ - BLI_listbase_sort(&ob->lodlevels, lod_cmp); -} - -bool BKE_object_lod_remove(Object *ob, int level) -{ - LodLevel *rem; - - if (level < 1 || level > BLI_listbase_count(&ob->lodlevels) - 1) - return false; - - rem = BLI_findlink(&ob->lodlevels, level); - - if (rem == ob->currentlod) { - ob->currentlod = rem->prev; - } - - BLI_remlink(&ob->lodlevels, rem); - MEM_freeN(rem); - - /* If there are no user defined lods, remove the base lod as well */ - if (BLI_listbase_is_single(&ob->lodlevels)) { - LodLevel *base = ob->lodlevels.first; - BLI_remlink(&ob->lodlevels, base); - MEM_freeN(base); - ob->currentlod = NULL; - } - - return true; -} - -static LodLevel *lod_level_select(Object *ob, const float camera_position[3]) -{ - LodLevel *current = ob->currentlod; - float dist_sq; - - if (!current) return NULL; - - dist_sq = len_squared_v3v3(ob->obmat[3], camera_position); - - if (dist_sq < SQUARE(current->distance)) { - /* check for higher LoD */ - while (current->prev && dist_sq < SQUARE(current->distance)) { - current = current->prev; - } - } - else { - /* check for lower LoD */ - while (current->next && dist_sq > SQUARE(current->next->distance)) { - current = current->next; - } - } - - return current; -} - -bool BKE_object_lod_is_usable(Object *ob, ViewLayer *view_layer) -{ - bool active = (view_layer) ? ob == OBACT(view_layer) : false; - return (ob->mode == OB_MODE_OBJECT || !active); -} - -void BKE_object_lod_update(Object *ob, const float camera_position[3]) -{ - LodLevel *cur_level = ob->currentlod; - LodLevel *new_level = lod_level_select(ob, camera_position); - - if (new_level != cur_level) { - ob->currentlod = new_level; - } -} - -static Object *lod_ob_get(Object *ob, ViewLayer *view_layer, int flag) -{ - LodLevel *current = ob->currentlod; - - if (!current || !BKE_object_lod_is_usable(ob, view_layer)) - return ob; - - while (current->prev && (!(current->flags & flag) || !current->source || current->source->type != OB_MESH)) { - current = current->prev; - } - - return current->source; -} - -struct Object *BKE_object_lod_meshob_get(Object *ob, ViewLayer *view_layer) -{ - return lod_ob_get(ob, view_layer, OB_LOD_USE_MESH); -} - -struct Object *BKE_object_lod_matob_get(Object *ob, ViewLayer *view_layer) -{ - return lod_ob_get(ob, view_layer, OB_LOD_USE_MAT); -} - -#endif /* WITH_GAMEENGINE */ - - SoftBody *copy_softbody(const SoftBody *sb, const int flag) { SoftBody *sbn; @@ -1012,17 +841,6 @@ SoftBody *copy_softbody(const SoftBody *sb, const int flag) return sbn; } -BulletSoftBody *copy_bulletsoftbody(const BulletSoftBody *bsb, const int UNUSED(flag)) -{ - BulletSoftBody *bsbn; - - if (bsb == NULL) - return NULL; - bsbn = MEM_dupallocN(bsb); - /* no pointer in this structure yet */ - return bsbn; -} - ParticleSystem *BKE_object_copy_particlesystem(ParticleSystem *psys, const int flag) { ParticleSystem *psysn; @@ -1356,11 +1174,6 @@ void BKE_object_copy_data(Main *UNUSED(bmain), Object *ob_dst, const Object *ob_ BLI_addtail(&ob_dst->modifiers, nmd); } - BLI_listbase_clear(&ob_dst->prop); - BKE_bproperty_copy_list(&ob_dst->prop, &ob_src->prop); - - BKE_sca_logic_copy(ob_dst, ob_src, flag_subdata); - if (ob_src->pose) { copy_object_pose(ob_dst, ob_src, flag_subdata); /* backwards compat... non-armatures can get poses in older files? */ @@ -1381,7 +1194,6 @@ void BKE_object_copy_data(Main *UNUSED(bmain), Object *ob_dst, const Object *ob_ } } ob_dst->soft = copy_softbody(ob_src->soft, flag_subdata); - ob_dst->bsoft = copy_bulletsoftbody(ob_src->bsoft, flag_subdata); ob_dst->rigidbody_object = BKE_rigidbody_copy_object(ob_src, flag_subdata); ob_dst->rigidbody_constraint = BKE_rigidbody_copy_constraint(ob_src, flag_subdata); @@ -2756,7 +2568,7 @@ typedef struct ObTfmBack { float obmat[4][4]; /* final worldspace matrix with constraints & animsys applied */ float parentinv[4][4]; /* inverse result of parent, so that object doesn't 'stick' to parent */ float constinv[4][4]; /* inverse result of constraints. doesn't include effect of parent or object local transform */ - float imat[4][4]; /* inverse matrix of 'obmat' for during render, old game engine, temporally: ipokeys of transform */ + float imat[4][4]; /* inverse matrix of 'obmat' for during render, temporally: ipokeys of transform */ } ObTfmBack; void *BKE_object_tfm_backup(Object *ob) diff --git a/source/blender/blenkernel/intern/property.c b/source/blender/blenkernel/intern/property.c deleted file mode 100644 index b163f623d21..00000000000 --- a/source/blender/blenkernel/intern/property.c +++ /dev/null @@ -1,267 +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): ton roosendaal - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file blender/blenkernel/intern/property.c - * \ingroup bke - * - * This module deals with bProperty only, - * they are used on blender objects in the game engine - * (where they get converted into C++ classes - CValue and subclasses) - */ - -#include -#include -#include -#include -#include - -#include "MEM_guardedalloc.h" - -#include "DNA_property_types.h" -#include "DNA_object_types.h" - -#include "BLI_blenlib.h" - -#include "BKE_property.h" - -void BKE_bproperty_free(bProperty *prop) -{ - - if (prop->poin && prop->poin != &prop->data) MEM_freeN(prop->poin); - MEM_freeN(prop); - -} - -void BKE_bproperty_free_list(ListBase *lb) -{ - bProperty *prop; - - while ((prop = BLI_pophead(lb))) { - BKE_bproperty_free(prop); - } -} - -bProperty *BKE_bproperty_copy(const bProperty *prop) -{ - bProperty *propn; - - propn = MEM_dupallocN(prop); - if (prop->poin && prop->poin != &prop->data) { - propn->poin = MEM_dupallocN(prop->poin); - } - else { - propn->poin = &propn->data; - } - - return propn; -} - -void BKE_bproperty_copy_list(ListBase *lbn, const ListBase *lbo) -{ - bProperty *prop, *propn; - BKE_bproperty_free_list(lbn); /* in case we are copying to an object with props */ - prop = lbo->first; - while (prop) { - propn = BKE_bproperty_copy(prop); - BLI_addtail(lbn, propn); - prop = prop->next; - } - - -} - -void BKE_bproperty_init(bProperty *prop) -{ - /* also use when property changes type */ - - if (prop->poin && prop->poin != &prop->data) MEM_freeN(prop->poin); - prop->poin = NULL; - - prop->data = 0; - - switch (prop->type) { - case GPROP_BOOL: - case GPROP_INT: - case GPROP_FLOAT: - case GPROP_TIME: - prop->poin = &prop->data; - break; - case GPROP_STRING: - prop->poin = MEM_callocN(MAX_PROPSTRING, "property string"); - break; - } -} - - -bProperty *BKE_bproperty_new(int type) -{ - bProperty *prop; - - prop = MEM_callocN(sizeof(bProperty), "property"); - prop->type = type; - - BKE_bproperty_init(prop); - - strcpy(prop->name, "prop"); - - return prop; -} - - -bProperty *BKE_bproperty_object_get(Object *ob, const char *name) -{ - return BLI_findstring(&ob->prop, name, offsetof(bProperty, name)); -} - -void BKE_bproperty_object_set(Object *ob, bProperty *propc) -{ - bProperty *prop; - prop = BKE_bproperty_object_get(ob, propc->name); - if (prop) { - BLI_remlink(&ob->prop, prop); - BKE_bproperty_free(prop); - } - BLI_addtail(&ob->prop, BKE_bproperty_copy(propc)); -} - -/* negative: prop is smaller - * positive: prop is larger - */ -#if 0 /* UNUSED */ -int BKE_bproperty_cmp(bProperty *prop, const char *str) -{ -// extern int Gdfra; /* sector.c */ - float fvalue, ftest; - - switch (prop->type) { - case GPROP_BOOL: - if (BLI_strcasecmp(str, "true") == 0) { - if (prop->data == 1) return 0; - else return 1; - } - else if (BLI_strcasecmp(str, "false") == 0) { - if (prop->data == 0) return 0; - else return 1; - } - /* no break, do GPROP_int too! */ - - case GPROP_INT: - return prop->data - atoi(str); - - case GPROP_FLOAT: - case GPROP_TIME: - /* WARNING: untested for GPROP_TIME - * function isn't used currently */ - fvalue = *((float *)&prop->data); - ftest = (float)atof(str); - if (fvalue > ftest) return 1; - else if (fvalue < ftest) return -1; - return 0; - - case GPROP_STRING: - return strcmp(prop->poin, str); - } - - return 0; -} -#endif - -void BKE_bproperty_set(bProperty *prop, const char *str) -{ -// extern int Gdfra; /* sector.c */ - - switch (prop->type) { - case GPROP_BOOL: - if (BLI_strcasecmp(str, "true") == 0) prop->data = 1; - else if (BLI_strcasecmp(str, "false") == 0) prop->data = 0; - else prop->data = (atoi(str) != 0); - break; - case GPROP_INT: - prop->data = atoi(str); - break; - case GPROP_FLOAT: - case GPROP_TIME: - *((float *)&prop->data) = (float)atof(str); - break; - case GPROP_STRING: - strcpy(prop->poin, str); /* TODO - check size? */ - break; - } - -} - -void BKE_bproperty_add(bProperty *prop, const char *str) -{ -// extern int Gdfra; /* sector.c */ - - switch (prop->type) { - case GPROP_BOOL: - case GPROP_INT: - prop->data += atoi(str); - break; - case GPROP_FLOAT: - case GPROP_TIME: - *((float *)&prop->data) += (float)atof(str); - break; - case GPROP_STRING: - /* strcpy(prop->poin, str); */ - break; - } -} - -/* reads value of property, sets it in chars in str */ -void BKE_bproperty_set_valstr(bProperty *prop, char str[MAX_PROPSTRING]) -{ -// extern int Gdfra; /* sector.c */ - - if (str == NULL) return; - - switch (prop->type) { - case GPROP_BOOL: - case GPROP_INT: - sprintf(str, "%d", prop->data); - break; - case GPROP_FLOAT: - case GPROP_TIME: - sprintf(str, "%f", *((float *)&prop->data)); - break; - case GPROP_STRING: - BLI_strncpy(str, prop->poin, MAX_PROPSTRING); - break; - } -} - -#if 0 /* UNUSED */ -void cp_property(bProperty *prop1, bProperty *prop2) -{ - char str[128]; - - BKE_bproperty_set_valstr(prop2, str); - - BKE_bproperty_set(prop1, str); -} -#endif diff --git a/source/blender/blenkernel/intern/rigidbody.c b/source/blender/blenkernel/intern/rigidbody.c index ab8f9dcb2e4..fdeba7186e8 100644 --- a/source/blender/blenkernel/intern/rigidbody.c +++ b/source/blender/blenkernel/intern/rigidbody.c @@ -1024,8 +1024,8 @@ RigidBodyOb *BKE_rigidbody_create_object(Scene *scene, Object *ob, short type) rbo->lin_sleep_thresh = 0.4f; /* 0.4 is half of Bullet default */ rbo->ang_sleep_thresh = 0.5f; /* 0.5 is half of Bullet default */ - rbo->lin_damping = 0.04f; /* 0.04 is game engine default */ - rbo->ang_damping = 0.1f; /* 0.1 is game engine default */ + rbo->lin_damping = 0.04f; + rbo->ang_damping = 0.1f; rbo->col_groups = 1; diff --git a/source/blender/blenkernel/intern/sca.c b/source/blender/blenkernel/intern/sca.c deleted file mode 100644 index fb81ed4d47f..00000000000 --- a/source/blender/blenkernel/intern/sca.c +++ /dev/null @@ -1,1179 +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 ***** - * these all are linked to objects (listbase) - * all data is 'direct data', not Blender lib data. - */ - -/** \file blender/blenkernel/intern/sca.c - * \ingroup bke - */ - - -#include -#include -#include - -#include "MEM_guardedalloc.h" - -#include "DNA_controller_types.h" -#include "DNA_sensor_types.h" -#include "DNA_actuator_types.h" -#include "DNA_object_types.h" - -#include "BLI_blenlib.h" -#include "BLI_ghash.h" -#include "BLI_math.h" - -#include "BKE_global.h" -#include "BKE_main.h" -#include "BKE_library.h" -#include "BKE_library_query.h" -#include "BKE_sca.h" - -/* ******************* SENSORS ************************ */ - -void free_sensor(bSensor *sens) -{ - if (sens->links) MEM_freeN(sens->links); - if (sens->data) MEM_freeN(sens->data); - MEM_freeN(sens); - -} - -void free_sensors(ListBase *lb) -{ - bSensor *sens; - - while ((sens = BLI_pophead(lb))) { - free_sensor(sens); - } -} - -bSensor *copy_sensor(bSensor *sens, const int UNUSED(flag)) -{ - bSensor *sensn; - - sensn= MEM_dupallocN(sens); - sensn->flag |= SENS_NEW; - if (sens->data) { - sensn->data= MEM_dupallocN(sens->data); - } - - if (sens->links) sensn->links= MEM_dupallocN(sens->links); - - return sensn; -} - -void copy_sensors(ListBase *lbn, const ListBase *lbo, const int flag) -{ - bSensor *sens, *sensn; - - lbn->first= lbn->last= NULL; - sens= lbo->first; - while (sens) { - sensn= copy_sensor(sens, flag); - BLI_addtail(lbn, sensn); - sens= sens->next; - } -} - -void init_sensor(bSensor *sens) -{ - /* also use when sensor changes type */ - bNearSensor *ns; - bMouseSensor *ms; - bJoystickSensor *js; - bRaySensor *rs; - - if (sens->data) MEM_freeN(sens->data); - sens->data= NULL; - sens->pulse = 0; - - switch (sens->type) { - case SENS_ALWAYS: - sens->pulse = 0; - break; - case SENS_NEAR: - ns=sens->data= MEM_callocN(sizeof(bNearSensor), "nearsens"); - ns->dist= 1.0; - ns->resetdist= 2.0; - break; - case SENS_KEYBOARD: - sens->data= MEM_callocN(sizeof(bKeyboardSensor), "keysens"); - break; - case SENS_PROPERTY: - sens->data= MEM_callocN(sizeof(bPropertySensor), "propsens"); - break; - case SENS_ARMATURE: - sens->data= MEM_callocN(sizeof(bArmatureSensor), "armsens"); - break; - case SENS_ACTUATOR: - sens->data= MEM_callocN(sizeof(bActuatorSensor), "actsens"); - break; - case SENS_DELAY: - sens->data= MEM_callocN(sizeof(bDelaySensor), "delaysens"); - break; - case SENS_MOUSE: - ms=sens->data= MEM_callocN(sizeof(bMouseSensor), "mousesens"); - ms->type= 1; // LEFTMOUSE workaround because Mouse Sensor types enum starts in 1 - break; - case SENS_COLLISION: - sens->data= MEM_callocN(sizeof(bCollisionSensor), "colsens"); - break; - case SENS_RADAR: - sens->data= MEM_callocN(sizeof(bRadarSensor), "radarsens"); - break; - case SENS_RANDOM: - sens->data= MEM_callocN(sizeof(bRandomSensor), "randomsens"); - break; - case SENS_RAY: - sens->data= MEM_callocN(sizeof(bRaySensor), "raysens"); - rs = sens->data; - rs->range = 0.01f; - break; - case SENS_MESSAGE: - sens->data= MEM_callocN(sizeof(bMessageSensor), "messagesens"); - break; - case SENS_JOYSTICK: - sens->data= MEM_callocN(sizeof(bJoystickSensor), "joysticksens"); - js= sens->data; - js->hatf = SENS_JOY_HAT_UP; - js->axis = 1; - js->hat = 1; - break; - default: - ; /* this is very severe... I cannot make any memory for this */ - /* logic brick... */ - } -} - -bSensor *new_sensor(int type) -{ - bSensor *sens; - - sens= MEM_callocN(sizeof(bSensor), "Sensor"); - sens->type= type; - sens->flag= SENS_SHOW; - - init_sensor(sens); - - strcpy(sens->name, "sensor"); -// XXX make_unique_prop_names(sens->name); - - return sens; -} - -/* ******************* CONTROLLERS ************************ */ - -void unlink_controller(bController *cont) -{ - bSensor *sens; - Object *ob; - - /* check for controller pointers in sensors */ - ob= G.main->object.first; - while (ob) { - sens= ob->sensors.first; - while (sens) { - unlink_logicbricks((void **)&cont, (void ***)&(sens->links), &sens->totlinks); - sens= sens->next; - } - ob= ob->id.next; - } -} - -void unlink_controllers(ListBase *lb) -{ - bController *cont; - - for (cont= lb->first; cont; cont= cont->next) - unlink_controller(cont); -} - -void free_controller(bController *cont) -{ - if (cont->links) MEM_freeN(cont->links); - - /* the controller itself */ - if (cont->data) MEM_freeN(cont->data); - MEM_freeN(cont); - -} - -void free_controllers(ListBase *lb) -{ - bController *cont; - - while ((cont = BLI_pophead(lb))) { - if (cont->slinks) - MEM_freeN(cont->slinks); - free_controller(cont); - } -} - -bController *copy_controller(bController *cont, const int UNUSED(flag)) -{ - bController *contn; - - cont->mynew=contn= MEM_dupallocN(cont); - contn->flag |= CONT_NEW; - if (cont->data) { - contn->data= MEM_dupallocN(cont->data); - } - - if (cont->links) contn->links= MEM_dupallocN(cont->links); - contn->slinks= NULL; - contn->totslinks= 0; - - return contn; -} - -void copy_controllers(ListBase *lbn, const ListBase *lbo, const int flag) -{ - bController *cont, *contn; - - lbn->first= lbn->last= NULL; - cont= lbo->first; - while (cont) { - contn= copy_controller(cont, flag); - BLI_addtail(lbn, contn); - cont= cont->next; - } -} - -void init_controller(bController *cont) -{ - /* also use when controller changes type, leave actuators... */ - - if (cont->data) MEM_freeN(cont->data); - cont->data= NULL; - - switch (cont->type) { - case CONT_EXPRESSION: - cont->data= MEM_callocN(sizeof(bExpressionCont), "expcont"); - break; - case CONT_PYTHON: - cont->data= MEM_callocN(sizeof(bPythonCont), "pycont"); - break; - } -} - -bController *new_controller(int type) -{ - bController *cont; - - cont= MEM_callocN(sizeof(bController), "Controller"); - cont->type= type; - cont->flag= CONT_SHOW; - - init_controller(cont); - - strcpy(cont->name, "cont"); -// XXX make_unique_prop_names(cont->name); - - return cont; -} - -/* ******************* ACTUATORS ************************ */ - -void unlink_actuator(bActuator *act) -{ - bController *cont; - Object *ob; - - /* check for actuator pointers in controllers */ - ob= G.main->object.first; - while (ob) { - cont= ob->controllers.first; - while (cont) { - unlink_logicbricks((void **)&act, (void ***)&(cont->links), &cont->totlinks); - cont= cont->next; - } - ob= ob->id.next; - } -} - -void unlink_actuators(ListBase *lb) -{ - bActuator *act; - - for (act= lb->first; act; act= act->next) - unlink_actuator(act); -} - -void free_actuator(bActuator *act) -{ - if (act->data) { - switch (act->type) { - case ACT_ACTION: - case ACT_SHAPEACTION: - { - bActionActuator *aa = (bActionActuator *)act->data; - if (aa->act) - id_us_min((ID *)aa->act); - break; - } - case ACT_SOUND: - { - bSoundActuator *sa = (bSoundActuator *) act->data; - if (sa->sound) - id_us_min((ID *)sa->sound); - break; - } - } - - MEM_freeN(act->data); - } - MEM_freeN(act); -} - -void free_actuators(ListBase *lb) -{ - bActuator *act; - - while ((act = BLI_pophead(lb))) { - free_actuator(act); - } -} - -bActuator *copy_actuator(bActuator *act, const int flag) -{ - bActuator *actn; - - act->mynew=actn= MEM_dupallocN(act); - actn->flag |= ACT_NEW; - if (act->data) { - actn->data= MEM_dupallocN(act->data); - } - - switch (act->type) { - case ACT_ACTION: - case ACT_SHAPEACTION: - { - bActionActuator *aa = (bActionActuator *)act->data; - if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) { - id_us_plus((ID *)aa->act); - } - break; - } - case ACT_SOUND: - { - bSoundActuator *sa = (bSoundActuator *)act->data; - if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) { - id_us_plus((ID *)sa->sound); - } - break; - } - } - return actn; -} - -void copy_actuators(ListBase *lbn, const ListBase *lbo, const int flag) -{ - bActuator *act, *actn; - - lbn->first= lbn->last= NULL; - act= lbo->first; - while (act) { - actn= copy_actuator(act, flag); - BLI_addtail(lbn, actn); - act= act->next; - } -} - -void init_actuator(bActuator *act) -{ - /* also use when actuator changes type */ - bCameraActuator *ca; - bObjectActuator *oa; - bRandomActuator *ra; - bSoundActuator *sa; - bSteeringActuator *sta; - bArmatureActuator *arma; - bMouseActuator *ma; - bEditObjectActuator *eoa; - - if (act->data) MEM_freeN(act->data); - act->data= NULL; - - switch (act->type) { - case ACT_ACTION: - case ACT_SHAPEACTION: - act->data= MEM_callocN(sizeof(bActionActuator), "actionact"); - break; - case ACT_SOUND: - sa = act->data= MEM_callocN(sizeof(bSoundActuator), "soundact"); - sa->volume = 1.0f; - sa->sound3D.rolloff_factor = 1.0f; - sa->sound3D.reference_distance = 1.0f; - sa->sound3D.max_gain = 1.0f; - sa->sound3D.cone_inner_angle = DEG2RADF(360.0f); - sa->sound3D.cone_outer_angle = DEG2RADF(360.0f); - sa->sound3D.max_distance = FLT_MAX; - break; - case ACT_OBJECT: - act->data= MEM_callocN(sizeof(bObjectActuator), "objectact"); - oa= act->data; - oa->flag= 15; - break; - case ACT_PROPERTY: - act->data= MEM_callocN(sizeof(bPropertyActuator), "propact"); - break; - case ACT_CAMERA: - act->data= MEM_callocN(sizeof(bCameraActuator), "camact"); - ca = act->data; - ca->axis = OB_POSX; - ca->damping = 1.0/32.0; - break; - case ACT_EDIT_OBJECT: - act->data= MEM_callocN(sizeof(bEditObjectActuator), "editobact"); - eoa = act->data; - eoa->upflag= ACT_TRACK_UP_Z; - eoa->trackflag= ACT_TRACK_TRAXIS_Y; - break; - case ACT_CONSTRAINT: - act->data= MEM_callocN(sizeof(bConstraintActuator), "cons act"); - break; - case ACT_SCENE: - act->data= MEM_callocN(sizeof(bSceneActuator), "scene act"); - break; - case ACT_GROUP: - act->data= MEM_callocN(sizeof(bGroupActuator), "group act"); - break; - case ACT_RANDOM: - act->data= MEM_callocN(sizeof(bRandomActuator), "random act"); - ra=act->data; - ra->float_arg_1 = 0.1f; - break; - case ACT_MESSAGE: - act->data= MEM_callocN(sizeof(bMessageActuator), "message act"); - break; - case ACT_GAME: - act->data= MEM_callocN(sizeof(bGameActuator), "game act"); - break; - case ACT_VISIBILITY: - act->data= MEM_callocN(sizeof(bVisibilityActuator), "visibility act"); - break; - case ACT_2DFILTER: - act->data = MEM_callocN(sizeof( bTwoDFilterActuator ), "2d filter act"); - break; - case ACT_PARENT: - act->data = MEM_callocN(sizeof( bParentActuator ), "parent act"); - break; - case ACT_STATE: - act->data = MEM_callocN(sizeof( bStateActuator ), "state act"); - break; - case ACT_ARMATURE: - act->data = MEM_callocN(sizeof( bArmatureActuator ), "armature act"); - arma = act->data; - arma->influence = 1.f; - break; - case ACT_STEERING: - act->data = MEM_callocN(sizeof( bSteeringActuator), "steering act"); - sta = act->data; - sta->acceleration = 3.f; - sta->turnspeed = 120.f; - sta->dist = 1.f; - sta->velocity= 3.f; - sta->flag = ACT_STEERING_AUTOMATICFACING | ACT_STEERING_LOCKZVEL; - sta->facingaxis = 1; - break; - case ACT_MOUSE: - ma = act->data = MEM_callocN(sizeof( bMouseActuator ), "mouse act"); - ma->flag = ACT_MOUSE_VISIBLE|ACT_MOUSE_USE_AXIS_X|ACT_MOUSE_USE_AXIS_Y|ACT_MOUSE_RESET_X|ACT_MOUSE_RESET_Y|ACT_MOUSE_LOCAL_Y; - ma->sensitivity[0] = ma->sensitivity[1] = 2.f; - ma->object_axis[0] = ACT_MOUSE_OBJECT_AXIS_Z; - ma->object_axis[1] = ACT_MOUSE_OBJECT_AXIS_X; - ma->limit_y[0] = DEG2RADF(-90.0f); - ma->limit_y[1] = DEG2RADF(90.0f); - break; - default: - ; /* this is very severe... I cannot make any memory for this */ - /* logic brick... */ - } -} - -bActuator *new_actuator(int type) -{ - bActuator *act; - - act= MEM_callocN(sizeof(bActuator), "Actuator"); - act->type= type; - act->flag= ACT_SHOW; - - init_actuator(act); - - strcpy(act->name, "act"); -// XXX make_unique_prop_names(act->name); - - return act; -} - -/* ******************** GENERAL ******************* */ -void clear_sca_new_poins_ob(Object *ob) -{ - bSensor *sens; - bController *cont; - bActuator *act; - - sens= ob->sensors.first; - while (sens) { - sens->flag &= ~SENS_NEW; - sens= sens->next; - } - cont= ob->controllers.first; - while (cont) { - cont->mynew= NULL; - cont->flag &= ~CONT_NEW; - cont= cont->next; - } - act= ob->actuators.first; - while (act) { - act->mynew= NULL; - act->flag &= ~ACT_NEW; - act= act->next; - } -} - -void clear_sca_new_poins(void) -{ - Object *ob; - - ob= G.main->object.first; - while (ob) { - clear_sca_new_poins_ob(ob); - ob= ob->id.next; - } -} - -void set_sca_new_poins_ob(Object *ob) -{ - bSensor *sens; - bController *cont; - bActuator *act; - int a; - - sens= ob->sensors.first; - while (sens) { - if (sens->flag & SENS_NEW) { - for (a=0; atotlinks; a++) { - if (sens->links[a] && sens->links[a]->mynew) - sens->links[a] = sens->links[a]->mynew; - } - } - sens= sens->next; - } - - cont= ob->controllers.first; - while (cont) { - if (cont->flag & CONT_NEW) { - for (a=0; atotlinks; a++) { - if ( cont->links[a] && cont->links[a]->mynew) - cont->links[a] = cont->links[a]->mynew; - } - } - cont= cont->next; - } - - - act= ob->actuators.first; - while (act) { - if (act->flag & ACT_NEW) { - if (act->type==ACT_EDIT_OBJECT) { - bEditObjectActuator *eoa= act->data; - ID_NEW_REMAP(eoa->ob); - } - else if (act->type==ACT_SCENE) { - bSceneActuator *sca= act->data; - ID_NEW_REMAP(sca->camera); - } - else if (act->type==ACT_CAMERA) { - bCameraActuator *ca= act->data; - ID_NEW_REMAP(ca->ob); - } - else if (act->type==ACT_OBJECT) { - bObjectActuator *oa= act->data; - ID_NEW_REMAP(oa->reference); - } - else if (act->type==ACT_MESSAGE) { - bMessageActuator *ma= act->data; - ID_NEW_REMAP(ma->toObject); - } - else if (act->type==ACT_PARENT) { - bParentActuator *para = act->data; - ID_NEW_REMAP(para->ob); - } - else if (act->type==ACT_ARMATURE) { - bArmatureActuator *aa = act->data; - ID_NEW_REMAP(aa->target); - ID_NEW_REMAP(aa->subtarget); - } - else if (act->type==ACT_PROPERTY) { - bPropertyActuator *pa= act->data; - ID_NEW_REMAP(pa->ob); - } - else if (act->type==ACT_STEERING) { - bSteeringActuator *sta = act->data; - ID_NEW_REMAP(sta->navmesh); - ID_NEW_REMAP(sta->target); - } - } - act= act->next; - } -} - - -void set_sca_new_poins(void) -{ - Object *ob; - - ob= G.main->object.first; - while (ob) { - set_sca_new_poins_ob(ob); - ob= ob->id.next; - } -} - -/** - * Try to remap logic links to new object... Very, *very* weak. - */ -/* XXX Logick bricks... I don't have words to say what I think about this behavior. - * They have silent hidden ugly inter-objects dependencies (a sensor can link into any other - * object's controllers, and same between controllers and actuators, without *any* explicit reference - * to data-block involved). - * This is bad, bad, bad!!! - * ...and forces us to add yet another very ugly hack to get remapping with logic bricks working. */ -void BKE_sca_logic_links_remap(Main *bmain, Object *ob_old, Object *ob_new) -{ - if (ob_new == NULL || (ob_old->controllers.first == NULL && ob_old->actuators.first == NULL)) { - /* Nothing to do here... */ - return; - } - - GHash *controllers_map = ob_old->controllers.first ? - BLI_ghash_ptr_new_ex(__func__, BLI_listbase_count(&ob_old->controllers)) : NULL; - GHash *actuators_map = ob_old->actuators.first ? - BLI_ghash_ptr_new_ex(__func__, BLI_listbase_count(&ob_old->actuators)) : NULL; - - /* We try to remap old controllers/actuators to new ones - in a very basic way. */ - for (bController *cont_old = ob_old->controllers.first, *cont_new = ob_new->controllers.first; - cont_old; - cont_old = cont_old->next) - { - bController *cont_new2 = cont_new; - - if (cont_old->mynew != NULL) { - cont_new2 = cont_old->mynew; - if (!(cont_new2 == cont_new || BLI_findindex(&ob_new->controllers, cont_new2) >= 0)) { - cont_new2 = NULL; - } - } - else if (cont_new && cont_old->type != cont_new->type) { - cont_new2 = NULL; - } - - BLI_ghash_insert(controllers_map, cont_old, cont_new2); - - if (cont_new) { - cont_new = cont_new->next; - } - } - - for (bActuator *act_old = ob_old->actuators.first, *act_new = ob_new->actuators.first; - act_old; - act_old = act_old->next) - { - bActuator *act_new2 = act_new; - - if (act_old->mynew != NULL) { - act_new2 = act_old->mynew; - if (!(act_new2 == act_new || BLI_findindex(&ob_new->actuators, act_new2) >= 0)) { - act_new2 = NULL; - } - } - else if (act_new && act_old->type != act_new->type) { - act_new2 = NULL; - } - - BLI_ghash_insert(actuators_map, act_old, act_new2); - - if (act_new) { - act_new = act_new->next; - } - } - - for (Object *ob = bmain->object.first; ob; ob = ob->id.next) { - if (controllers_map != NULL) { - for (bSensor *sens = ob->sensors.first; sens; sens = sens->next) { - for (int a = 0; a < sens->totlinks; a++) { - if (sens->links[a]) { - bController *old_link = sens->links[a]; - bController **new_link_p = (bController **)BLI_ghash_lookup_p(controllers_map, old_link); - - if (new_link_p == NULL) { - /* old_link is *not* in map's keys (i.e. not to any ob_old->controllers), - * which means we ignore it totally here. */ - } - else if (*new_link_p == NULL) { - unlink_logicbricks((void **)&old_link, (void ***)&(sens->links), &sens->totlinks); - a--; - } - else { - sens->links[a] = *new_link_p; - } - } - } - } - } - - if (actuators_map != NULL) { - for (bController *cont = ob->controllers.first; cont; cont = cont->next) { - for (int a = 0; a < cont->totlinks; a++) { - if (cont->links[a]) { - bActuator *old_link = cont->links[a]; - bActuator **new_link_p = (bActuator **)BLI_ghash_lookup_p(actuators_map, old_link); - - if (new_link_p == NULL) { - /* old_link is *not* in map's keys (i.e. not to any ob_old->actuators), - * which means we ignore it totally here. */ - } - else if (*new_link_p == NULL) { - unlink_logicbricks((void **)&old_link, (void ***)&(cont->links), &cont->totlinks); - a--; - } - else { - cont->links[a] = *new_link_p; - } - } - } - } - } - } - - if (controllers_map) { - BLI_ghash_free(controllers_map, NULL, NULL); - } - if (actuators_map) { - BLI_ghash_free(actuators_map, NULL, NULL); - } -} - -/** - * Handle the copying of logic data into a new object, including internal logic links update. - * External links (links between logic bricks of different objects) must be handled separately. - */ -void BKE_sca_logic_copy(Object *ob_new, const Object *ob, const int flag) -{ - copy_sensors(&ob_new->sensors, &ob->sensors, flag); - copy_controllers(&ob_new->controllers, &ob->controllers, flag); - copy_actuators(&ob_new->actuators, &ob->actuators, flag); - - for (bSensor *sens = ob_new->sensors.first; sens; sens = sens->next) { - if (sens->flag & SENS_NEW) { - for (int a = 0; a < sens->totlinks; a++) { - if (sens->links[a] && sens->links[a]->mynew) { - sens->links[a] = sens->links[a]->mynew; - } - } - } - } - - for (bController *cont = ob_new->controllers.first; cont; cont = cont->next) { - if (cont->flag & CONT_NEW) { - for (int a = 0; a < cont->totlinks; a++) { - if (cont->links[a] && cont->links[a]->mynew) { - cont->links[a] = cont->links[a]->mynew; - } - } - } - } -} - -/* ******************** INTERFACE ******************* */ -void sca_move_sensor(bSensor *sens_to_move, Object *ob, int move_up) -{ - bSensor *sens, *tmp; - - int val; - val = move_up ? 1 : 2; - - /* make sure this sensor belongs to this object */ - sens= ob->sensors.first; - while (sens) { - if (sens == sens_to_move) break; - sens= sens->next; - } - if (!sens) return; - - /* move up */ - if (val == 1 && sens->prev) { - for (tmp=sens->prev; tmp; tmp=tmp->prev) { - if (tmp->flag & SENS_VISIBLE) - break; - } - if (tmp) { - BLI_remlink(&ob->sensors, sens); - BLI_insertlinkbefore(&ob->sensors, tmp, sens); - } - } - /* move down */ - else if (val == 2 && sens->next) { - for (tmp=sens->next; tmp; tmp=tmp->next) { - if (tmp->flag & SENS_VISIBLE) - break; - } - if (tmp) { - BLI_remlink(&ob->sensors, sens); - BLI_insertlinkafter(&ob->sensors, tmp, sens); - } - } -} - -void sca_move_controller(bController *cont_to_move, Object *ob, int move_up) -{ - bController *cont, *tmp; - - int val; - val = move_up ? 1 : 2; - - /* make sure this controller belongs to this object */ - cont= ob->controllers.first; - while (cont) { - if (cont == cont_to_move) break; - cont= cont->next; - } - if (!cont) return; - - /* move up */ - if (val == 1 && cont->prev) { - /* locate the controller that has the same state mask but is earlier in the list */ - tmp = cont->prev; - while (tmp) { - if (tmp->state_mask & cont->state_mask) - break; - tmp = tmp->prev; - } - if (tmp) { - BLI_remlink(&ob->controllers, cont); - BLI_insertlinkbefore(&ob->controllers, tmp, cont); - } - } - - /* move down */ - else if (val == 2 && cont->next) { - tmp = cont->next; - while (tmp) { - if (tmp->state_mask & cont->state_mask) - break; - tmp = tmp->next; - } - BLI_remlink(&ob->controllers, cont); - BLI_insertlinkafter(&ob->controllers, tmp, cont); - } -} - -void sca_move_actuator(bActuator *act_to_move, Object *ob, int move_up) -{ - bActuator *act, *tmp; - int val; - - val = move_up ? 1 : 2; - - /* make sure this actuator belongs to this object */ - act= ob->actuators.first; - while (act) { - if (act == act_to_move) break; - act= act->next; - } - if (!act) return; - - /* move up */ - if (val == 1 && act->prev) { - /* locate the first visible actuators before this one */ - for (tmp = act->prev; tmp; tmp=tmp->prev) { - if (tmp->flag & ACT_VISIBLE) - break; - } - if (tmp) { - BLI_remlink(&ob->actuators, act); - BLI_insertlinkbefore(&ob->actuators, tmp, act); - } - } - /* move down */ - else if (val == 2 && act->next) { - /* locate the first visible actuators after this one */ - for (tmp=act->next; tmp; tmp=tmp->next) { - if (tmp->flag & ACT_VISIBLE) - break; - } - if (tmp) { - BLI_remlink(&ob->actuators, act); - BLI_insertlinkafter(&ob->actuators, tmp, act); - } - } -} - -void link_logicbricks(void **poin, void ***ppoin, short *tot, short size) -{ - void **old_links= NULL; - - int ibrick; - - /* check if the bricks are already linked */ - for (ibrick=0; ibrick < *tot; ibrick++) { - if ((*ppoin)[ibrick] == *poin) - return; - } - - if (*ppoin) { - old_links= *ppoin; - - (*tot) ++; - *ppoin = MEM_callocN((*tot)*size, "new link"); - - for (ibrick=0; ibrick < *(tot) - 1; ibrick++) { - (*ppoin)[ibrick] = old_links[ibrick]; - } - (*ppoin)[ibrick] = *poin; - - if (old_links) MEM_freeN(old_links); - } - else { - (*tot) = 1; - *ppoin = MEM_callocN((*tot)*size, "new link"); - (*ppoin)[0] = *poin; - } -} - -void unlink_logicbricks(void **poin, void ***ppoin, short *tot) -{ - int ibrick, removed; - - removed= 0; - for (ibrick=0; ibrick < *tot; ibrick++) { - if (removed) (*ppoin)[ibrick - removed] = (*ppoin)[ibrick]; - else if ((*ppoin)[ibrick] == *poin) removed = 1; - } - - if (removed) { - (*tot) --; - - if (*tot == 0) { - MEM_freeN(*ppoin); - (*ppoin)= NULL; - } - return; - } -} - -void BKE_sca_sensors_id_loop(ListBase *senslist, SCASensorIDFunc func, void *userdata) -{ - bSensor *sensor; - - for (sensor = senslist->first; sensor; sensor = sensor->next) { - func(sensor, (ID **)&sensor->ob, userdata, IDWALK_CB_NOP); - - switch (sensor->type) { - case SENS_TOUCH: /* DEPRECATED */ - { - bTouchSensor *ts = sensor->data; - func(sensor, (ID **)&ts->ma, userdata, IDWALK_CB_NOP); - break; - } - case SENS_MESSAGE: - { - bMessageSensor *ms = sensor->data; - func(sensor, (ID **)&ms->fromObject, userdata, IDWALK_CB_NOP); - break; - } - case SENS_ALWAYS: - case SENS_NEAR: - case SENS_KEYBOARD: - case SENS_PROPERTY: - case SENS_MOUSE: - case SENS_COLLISION: - case SENS_RADAR: - case SENS_RANDOM: - case SENS_RAY: - case SENS_JOYSTICK: - case SENS_ACTUATOR: - case SENS_DELAY: - case SENS_ARMATURE: - default: - break; - } - } -} - -void BKE_sca_controllers_id_loop(ListBase *contlist, SCAControllerIDFunc func, void *userdata) -{ - bController *controller; - - for (controller = contlist->first; controller; controller = controller->next) { - switch (controller->type) { - case CONT_PYTHON: - { - bPythonCont *pc = controller->data; - func(controller, (ID **)&pc->text, userdata, IDWALK_CB_NOP); - break; - } - case CONT_LOGIC_AND: - case CONT_LOGIC_OR: - case CONT_EXPRESSION: - case CONT_LOGIC_NAND: - case CONT_LOGIC_NOR: - case CONT_LOGIC_XOR: - case CONT_LOGIC_XNOR: - default: - break; - } - } -} - -void BKE_sca_actuators_id_loop(ListBase *actlist, SCAActuatorIDFunc func, void *userdata) -{ - bActuator *actuator; - - for (actuator = actlist->first; actuator; actuator = actuator->next) { - func(actuator, (ID **)&actuator->ob, userdata, IDWALK_CB_NOP); - - switch (actuator->type) { - case ACT_ADD_OBJECT: /* DEPRECATED */ - { - bAddObjectActuator *aoa = actuator->data; - func(actuator, (ID **)&aoa->ob, userdata, IDWALK_CB_NOP); - break; - } - case ACT_ACTION: - { - bActionActuator *aa = actuator->data; - func(actuator, (ID **)&aa->act, userdata, IDWALK_CB_NOP); - break; - } - case ACT_SOUND: - { - bSoundActuator *sa = actuator->data; - func(actuator, (ID **)&sa->sound, userdata, IDWALK_CB_NOP); - break; - } - case ACT_EDIT_OBJECT: - { - bEditObjectActuator *eoa = actuator->data; - func(actuator, (ID **)&eoa->ob, userdata, IDWALK_CB_NOP); - func(actuator, (ID **)&eoa->me, userdata, IDWALK_CB_NOP); - break; - } - case ACT_SCENE: - { - bSceneActuator *sa = actuator->data; - func(actuator, (ID **)&sa->scene, userdata, IDWALK_CB_NOP); - func(actuator, (ID **)&sa->camera, userdata, IDWALK_CB_NOP); - break; - } - case ACT_PROPERTY: - { - bPropertyActuator *pa = actuator->data; - func(actuator, (ID **)&pa->ob, userdata, IDWALK_CB_NOP); - break; - } - case ACT_OBJECT: - { - bObjectActuator *oa = actuator->data; - func(actuator, (ID **)&oa->reference, userdata, IDWALK_CB_NOP); - break; - } - case ACT_CAMERA: - { - bCameraActuator *ca = actuator->data; - func(actuator, (ID **)&ca->ob, userdata, IDWALK_CB_NOP); - break; - } - case ACT_MESSAGE: - { - bMessageActuator *ma = actuator->data; - func(actuator, (ID **)&ma->toObject, userdata, IDWALK_CB_NOP); - break; - } - case ACT_2DFILTER: - { - bTwoDFilterActuator *tdfa = actuator->data; - func(actuator, (ID **)&tdfa->text, userdata, IDWALK_CB_NOP); - break; - } - case ACT_PARENT: - { - bParentActuator *pa = actuator->data; - func(actuator, (ID **)&pa->ob, userdata, IDWALK_CB_NOP); - break; - } - case ACT_ARMATURE: - { - bArmatureActuator *aa = actuator->data; - func(actuator, (ID **)&aa->target, userdata, IDWALK_CB_NOP); - func(actuator, (ID **)&aa->subtarget, userdata, IDWALK_CB_NOP); - break; - } - case ACT_STEERING: - { - bSteeringActuator *sa = actuator->data; - func(actuator, (ID **)&sa->target, userdata, IDWALK_CB_NOP); - func(actuator, (ID **)&sa->navmesh, userdata, IDWALK_CB_NOP); - break; - } - /* Note: some types seems to be non-implemented? ACT_LAMP, ACT_MATERIAL... */ - case ACT_LAMP: - case ACT_MATERIAL: - case ACT_END_OBJECT: /* DEPRECATED */ - case ACT_CONSTRAINT: - case ACT_GROUP: - case ACT_RANDOM: - case ACT_GAME: - case ACT_VISIBILITY: - case ACT_SHAPEACTION: - case ACT_STATE: - case ACT_MOUSE: - default: - break; - } - } -} - -const char *sca_state_name_get(Object *ob, short bit) -{ - bController *cont; - unsigned int mask; - - mask = (1<controllers.first; - while (cont) { - if (cont->state_mask & mask) { - return cont->name; - } - cont = cont->next; - } - return NULL; -} - diff --git a/source/blender/blenkernel/intern/scene.c b/source/blender/blenkernel/intern/scene.c index ee60a9b9f4d..e94a722ca28 100644 --- a/source/blender/blenkernel/intern/scene.c +++ b/source/blender/blenkernel/intern/scene.c @@ -112,7 +112,6 @@ #include "bmesh.h" const char *RE_engine_id_BLENDER_RENDER = "BLENDER_RENDER"; -const char *RE_engine_id_BLENDER_GAME = "BLENDER_GAME"; const char *RE_engine_id_BLENDER_CLAY = "BLENDER_CLAY"; const char *RE_engine_id_BLENDER_EEVEE = "BLENDER_EEVEE"; const char *RE_engine_id_BLENDER_WORKBENCH = "BLENDER_WORKBENCH"; @@ -351,7 +350,6 @@ Scene *BKE_scene_copy(Main *bmain, Scene *sce, int type) sce_copy->r.views = rv; sce_copy->unit = sce->unit; sce_copy->physics_settings = sce->physics_settings; - sce_copy->gm = sce->gm; sce_copy->audio = sce->audio; if (sce->id.properties) @@ -767,59 +765,6 @@ void BKE_scene_init(Scene *sce) srv = sce->r.views.last; BLI_strncpy(srv->suffix, STEREO_RIGHT_SUFFIX, sizeof(srv->suffix)); - /* game data */ - sce->gm.stereoflag = STEREO_NOSTEREO; - sce->gm.stereomode = STEREO_ANAGLYPH; - sce->gm.eyeseparation = 0.10; - - sce->gm.dome.angle = 180; - sce->gm.dome.mode = DOME_FISHEYE; - sce->gm.dome.res = 4; - sce->gm.dome.resbuf = 1.0f; - sce->gm.dome.tilt = 0; - - sce->gm.xplay = 640; - sce->gm.yplay = 480; - sce->gm.freqplay = 60; - sce->gm.depth = 32; - - sce->gm.gravity = 9.8f; - sce->gm.physicsEngine = WOPHY_BULLET; - sce->gm.mode = 32; //XXX ugly harcoding, still not sure we should drop mode. 32 == 1 << 5 == use_occlusion_culling - sce->gm.occlusionRes = 128; - sce->gm.ticrate = 60; - sce->gm.maxlogicstep = 5; - sce->gm.physubstep = 1; - sce->gm.maxphystep = 5; - sce->gm.lineardeactthreshold = 0.8f; - sce->gm.angulardeactthreshold = 1.0f; - sce->gm.deactivationtime = 0.0f; - - sce->gm.flag = 0; - sce->gm.matmode = GAME_MAT_MULTITEX; - - sce->gm.obstacleSimulation = OBSTSIMULATION_NONE; - sce->gm.levelHeight = 2.f; - - sce->gm.recastData.cellsize = 0.3f; - sce->gm.recastData.cellheight = 0.2f; - sce->gm.recastData.agentmaxslope = M_PI_4; - sce->gm.recastData.agentmaxclimb = 0.9f; - sce->gm.recastData.agentheight = 2.0f; - sce->gm.recastData.agentradius = 0.6f; - sce->gm.recastData.edgemaxlen = 12.0f; - sce->gm.recastData.edgemaxerror = 1.3f; - sce->gm.recastData.regionminsize = 8.f; - sce->gm.recastData.regionmergesize = 20.f; - sce->gm.recastData.vertsperpoly = 6; - sce->gm.recastData.detailsampledist = 6.0f; - sce->gm.recastData.detailsamplemaxerror = 1.0f; - - sce->gm.lodflag = SCE_LOD_USE_HYST; - sce->gm.scehysteresis = 10; - - sce->gm.exitkey = 218; // Blender key code for ESC - BKE_sound_create_scene(sce); /* color management */ @@ -1605,11 +1550,6 @@ bool BKE_scene_uses_blender_internal(const Scene *scene) return BKE_viewrender_uses_blender_internal(&scene->view_render); } -bool BKE_scene_uses_blender_game(const Scene *scene) -{ - return BKE_viewrender_uses_blender_game(&scene->view_render); -} - bool BKE_scene_uses_blender_eevee(const Scene *scene) { return BKE_viewrender_uses_blender_eevee(&scene->view_render); @@ -1778,12 +1718,6 @@ bool BKE_viewrender_uses_blender_internal(const ViewRender *view_render) return STREQ(engine_id, RE_engine_id_BLENDER_RENDER); } -bool BKE_viewrender_uses_blender_game(const ViewRender *view_render) -{ - const char *engine_id = view_render->engine_id; - return STREQ(engine_id, RE_engine_id_BLENDER_GAME); -} - bool BKE_viewrender_uses_blender_eevee(const ViewRender *view_render) { const char *engine_id = view_render->engine_id; diff --git a/source/blender/blenkernel/intern/text.c b/source/blender/blenkernel/intern/text.c index b1ff2724375..3892b2f0546 100644 --- a/source/blender/blenkernel/intern/text.c +++ b/source/blender/blenkernel/intern/text.c @@ -47,8 +47,6 @@ #include "BLI_fileops.h" #include "DNA_constraint_types.h" -#include "DNA_controller_types.h" -#include "DNA_actuator_types.h" #include "DNA_scene_types.h" #include "DNA_screen_types.h" #include "DNA_space_types.h" diff --git a/source/blender/blenlib/BLI_callbacks.h b/source/blender/blenlib/BLI_callbacks.h index be53d1f603b..adc7bf5af6b 100644 --- a/source/blender/blenlib/BLI_callbacks.h +++ b/source/blender/blenlib/BLI_callbacks.h @@ -49,8 +49,6 @@ typedef enum { BLI_CB_EVT_LOAD_POST, BLI_CB_EVT_SAVE_PRE, BLI_CB_EVT_SAVE_POST, - BLI_CB_EVT_GAME_PRE, - BLI_CB_EVT_GAME_POST, BLI_CB_EVT_VERSION_UPDATE, BLI_CB_EVT_TOT } eCbEvent; diff --git a/source/blender/blenloader/intern/readfile.c b/source/blender/blenloader/intern/readfile.c index f2f5dd2d27b..dad9d92225f 100644 --- a/source/blender/blenloader/intern/readfile.c +++ b/source/blender/blenloader/intern/readfile.c @@ -61,12 +61,10 @@ #include "DNA_anim_types.h" #include "DNA_armature_types.h" -#include "DNA_actuator_types.h" #include "DNA_brush_types.h" #include "DNA_camera_types.h" #include "DNA_cachefile_types.h" #include "DNA_cloth_types.h" -#include "DNA_controller_types.h" #include "DNA_constraint_types.h" #include "DNA_dynamicpaint_types.h" #include "DNA_effect_types.h" @@ -91,12 +89,10 @@ #include "DNA_packedFile_types.h" #include "DNA_particle_types.h" #include "DNA_lightprobe_types.h" -#include "DNA_property_types.h" #include "DNA_rigidbody_types.h" #include "DNA_text_types.h" #include "DNA_view3d_types.h" #include "DNA_screen_types.h" -#include "DNA_sensor_types.h" #include "DNA_sdna_types.h" #include "DNA_scene_types.h" #include "DNA_sequence_types.h" @@ -152,7 +148,6 @@ #include "BKE_particle.h" #include "BKE_pointcache.h" #include "BKE_report.h" -#include "BKE_sca.h" // for init_actuator #include "BKE_scene.h" #include "BKE_screen.h" #include "BKE_sequencer.h" @@ -4980,144 +4975,7 @@ static void lib_link_object(FileData *fd, Main *main) paf->group = newlibadr_us(fd, ob->id.lib, paf->group); } } - - for (bSensor *sens = ob->sensors.first; sens; sens = sens->next) { - for (a = 0; a < sens->totlinks; a++) - sens->links[a] = newglobadr(fd, sens->links[a]); - if (sens->type == SENS_MESSAGE) { - bMessageSensor *ms = sens->data; - ms->fromObject = - newlibadr(fd, ob->id.lib, ms->fromObject); - } - } - - for (bController *cont = ob->controllers.first; cont; cont = cont->next) { - for (a=0; a < cont->totlinks; a++) - cont->links[a] = newglobadr(fd, cont->links[a]); - - if (cont->type == CONT_PYTHON) { - bPythonCont *pc = cont->data; - pc->text = newlibadr(fd, ob->id.lib, pc->text); - } - cont->slinks = NULL; - cont->totslinks = 0; - } - - for (bActuator *act = ob->actuators.first; act; act = act->next) { - switch (act->type) { - case ACT_SOUND: - { - bSoundActuator *sa = act->data; - sa->sound = newlibadr_us(fd, ob->id.lib, sa->sound); - break; - } - case ACT_GAME: - /* bGameActuator *ga= act->data; */ - break; - case ACT_CAMERA: - { - bCameraActuator *ca = act->data; - ca->ob = newlibadr(fd, ob->id.lib, ca->ob); - break; - } - /* leave this one, it's obsolete but necessary to read for conversion */ - case ACT_ADD_OBJECT: - { - bAddObjectActuator *eoa = act->data; - if (eoa) - eoa->ob = newlibadr(fd, ob->id.lib, eoa->ob); - break; - } - case ACT_OBJECT: - { - bObjectActuator *oa = act->data; - if (oa == NULL) { - init_actuator(act); - } - else { - oa->reference = newlibadr(fd, ob->id.lib, oa->reference); - } - break; - } - case ACT_EDIT_OBJECT: - { - bEditObjectActuator *eoa = act->data; - if (eoa == NULL) { - init_actuator(act); - } - else { - eoa->ob = newlibadr(fd, ob->id.lib, eoa->ob); - eoa->me = newlibadr(fd, ob->id.lib, eoa->me); - } - break; - } - case ACT_SCENE: - { - bSceneActuator *sa = act->data; - sa->camera = newlibadr(fd, ob->id.lib, sa->camera); - sa->scene = newlibadr(fd, ob->id.lib, sa->scene); - break; - } - case ACT_ACTION: - { - bActionActuator *aa = act->data; - aa->act = newlibadr_us(fd, ob->id.lib, aa->act); - break; - } - case ACT_SHAPEACTION: - { - bActionActuator *aa = act->data; - aa->act = newlibadr_us(fd, ob->id.lib, aa->act); - break; - } - case ACT_PROPERTY: - { - bPropertyActuator *pa = act->data; - pa->ob = newlibadr(fd, ob->id.lib, pa->ob); - break; - } - case ACT_MESSAGE: - { - bMessageActuator *ma = act->data; - ma->toObject = newlibadr(fd, ob->id.lib, ma->toObject); - break; - } - case ACT_2DFILTER: - { - bTwoDFilterActuator *_2dfa = act->data; - _2dfa->text = newlibadr(fd, ob->id.lib, _2dfa->text); - break; - } - case ACT_PARENT: - { - bParentActuator *parenta = act->data; - parenta->ob = newlibadr(fd, ob->id.lib, parenta->ob); - break; - } - case ACT_STATE: - /* bStateActuator *statea = act->data; */ - break; - case ACT_ARMATURE: - { - bArmatureActuator *arma= act->data; - arma->target = newlibadr(fd, ob->id.lib, arma->target); - arma->subtarget = newlibadr(fd, ob->id.lib, arma->subtarget); - break; - } - case ACT_STEERING: - { - bSteeringActuator *steeringa = act->data; - steeringa->target = newlibadr(fd, ob->id.lib, steeringa->target); - steeringa->navmesh = newlibadr(fd, ob->id.lib, steeringa->navmesh); - break; - } - case ACT_MOUSE: - /* bMouseActuator *moa = act->data; */ - break; - } - } - { FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim); @@ -5542,10 +5400,6 @@ static void direct_link_modifiers(FileData *fd, ListBase *lb) static void direct_link_object(FileData *fd, Object *ob) { PartEff *paf; - bProperty *prop; - bSensor *sens; - bController *cont; - bActuator *act; /* weak weak... this was only meant as draw flag, now is used in give_base_to_objects too */ ob->flag &= ~OB_FROMGROUP; @@ -5667,7 +5521,6 @@ static void direct_link_object(FileData *fd, Object *ob) direct_link_pointcache_list(fd, &sb->ptcaches, &sb->pointcache, 0); } - ob->bsoft = newdataadr(fd, ob->bsoft); ob->fluidsimSettings= newdataadr(fd, ob->fluidsimSettings); /* NT */ ob->rigidbody_object = newdataadr(fd, ob->rigidbody_object); @@ -5686,44 +5539,9 @@ static void direct_link_object(FileData *fd, Object *ob) link_list(fd, &ob->particlesystem); direct_link_particlesystems(fd, &ob->particlesystem); - - link_list(fd, &ob->prop); - for (prop = ob->prop.first; prop; prop = prop->next) { - prop->poin = newdataadr(fd, prop->poin); - if (prop->poin == NULL) - prop->poin = &prop->data; - } - - link_list(fd, &ob->sensors); - for (sens = ob->sensors.first; sens; sens = sens->next) { - sens->data = newdataadr(fd, sens->data); - sens->links = newdataadr(fd, sens->links); - test_pointer_array(fd, (void **)&sens->links); - } direct_link_constraints(fd, &ob->constraints); - link_glob_list(fd, &ob->controllers); - if (ob->init_state) { - /* if a known first state is specified, set it so that the game will start ok */ - ob->state = ob->init_state; - } - else if (!ob->state) { - ob->state = 1; - } - for (cont = ob->controllers.first; cont; cont = cont->next) { - cont->data = newdataadr(fd, cont->data); - cont->links = newdataadr(fd, cont->links); - test_pointer_array(fd, (void **)&cont->links); - if (cont->state_mask == 0) - cont->state_mask = 1; - } - - link_glob_list(fd, &ob->actuators); - for (act = ob->actuators.first; act; act = act->next) { - act->data = newdataadr(fd, act->data); - } - link_list(fd, &ob->hooks); while (ob->hooks.first) { ObHook *hook = ob->hooks.first; @@ -6042,9 +5860,6 @@ static void lib_link_scene(FileData *fd, Main *main) fls->group = newlibadr_us(fd, sce->id.lib, fls->group); } } - /*Game Settings: Dome Warp Text*/ - sce->gm.dome.warptext = newlibadr(fd, sce->id.lib, sce->gm.dome.warptext); - /* Motion Tracking */ sce->clip = newlibadr_us(fd, sce->id.lib, sce->clip); @@ -6664,7 +6479,7 @@ static void direct_link_area(FileData *fd, ScrArea *area) area->type = NULL; /* spacetype callbacks */ area->region_active_win = -1; - /* if we do not have the spacetype registered (game player), we cannot + /* if we do not have the spacetype registered we cannot * free it, so don't allocate any new memory for such spacetypes. */ if (!BKE_spacetype_exists(area->spacetype)) { area->spacetype = SPACE_EMPTY; @@ -6692,7 +6507,7 @@ static void direct_link_area(FileData *fd, ScrArea *area) for (sl = area->spacedata.first; sl; sl = sl->next) { link_list(fd, &(sl->regionbase)); - /* if we do not have the spacetype registered (game player), we cannot + /* if we do not have the spacetype registered we cannot * free it, so don't allocate any new memory for such spacetypes. */ if (!BKE_spacetype_exists(sl->spacetype)) sl->spacetype = SPACE_EMPTY; @@ -6810,15 +6625,6 @@ static void direct_link_area(FileData *fd, ScrArea *area) SpaceTime *stime = (SpaceTime *)sl; BLI_listbase_clear(&stime->caches); } - else if (sl->spacetype == SPACE_LOGIC) { - SpaceLogic *slogic = (SpaceLogic *)sl; - - /* XXX: this is new stuff, which shouldn't be directly linking to gpd... */ - if (slogic->gpd) { - slogic->gpd = newdataadr(fd, slogic->gpd); - direct_link_gpencil(fd, slogic->gpd); - } - } else if (sl->spacetype == SPACE_SEQ) { SpaceSeq *sseq = (SpaceSeq *)sl; @@ -7085,13 +6891,6 @@ static void lib_link_area(FileData *fd, bScreen *sc, ScrArea *area) sclip->mask_info.mask = newlibadr_real_us(fd, sc->id.lib, sclip->mask_info.mask); break; } - case SPACE_LOGIC: - { - SpaceLogic *slogic = (SpaceLogic *)sl; - - slogic->gpd = newlibadr_us(fd, sc->id.lib, slogic->gpd); - break; - } default: break; } @@ -7563,11 +7362,6 @@ static void lib_link_workspace_layout_restore(struct IDNameLib_Map *id_map, Main sclip->scopes.ok = 0; } - else if (sl->spacetype == SPACE_LOGIC) { - SpaceLogic *slogic = (SpaceLogic *)sl; - - slogic->gpd = restore_pointer_by_name(id_map, (ID *)slogic->gpd, USER_REAL); - } } } } @@ -9794,9 +9588,6 @@ static void expand_object_expandModifiers( static void expand_object(FileData *fd, Main *mainvar, Object *ob) { ParticleSystem *psys; - bSensor *sens; - bController *cont; - bActuator *act; bActionStrip *strip; PartEff *paf; int a; @@ -9853,84 +9644,6 @@ static void expand_object(FileData *fd, Main *mainvar, Object *ob) for (psys = ob->particlesystem.first; psys; psys = psys->next) expand_doit(fd, mainvar, psys->part); - for (sens = ob->sensors.first; sens; sens = sens->next) { - if (sens->type == SENS_MESSAGE) { - bMessageSensor *ms = sens->data; - expand_doit(fd, mainvar, ms->fromObject); - } - } - - for (cont = ob->controllers.first; cont; cont = cont->next) { - if (cont->type == CONT_PYTHON) { - bPythonCont *pc = cont->data; - expand_doit(fd, mainvar, pc->text); - } - } - - for (act = ob->actuators.first; act; act = act->next) { - if (act->type == ACT_SOUND) { - bSoundActuator *sa = act->data; - expand_doit(fd, mainvar, sa->sound); - } - else if (act->type == ACT_CAMERA) { - bCameraActuator *ca = act->data; - expand_doit(fd, mainvar, ca->ob); - } - else if (act->type == ACT_EDIT_OBJECT) { - bEditObjectActuator *eoa = act->data; - if (eoa) { - expand_doit(fd, mainvar, eoa->ob); - expand_doit(fd, mainvar, eoa->me); - } - } - else if (act->type == ACT_OBJECT) { - bObjectActuator *oa = act->data; - expand_doit(fd, mainvar, oa->reference); - } - else if (act->type == ACT_ADD_OBJECT) { - bAddObjectActuator *aoa = act->data; - expand_doit(fd, mainvar, aoa->ob); - } - else if (act->type == ACT_SCENE) { - bSceneActuator *sa = act->data; - expand_doit(fd, mainvar, sa->camera); - expand_doit(fd, mainvar, sa->scene); - } - else if (act->type == ACT_2DFILTER) { - bTwoDFilterActuator *tdfa = act->data; - expand_doit(fd, mainvar, tdfa->text); - } - else if (act->type == ACT_ACTION) { - bActionActuator *aa = act->data; - expand_doit(fd, mainvar, aa->act); - } - else if (act->type == ACT_SHAPEACTION) { - bActionActuator *aa = act->data; - expand_doit(fd, mainvar, aa->act); - } - else if (act->type == ACT_PROPERTY) { - bPropertyActuator *pa = act->data; - expand_doit(fd, mainvar, pa->ob); - } - else if (act->type == ACT_MESSAGE) { - bMessageActuator *ma = act->data; - expand_doit(fd, mainvar, ma->toObject); - } - else if (act->type==ACT_PARENT) { - bParentActuator *pa = act->data; - expand_doit(fd, mainvar, pa->ob); - } - else if (act->type == ACT_ARMATURE) { - bArmatureActuator *arma = act->data; - expand_doit(fd, mainvar, arma->target); - } - else if (act->type == ACT_STEERING) { - bSteeringActuator *sta = act->data; - expand_doit(fd, mainvar, sta->target); - expand_doit(fd, mainvar, sta->navmesh); - } - } - if (ob->pd) { expand_doit(fd, mainvar, ob->pd->tex); expand_doit(fd, mainvar, ob->pd->f_source); @@ -10040,9 +9753,6 @@ static void expand_scene(FileData *fd, Main *mainvar, Scene *sce) } } - if (sce->r.dometext) - expand_doit(fd, mainvar, sce->gm.dome.warptext); - if (sce->gpd) expand_doit(fd, mainvar, sce->gpd); diff --git a/source/blender/blenloader/intern/versioning_250.c b/source/blender/blenloader/intern/versioning_250.c index f5a4a33860f..e7f448f6a86 100644 --- a/source/blender/blenloader/intern/versioning_250.c +++ b/source/blender/blenloader/intern/versioning_250.c @@ -39,7 +39,6 @@ #include "DNA_anim_types.h" #include "DNA_armature_types.h" -#include "DNA_actuator_types.h" #include "DNA_brush_types.h" #include "DNA_camera_types.h" #include "DNA_cloth_types.h" @@ -84,7 +83,6 @@ #include "BKE_sequencer.h" #include "BKE_texture.h" #include "BKE_sound.h" -#include "BKE_sca.h" #include "NOD_socket.h" @@ -610,13 +608,7 @@ static void do_version_constraints_radians_degrees_250(ListBase *lb) bConstraint *con; for (con = lb->first; con; con = con->next) { - if (con->type == CONSTRAINT_TYPE_RIGIDBODYJOINT) { - bRigidBodyJointConstraint *data = con->data; - data->axX *= (float)(M_PI / 180.0); - data->axY *= (float)(M_PI / 180.0); - data->axZ *= (float)(M_PI / 180.0); - } - else if (con->type == CONSTRAINT_TYPE_KINEMATIC) { + if (con->type == CONSTRAINT_TYPE_KINEMATIC) { bKinematicConstraint *data = con->data; data->poleangle *= (float)(M_PI / 180.0); } @@ -750,7 +742,6 @@ void blo_do_versions_250(FileData *fd, Library *lib, Main *main) bSound *sound; Sequence *seq; - bActuator *act; int a; for (sound = main->sound.first; sound; sound = sound->id.next) { @@ -760,33 +751,6 @@ void blo_do_versions_250(FileData *fd, Library *lib, Main *main) } } - for (ob = main->object.first; ob; ob = ob->id.next) { - for (act = ob->actuators.first; act; act = act->next) { - if (act->type == ACT_SOUND) { - bSoundActuator *sAct = (bSoundActuator*) act->data; - if (sAct->sound) { - sound = blo_do_versions_newlibadr(fd, lib, sAct->sound); - sAct->flag = (sound->flags & SOUND_FLAGS_3D) ? ACT_SND_3D_SOUND : 0; - sAct->pitch = sound->pitch; - sAct->volume = sound->volume; - sAct->sound3D.reference_distance = sound->distance; - sAct->sound3D.max_gain = sound->max_gain; - sAct->sound3D.min_gain = sound->min_gain; - sAct->sound3D.rolloff_factor = sound->attenuation; - } - else { - sAct->sound3D.reference_distance = 1.0f; - sAct->volume = 1.0f; - sAct->sound3D.max_gain = 1.0f; - sAct->sound3D.rolloff_factor = 1.0f; - } - sAct->sound3D.cone_inner_angle = 360.0f; - sAct->sound3D.cone_outer_angle = 360.0f; - sAct->sound3D.max_distance = FLT_MAX; - } - } - } - for (scene = main->scene.first; scene; scene = scene->id.next) { if (scene->ed && scene->ed->seqbasep) { SEQ_BEGIN (scene->ed, seq) @@ -1034,93 +998,12 @@ void blo_do_versions_250(FileData *fd, Library *lib, Main *main) ts->uv_selectmode = UV_SELECT_VERTEX; ts->vgroup_weight = 1.0f; } - - /* Game Settings */ - /* Dome */ - sce->gm.dome.angle = sce->r.domeangle; - sce->gm.dome.mode = sce->r.domemode; - sce->gm.dome.res = sce->r.domeres; - sce->gm.dome.resbuf = sce->r.domeresbuf; - sce->gm.dome.tilt = sce->r.dometilt; - sce->gm.dome.warptext = sce->r.dometext; - - /* Stand Alone */ - sce->gm.playerflag |= (sce->r.fullscreen ? GAME_PLAYER_FULLSCREEN : 0); - sce->gm.xplay = sce->r.xplay; - sce->gm.yplay = sce->r.yplay; - sce->gm.freqplay = sce->r.freqplay; - sce->gm.depth = sce->r.depth; - sce->gm.attrib = sce->r.attrib; - - /* Stereo */ - sce->gm.stereomode = sce->r.stereomode; - /* reassigning stereomode NO_STEREO and DOME to a separeted flag*/ - if (sce->gm.stereomode == 1) { // 1 = STEREO_NOSTEREO - sce->gm.stereoflag = STEREO_NOSTEREO; - sce->gm.stereomode = STEREO_ANAGLYPH; - } - else if (sce->gm.stereomode == 8) { // 8 = STEREO_DOME - sce->gm.stereoflag = STEREO_DOME; - sce->gm.stereomode = STEREO_ANAGLYPH; - } - else - sce->gm.stereoflag = STEREO_ENABLED; - - /* Framing */ - sce->gm.framing = sce->framing; - sce->gm.xplay = sce->r.xplay; - sce->gm.yplay = sce->r.yplay; - sce->gm.freqplay = sce->r.freqplay; - sce->gm.depth = sce->r.depth; - - /* Physic (previously stored in world) */ - sce->gm.gravity =9.8f; - sce->gm.physicsEngine = WOPHY_BULLET; /* Bullet by default */ - sce->gm.mode = WO_DBVT_CULLING; /* DBVT culling by default */ - sce->gm.occlusionRes = 128; - sce->gm.ticrate = 60; - sce->gm.maxlogicstep = 5; - sce->gm.physubstep = 1; - sce->gm.maxphystep = 5; } } if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 2)) { - Scene *sce; Object *ob; - for (sce = main->scene.first; sce; sce = sce->id.next) { - if (fd->fileflags & G_FILE_ENABLE_ALL_FRAMES) - sce->gm.flag |= GAME_ENABLE_ALL_FRAMES; - if (fd->fileflags & G_FILE_SHOW_DEBUG_PROPS) - sce->gm.flag |= GAME_SHOW_DEBUG_PROPS; - if (fd->fileflags & G_FILE_SHOW_FRAMERATE) - sce->gm.flag |= GAME_SHOW_FRAMERATE; - if (fd->fileflags & G_FILE_SHOW_PHYSICS) - sce->gm.flag |= GAME_SHOW_PHYSICS; - if (fd->fileflags & G_FILE_GLSL_NO_SHADOWS) - sce->gm.flag |= GAME_GLSL_NO_SHADOWS; - if (fd->fileflags & G_FILE_GLSL_NO_SHADERS) - sce->gm.flag |= GAME_GLSL_NO_SHADERS; - if (fd->fileflags & G_FILE_GLSL_NO_RAMPS) - sce->gm.flag |= GAME_GLSL_NO_RAMPS; - if (fd->fileflags & G_FILE_GLSL_NO_NODES) - sce->gm.flag |= GAME_GLSL_NO_NODES; - if (fd->fileflags & G_FILE_GLSL_NO_EXTRA_TEX) - sce->gm.flag |= GAME_GLSL_NO_EXTRA_TEX; - if (fd->fileflags & G_FILE_GLSL_NO_ENV_LIGHTING) - sce->gm.flag |= GAME_GLSL_NO_ENV_LIGHTING; - if (fd->fileflags & G_FILE_IGNORE_DEPRECATION_WARNINGS) - sce->gm.flag |= GAME_IGNORE_DEPRECATION_WARNINGS; - - if (fd->fileflags & G_FILE_GAME_MAT_GLSL) - sce->gm.matmode = GAME_MAT_GLSL; - else if (fd->fileflags & G_FILE_GAME_MAT) - sce->gm.matmode = GAME_MAT_MULTITEX; - else - sce->gm.matmode = GAME_MAT_TEXFACE; - } - for (ob = main->object.first; ob; ob = ob->id.next) { if (ob->flag & 8192) // OB_POSEMODE = 8192 ob->mode |= OB_MODE_POSE; @@ -1565,16 +1448,10 @@ void blo_do_versions_250(FileData *fd, Library *lib, Main *main) } if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 12)) { - Scene *sce; Object *ob; Brush *brush; Material *ma; - /* game engine changes */ - for (sce = main->scene.first; sce; sce = sce->id.next) { - sce->gm.eyeseparation = 0.10f; - } - /* anim viz changes */ for (ob = main->object.first; ob; ob = ob->id.next) { /* initialize object defaults */ @@ -2195,7 +2072,6 @@ void blo_do_versions_250(FileData *fd, Library *lib, Main *main) Brush *br; ParticleSettings *part; bScreen *sc; - Object *ob; for (br = main->brush.first; br; br = br->id.next) { if (br->ob_mode == 0) @@ -2235,41 +2111,6 @@ void blo_do_versions_250(FileData *fd, Library *lib, Main *main) } } } - - /* fix rotation actuators for objects so they use real angles (radians) - * since before blender went opensource this strange scalar was used: (1 / 0.02) * 2 * math.pi/360 */ - for (ob = main->object.first; ob; ob = ob->id.next) { - bActuator *act = ob->actuators.first; - while (act) { - if (act->type == ACT_OBJECT) { - /* multiply velocity with 50 in old files */ - bObjectActuator *oa = act->data; - mul_v3_fl(oa->drot, 0.8726646259971648f); - } - act = act->next; - } - } - } - - /* init facing axis property of steering actuators */ - { - Object *ob; - for (ob = main->object.first; ob; ob = ob->id.next) { - bActuator *act; - for (act = ob->actuators.first; act; act = act->next) { - if (act->type == ACT_STEERING) { - bSteeringActuator *stact = act->data; - if (stact == NULL) {//HG1 - init_actuator(act); - } - else { - if (stact->facingaxis == 0) { - stact->facingaxis = 1; - } - } - } - } - } } if (main->versionfile < 255 || (main->versionfile == 255 && main->subversionfile < 3)) { @@ -2561,21 +2402,6 @@ void blo_do_versions_250(FileData *fd, Library *lib, Main *main) } } - { - /* add default value for behind strength of camera actuator */ - Object *ob; - bActuator *act; - for (ob = main->object.first; ob; ob = ob->id.next) { - for (act = ob->actuators.first; act; act = act->next) { - if (act->type == ACT_CAMERA) { - bCameraActuator *ba = act->data; - - ba->damping = 1.0/32.0; - } - } - } - } - { ParticleSettings *part; for (part = main->particle.first; part; part = part->id.next) { @@ -2667,50 +2493,6 @@ void blo_do_versions_250(FileData *fd, Library *lib, Main *main) } } } - - { - /* convert fcurve and shape action actuators to action actuators */ - Object *ob; - bActuator *act; - bIpoActuator *ia; - bActionActuator *aa; - - for (ob = main->object.first; ob; ob = ob->id.next) { - for (act = ob->actuators.first; act; act = act->next) { - if (act->type == ACT_IPO) { - /* Create the new actuator */ - ia = act->data; - aa = MEM_callocN(sizeof(bActionActuator), "fcurve -> action actuator do_version"); - - /* Copy values */ - aa->type = ia->type; - aa->flag = ia->flag; - aa->sta = ia->sta; - aa->end = ia->end; - BLI_strncpy(aa->name, ia->name, sizeof(aa->name)); - BLI_strncpy(aa->frameProp, ia->frameProp, sizeof(aa->frameProp)); - if (ob->adt) - aa->act = ob->adt->action; - - /* Get rid of the old actuator */ - MEM_freeN(ia); - - /* Assign the new actuator */ - act->data = aa; - act->type = act->otype = ACT_ACTION; - - /* Fix for converting 2.4x files: if we don't have an action, but we have an - * object IPO, then leave the actuator as an IPO actuator for now and let the - * IPO conversion code handle it */ - if (ob->ipo && !aa->act) - act->type = ACT_IPO; - } - else if (act->type == ACT_SHAPEACTION) { - act->type = act->otype = ACT_ACTION; - } - } - } - } } if (main->versionfile < 259 || (main->versionfile == 259 && main->subversionfile < 2)) { @@ -2758,41 +2540,5 @@ void blo_do_versions_250(FileData *fd, Library *lib, Main *main) part->time_flag &= ~PART_TIME_AUTOSF; } } - - { - /* set defaults for obstacle avoidance, recast data */ - Scene *sce; - for (sce = main->scene.first; sce; sce = sce->id.next) { - if (sce->gm.levelHeight == 0.f) - sce->gm.levelHeight = 2.f; - - if (sce->gm.recastData.cellsize == 0.0f) - sce->gm.recastData.cellsize = 0.3f; - if (sce->gm.recastData.cellheight == 0.0f) - sce->gm.recastData.cellheight = 0.2f; - if (sce->gm.recastData.agentmaxslope == 0.0f) - sce->gm.recastData.agentmaxslope = (float)M_PI/4; - if (sce->gm.recastData.agentmaxclimb == 0.0f) - sce->gm.recastData.agentmaxclimb = 0.9f; - if (sce->gm.recastData.agentheight == 0.0f) - sce->gm.recastData.agentheight = 2.0f; - if (sce->gm.recastData.agentradius == 0.0f) - sce->gm.recastData.agentradius = 0.6f; - if (sce->gm.recastData.edgemaxlen == 0.0f) - sce->gm.recastData.edgemaxlen = 12.0f; - if (sce->gm.recastData.edgemaxerror == 0.0f) - sce->gm.recastData.edgemaxerror = 1.3f; - if (sce->gm.recastData.regionminsize == 0.0f) - sce->gm.recastData.regionminsize = 8.f; - if (sce->gm.recastData.regionmergesize == 0.0f) - sce->gm.recastData.regionmergesize = 20.f; - if (sce->gm.recastData.vertsperpoly<3) - sce->gm.recastData.vertsperpoly = 6; - if (sce->gm.recastData.detailsampledist == 0.0f) - sce->gm.recastData.detailsampledist = 6.0f; - if (sce->gm.recastData.detailsamplemaxerror == 0.0f) - sce->gm.recastData.detailsamplemaxerror = 1.0f; - } - } } } diff --git a/source/blender/blenloader/intern/versioning_260.c b/source/blender/blenloader/intern/versioning_260.c index 023bd7fe809..89577c7b7d1 100644 --- a/source/blender/blenloader/intern/versioning_260.c +++ b/source/blender/blenloader/intern/versioning_260.c @@ -31,7 +31,6 @@ #define DNA_DEPRECATED_ALLOW #include "DNA_anim_types.h" -#include "DNA_actuator_types.h" #include "DNA_brush_types.h" #include "DNA_camera_types.h" #include "DNA_cloth_types.h" @@ -43,11 +42,9 @@ #include "DNA_meshdata_types.h" #include "DNA_object_fluidsim_types.h" #include "DNA_object_types.h" -#include "DNA_property_types.h" #include "DNA_text_types.h" #include "DNA_view3d_types.h" #include "DNA_screen_types.h" -#include "DNA_sensor_types.h" #include "DNA_sdna_types.h" #include "DNA_smoke_types.h" #include "DNA_space_types.h" @@ -67,7 +64,6 @@ #include "BKE_modifier.h" #include "BKE_particle.h" #include "BKE_pointcache.h" -#include "BKE_property.h" // for BKE_bproperty_object_get #include "BKE_scene.h" #include "BKE_screen.h" #include "BKE_sequencer.h" @@ -432,25 +428,6 @@ static void do_versions_nodetree_frame_2_64_6(bNodeTree *ntree) } } -static void do_version_logic_264(ListBase *regionbase) -{ - ARegion *ar; - - /* view settings for logic changed */ - for (ar = regionbase->first; ar; ar = ar->next) { - if (ar->regiontype == RGN_TYPE_WINDOW) { - if (ar->v2d.keeptot == 0) { - ar->v2d.maxzoom = 1.5f; - - ar->v2d.keepzoom = V2D_KEEPZOOM | V2D_LIMITZOOM | V2D_KEEPASPECT; - ar->v2d.keeptot = V2D_KEEPTOT_BOUNDS; - ar->v2d.align = V2D_ALIGN_NO_POS_Y | V2D_ALIGN_NO_NEG_X; - ar->v2d.keepofs = V2D_KEEPOFS_Y; - } - } - } -} - static void do_versions_affine_tracker_track(MovieTrackingTrack *track) { int i; @@ -899,14 +876,6 @@ void blo_do_versions_260(FileData *fd, Library *UNUSED(lib), Main *main) do_versions_nodetree_socket_use_flags_2_62(ntree); } } - { - /* Initialize BGE exit key to esc key */ - Scene *scene; - for (scene = main->scene.first; scene; scene = scene->id.next) { - if (!scene->gm.exitkey) - scene->gm.exitkey = 218; // Blender key code for ESC - } - } { MovieClip *clip; Object *ob; @@ -943,44 +912,9 @@ void blo_do_versions_260(FileData *fd, Library *UNUSED(lib), Main *main) } } } - { - /* Warn the user if he is using ["Text"] properties for Font objects */ - Object *ob; - bProperty *prop; - - for (ob = main->object.first; ob; ob = ob->id.next) { - if (ob->type == OB_FONT) { - prop = BKE_bproperty_object_get(ob, "Text"); - if (prop) { - blo_reportf_wrap(fd->reports, RPT_WARNING, - TIP_("Game property name conflict in object '%s': text objects reserve the " - "['Text'] game property to change their content through logic bricks"), - ob->id.name + 2); - } - } - } - } } if (main->versionfile < 261 || (main->versionfile == 261 && main->subversionfile < 2)) { - { - /* convert Camera Actuator values to defines */ - Object *ob; - bActuator *act; - for (ob = main->object.first; ob; ob = ob->id.next) { - for (act = ob->actuators.first; act; act = act->next) { - if (act->type == ACT_CAMERA) { - bCameraActuator *ba = act->data; - - if (ba->axis == (float) 'x') ba->axis = OB_POSX; - else if (ba->axis == (float)'y') ba->axis = OB_POSY; - /* don't do an if/else to avoid imediate subversion bump*/ -// ba->axis=((ba->axis == (float)'x') ? OB_POSX_X : OB_POSY); - } - } - } - } - { /* convert deprecated sculpt_paint_unified_* fields to * UnifiedPaintSettings */ @@ -1316,19 +1250,6 @@ void blo_do_versions_260(FileData *fd, Library *UNUSED(lib), Main *main) } } - - if (main->versionfile < 263 || (main->versionfile == 263 && main->subversionfile < 8)) { - /* set new deactivation values for game settings */ - Scene *sce; - - for (sce = main->scene.first; sce; sce = sce->id.next) { - /* Game Settings */ - sce->gm.lineardeactthreshold = 0.8f; - sce->gm.angulardeactthreshold = 1.0f; - sce->gm.deactivationtime = 2.0f; - } - } - if (main->versionfile < 263 || (main->versionfile == 263 && main->subversionfile < 9)) { FOREACH_NODETREE(main, ntree, id) { if (ntree->type == NTREE_SHADER) { @@ -1738,24 +1659,6 @@ void blo_do_versions_260(FileData *fd, Library *UNUSED(lib), Main *main) } FOREACH_NODETREE_END } - if (main->versionfile < 264 || (main->versionfile == 264 && main->subversionfile < 6)) { - bScreen *sc; - - for (sc = main->screen.first; sc; sc = sc->id.next) { - ScrArea *sa; - for (sa = sc->areabase.first; sa; sa = sa->next) { - SpaceLink *sl; - if ( sa->spacetype == SPACE_LOGIC) - do_version_logic_264(&sa->regionbase); - - for (sl = sa->spacedata.first; sl; sl = sl->next) { - if (sl->spacetype == SPACE_LOGIC) - do_version_logic_264(&sl->regionbase); - } - } - } - } - if (main->versionfile < 264 || (main->versionfile == 264 && main->subversionfile < 7)) { /* convert tiles size from resolution and number of tiles */ { @@ -1809,17 +1712,6 @@ void blo_do_versions_260(FileData *fd, Library *UNUSED(lib), Main *main) } } - if (main->versionfile < 265) { - Object *ob; - for (ob = main->object.first; ob; ob = ob->id.next) { - if (ob->step_height == 0.0f) { - ob->step_height = 0.15f; - ob->jump_speed = 10.0f; - ob->fall_speed = 55.0f; - } - } - } - if (main->versionfile < 265 || (main->versionfile == 265 && main->subversionfile < 3)) { bScreen *sc; for (sc = main->screen.first; sc; sc = sc->id.next) { @@ -2335,32 +2227,6 @@ void blo_do_versions_260(FileData *fd, Library *UNUSED(lib), Main *main) } } } - - for (ob = main->object.first; ob; ob = ob->id.next) { - bSensor *sens; - bTouchSensor *ts; - bCollisionSensor *cs; - Material *ma; - - for (sens = ob->sensors.first; sens; sens = sens->next) { - if (sens->type == SENS_TOUCH) { - ts = sens->data; - cs = MEM_callocN(sizeof(bCollisionSensor), "touch -> collision sensor do_version"); - - if (ts->ma) { - ma = blo_do_versions_newlibadr(fd, ob->id.lib, ts->ma); - BLI_strncpy(cs->materialName, ma->id.name + 2, sizeof(cs->materialName)); - } - - cs->mode = SENS_COLLISION_MATERIAL; - - MEM_freeN(ts); - - sens->data = cs; - sens->type = sens->otype = SENS_COLLISION; - } - } - } } if (!MAIN_VERSION_ATLEAST(main, 268, 5)) { @@ -2514,10 +2380,6 @@ void blo_do_versions_260(FileData *fd, Library *UNUSED(lib), Main *main) if (ts->sculpt) ts->sculpt->flags |= SCULPT_DYNTOPO_SUBDIVIDE; - /* single texture mode removed from game engine */ - if (scene->gm.matmode == GAME_MAT_TEXFACE) - scene->gm.matmode = GAME_MAT_MULTITEX; - /* 'Increment' mode disabled for nodes, use true grid snapping instead */ if (scene->toolsettings->snap_node_mode == SCE_SNAP_MODE_INCREMENT) scene->toolsettings->snap_node_mode = SCE_SNAP_MODE_GRID; @@ -2544,8 +2406,6 @@ void blo_do_versions_260(FileData *fd, Library *UNUSED(lib), Main *main) for (ob = main->object.first; ob; ob = ob->id.next) { ModifierData *md; - bSensor *bs; - bActuator *ba; for (md = ob->modifiers.first; md; md = md->next) { if (md->type == eModifierType_EdgeSplit) { @@ -2557,28 +2417,6 @@ void blo_do_versions_260(FileData *fd, Library *UNUSED(lib), Main *main) bmd->bevel_angle = DEG2RADF(bmd->bevel_angle); } } - - for (bs = ob->sensors.first; bs; bs = bs->next) { - if (bs->type == SENS_RADAR) { - bRadarSensor *brs = bs->data; - brs->angle = DEG2RADF(brs->angle); - } - } - - for (ba = ob->actuators.first; ba; ba = ba->next) { - if (ba->type == ACT_CONSTRAINT) { - bConstraintActuator *bca = ba->data; - if (bca->type == ACT_CONST_TYPE_ORI) { - bca->minloc[0] = DEG2RADF(bca->minloc[0]); - bca->maxloc[0] = DEG2RADF(bca->maxloc[0]); - } - } - else if (ba->type == ACT_SOUND) { - bSoundActuator *bsa = ba->data; - bsa->sound3D.cone_outer_angle = DEG2RADF(bsa->sound3D.cone_outer_angle); - bsa->sound3D.cone_inner_angle = DEG2RADF(bsa->sound3D.cone_inner_angle); - } - } } for (scene = main->scene.first; scene; scene = scene->id.next) { diff --git a/source/blender/blenloader/intern/versioning_270.c b/source/blender/blenloader/intern/versioning_270.c index 7228c3522f0..e72ed9a41fd 100644 --- a/source/blender/blenloader/intern/versioning_270.c +++ b/source/blender/blenloader/intern/versioning_270.c @@ -52,7 +52,6 @@ #include "DNA_modifier_types.h" #include "DNA_particle_types.h" #include "DNA_linestyle_types.h" -#include "DNA_actuator_types.h" #include "DNA_view3d_types.h" #include "DNA_smoke_types.h" #include "DNA_rigidbody_types.h" @@ -554,29 +553,6 @@ void blo_do_versions_270(FileData *fd, Library *UNUSED(lib), Main *main) } } - if (!MAIN_VERSION_ATLEAST(main, 271, 2)) { - /* init up & track axis property of trackto actuators */ - Object *ob; - - for (ob = main->object.first; ob; ob = ob->id.next) { - bActuator *act; - for (act = ob->actuators.first; act; act = act->next) { - if (act->type == ACT_EDIT_OBJECT) { - bEditObjectActuator *eoact = act->data; - eoact->trackflag = ob->trackflag; - /* if trackflag is pointing +-Z axis then upflag should point Y axis. - * Rest of trackflag cases, upflag should be point z axis */ - if ((ob->trackflag == OB_POSZ) || (ob->trackflag == OB_NEGZ)) { - eoact->upflag = 1; - } - else { - eoact->upflag = 2; - } - } - } - } - } - if (!MAIN_VERSION_ATLEAST(main, 271, 3)) { Brush *br; @@ -857,13 +833,6 @@ void blo_do_versions_270(FileData *fd, Library *UNUSED(lib), Main *main) } } } - - if (!DNA_struct_elem_find(fd->filesdna, "GameData", "int", "scehysteresis")) { - Scene *scene; - for (scene = main->scene.first; scene; scene = scene->id.next) { - scene->gm.scehysteresis = 10; - } - } } if (!MAIN_VERSION_ATLEAST(main, 274, 2)) { @@ -1092,16 +1061,6 @@ void blo_do_versions_270(FileData *fd, Library *UNUSED(lib), Main *main) } #undef LA_YF_PHOTON } - - { - Object *ob; - for (ob = main->object.first; ob; ob = ob->id.next) { - if (ob->body_type == OB_BODY_TYPE_CHARACTER && (ob->gameflag & OB_BOUNDS) && ob->collision_boundtype == OB_BOUND_TRIANGLE_MESH) { - ob->boundtype = ob->collision_boundtype = OB_BOUND_BOX; - } - } - } - } if (!MAIN_VERSION_ATLEAST(main, 276, 3)) { @@ -1212,12 +1171,6 @@ void blo_do_versions_270(FileData *fd, Library *UNUSED(lib), Main *main) else gpd->flag &= ~GP_DATA_SHOW_ONIONSKINS; } - - if (!DNA_struct_elem_find(fd->filesdna, "Object", "unsigned char", "max_jumps")) { - for (Object *ob = main->object.first; ob; ob = ob->id.next) { - ob->max_jumps = 1; - } - } } if (!MAIN_VERSION_ATLEAST(main, 276, 5)) { ListBase *lbarray[MAX_LIBARRAY]; diff --git a/source/blender/blenloader/intern/versioning_280.c b/source/blender/blenloader/intern/versioning_280.c index 50b7f736a67..71074aef9b6 100644 --- a/source/blender/blenloader/intern/versioning_280.c +++ b/source/blender/blenloader/intern/versioning_280.c @@ -38,6 +38,7 @@ #include "DNA_object_types.h" #include "DNA_camera_types.h" +#include "DNA_constraint_types.h" #include "DNA_gpu_types.h" #include "DNA_group_types.h" #include "DNA_lamp_types.h" @@ -53,6 +54,7 @@ #include "DNA_workspace_types.h" #include "BKE_collection.h" +#include "BKE_constraint.h" #include "BKE_customdata.h" #include "BKE_freestyle.h" #include "BKE_group.h" @@ -314,7 +316,7 @@ void do_versions_after_linking_280(Main *main) scene->active_view_layer = 0; /* Handle legacy render layers. */ - if (!BKE_scene_uses_blender_game(scene)) { + { for (SceneRenderLayer *srl = scene->r.layers.first; srl; srl = srl->next) { ViewLayer *view_layer = BKE_view_layer_add(scene, srl->name); @@ -419,15 +421,6 @@ void do_versions_after_linking_280(Main *main) scene->active_view_layer = scene->r.actlay; } } - else { - for (SceneRenderLayer *srl = scene->r.layers.first; srl; srl = srl->next) { - if (srl->prop) { - IDP_FreeProperty(srl->prop); - MEM_freeN(srl->prop); - } - BKE_freestyle_config_free(&srl->freestyleConfig, true); - } - } BLI_freelistN(&scene->r.layers); ViewLayer *view_layer = BKE_view_layer_add(scene, "Viewport"); @@ -900,7 +893,7 @@ void blo_do_versions_280(FileData *fd, Library *UNUSED(lib), Main *main) } } - { + if (!MAIN_VERSION_ATLEAST(main, 280, 6)) { if (DNA_struct_elem_find(fd->filesdna, "SpaceOops", "int", "filter") == false) { bScreen *sc; ScrArea *sa; @@ -932,11 +925,27 @@ void blo_do_versions_280(FileData *fd, Library *UNUSED(lib), Main *main) } } - { + if (!MAIN_VERSION_ATLEAST(main, 280, 6)) { if (!DNA_struct_elem_find(fd->filesdna, "LightProbe", "float", "intensity")) { for (LightProbe *probe = main->lightprobe.first; probe; probe = probe->id.next) { probe->intensity = 1.0f; } } } + + if (!MAIN_VERSION_ATLEAST(main, 280, 6)) { + for (Object *ob = main->object.first; ob; ob = ob->id.next) { + bConstraint *con, *con_next; + con = ob->constraints.first; + while (con) { + con_next = con->next; + if (con->type == 17) { /* CONSTRAINT_TYPE_RIGIDBODYJOINT */ + BLI_remlink(&ob->constraints, con); + BKE_constraint_free_data(con); + MEM_freeN(con); + } + con = con_next; + } + } + } } diff --git a/source/blender/blenloader/intern/versioning_defaults.c b/source/blender/blenloader/intern/versioning_defaults.c index b09c7d77e59..74becdc67da 100644 --- a/source/blender/blenloader/intern/versioning_defaults.c +++ b/source/blender/blenloader/intern/versioning_defaults.c @@ -210,9 +210,6 @@ void BLO_update_defaults_startup_blend(Main *bmain) pset->brush[PE_BRUSH_CUT].strength = 1.0f; } - scene->gm.lodflag |= SCE_LOD_USE_HYST; - scene->gm.scehysteresis = 10; - scene->r.ffcodecdata.audio_mixrate = 48000; } diff --git a/source/blender/blenloader/intern/versioning_legacy.c b/source/blender/blenloader/intern/versioning_legacy.c index b8744b71812..b1b24b8d0e6 100644 --- a/source/blender/blenloader/intern/versioning_legacy.c +++ b/source/blender/blenloader/intern/versioning_legacy.c @@ -45,7 +45,6 @@ #define DNA_DEPRECATED_ALLOW #include "DNA_armature_types.h" -#include "DNA_actuator_types.h" #include "DNA_camera_types.h" #include "DNA_constraint_types.h" #include "DNA_effect_types.h" @@ -60,10 +59,8 @@ #include "DNA_node_types.h" #include "DNA_object_fluidsim_types.h" #include "DNA_object_types.h" -#include "DNA_property_types.h" #include "DNA_view3d_types.h" #include "DNA_screen_types.h" -#include "DNA_sensor_types.h" #include "DNA_sdna_types.h" #include "DNA_sequence_types.h" #include "DNA_sound_types.h" @@ -90,7 +87,6 @@ #include "BKE_modifier.h" #include "BKE_particle.h" #include "BKE_pointcache.h" -#include "BKE_property.h" // for BKE_bproperty_object_get #include "BKE_scene.h" #include "BKE_sequencer.h" @@ -128,38 +124,6 @@ static void vcol_to_fcol(Mesh *me) me->mcol = (MCol *)mcolmain; } -static int map_223_keybd_code_to_224_keybd_code(int code) -{ - switch (code) { - case 312: - return 311; /* F12KEY */ - case 159: - return 161; /* PADSLASHKEY */ - case 161: - return 150; /* PAD0 */ - case 154: - return 151; /* PAD1 */ - case 150: - return 152; /* PAD2 */ - case 155: - return 153; /* PAD3 */ - case 151: - return 154; /* PAD4 */ - case 156: - return 155; /* PAD5 */ - case 152: - return 156; /* PAD6 */ - case 157: - return 157; /* PAD7 */ - case 153: - return 158; /* PAD8 */ - case 158: - return 159; /* PAD9 */ - default: - return code; - } -} - static void do_version_bone_head_tail_237(Bone *bone) { Bone *child; @@ -833,7 +797,6 @@ void blo_do_versions_pre250(FileData *fd, Library *lib, Main *main) } if (main->versionfile <= 191) { - Object *ob = main->object.first; Material *ma = main->mat.first; /* let faces have default add factor of 0.0 */ @@ -842,121 +805,10 @@ void blo_do_versions_pre250(FileData *fd, Library *lib, Main *main) ma->add = 0.0; ma = ma->id.next; } - - while (ob) { - ob->mass = 1.0f; - ob->damping = 0.1f; - /*ob->quat[1] = 1.0f;*/ /* quats arnt used yet */ - ob = ob->id.next; - } - } - - if (main->versionfile <= 193) { - Object *ob = main->object.first; - while (ob) { - ob->inertia = 1.0f; - ob->rdamping = 0.1f; - ob = ob->id.next; - } - } - - if (main->versionfile <= 200) { - Object *ob = main->object.first; - while (ob) { - ob->scaflag = ob->gameflag & (OB_DO_FH|OB_ROT_FH|OB_ANISOTROPIC_FRICTION|OB_GHOST|OB_RIGID_BODY|OB_BOUNDS); - /* 64 is do_fh */ - ob->gameflag &= ~(OB_ROT_FH|OB_ANISOTROPIC_FRICTION|OB_GHOST|OB_RIGID_BODY|OB_BOUNDS); - ob = ob->id.next; - } - } - - if (main->versionfile <= 201) { - /* add-object + end-object are joined to edit-object actuator */ - Object *ob = main->object.first; - bProperty *prop; - bActuator *act; - bIpoActuator *ia; - bEditObjectActuator *eoa; - bAddObjectActuator *aoa; - while (ob) { - act = ob->actuators.first; - while (act) { - if (act->type == ACT_IPO) { - ia = act->data; - prop = BKE_bproperty_object_get(ob, ia->name); - if (prop) { - ia->type = ACT_IPO_FROM_PROP; - } - } - else if (act->type == ACT_ADD_OBJECT) { - aoa = act->data; - eoa = MEM_callocN(sizeof(bEditObjectActuator), "edit ob act"); - eoa->type = ACT_EDOB_ADD_OBJECT; - eoa->ob = aoa->ob; - eoa->time = aoa->time; - MEM_freeN(aoa); - act->data = eoa; - act->type = act->otype = ACT_EDIT_OBJECT; - } - else if (act->type == ACT_END_OBJECT) { - eoa = MEM_callocN(sizeof(bEditObjectActuator), "edit ob act"); - eoa->type = ACT_EDOB_END_OBJECT; - act->data = eoa; - act->type = act->otype = ACT_EDIT_OBJECT; - } - act = act->next; - } - ob = ob->id.next; - } - } - - if (main->versionfile <= 202) { - /* add-object and end-object are joined to edit-object - * actuator */ - Object *ob = main->object.first; - bActuator *act; - bObjectActuator *oa; - while (ob) { - act = ob->actuators.first; - while (act) { - if (act->type == ACT_OBJECT) { - oa = act->data; - oa->flag &= ~(ACT_TORQUE_LOCAL|ACT_DROT_LOCAL); /* this actuator didn't do local/glob rot before */ - } - act = act->next; - } - ob = ob->id.next; - } } if (main->versionfile <= 204) { - /* patches for new physics */ - Object *ob = main->object.first; - bActuator *act; - bObjectActuator *oa; bSound *sound; - while (ob) { - - /* please check this for demo20 files like - * original Egypt levels etc. converted - * rotation factor of 50 is not workable */ - act = ob->actuators.first; - while (act) { - if (act->type == ACT_OBJECT) { - oa = act->data; - - oa->forceloc[0] *= 25.0f; - oa->forceloc[1] *= 25.0f; - oa->forceloc[2] *= 25.0f; - - oa->forcerot[0] *= 10.0f; - oa->forcerot[1] *= 10.0f; - oa->forcerot[2] *= 10.0f; - } - act = act->next; - } - ob = ob->id.next; - } sound = main->sound.first; while (sound) { @@ -967,120 +819,8 @@ void blo_do_versions_pre250(FileData *fd, Library *lib, Main *main) } } - if (main->versionfile <= 205) { - /* patches for new physics */ - Object *ob = main->object.first; - bActuator *act; - bSensor *sens; - bEditObjectActuator *oa; - bRaySensor *rs; - bCollisionSensor *cs; - while (ob) { - /* Set anisotropic friction off for old objects, - * values to 1.0. */ - ob->gameflag &= ~OB_ANISOTROPIC_FRICTION; - ob->anisotropicFriction[0] = 1.0; - ob->anisotropicFriction[1] = 1.0; - ob->anisotropicFriction[2] = 1.0; - - act = ob->actuators.first; - while (act) { - if (act->type == ACT_EDIT_OBJECT) { - /* Zero initial velocity for newly - * added objects */ - oa = act->data; - oa->linVelocity[0] = 0.0; - oa->linVelocity[1] = 0.0; - oa->linVelocity[2] = 0.0; - oa->localflag = 0; - } - act = act->next; - } - - sens = ob->sensors.first; - while (sens) { - /* Extra fields for radar sensors. */ - if (sens->type == SENS_RADAR) { - bRadarSensor *s = sens->data; - s->range = 10000.0; - } - - /* Pulsing: defaults for new sensors. */ - if (sens->type != SENS_ALWAYS) { - sens->pulse = 0; - sens->freq = 0; - } - else { - sens->pulse = 1; - } - - /* Invert: off. */ - sens->invert = 0; - - /* Collision and ray: default = trigger - * on property. The material field can - * remain empty. */ - if (sens->type == SENS_COLLISION) { - cs = (bCollisionSensor*) sens->data; - cs->mode = 0; - } - if (sens->type == SENS_RAY) { - rs = (bRaySensor*) sens->data; - rs->mode = 0; - } - sens = sens->next; - } - ob = ob->id.next; - } - /* have to check the exact multiplier */ - } - - if (main->versionfile <= 211) { - /* Render setting: per scene, the applicable gamma value - * can be set. Default is 1.0, which means no - * correction. */ - bActuator *act; - bObjectActuator *oa; - Object *ob; - - /* added alpha in obcolor */ - ob = main->object.first; - while (ob) { - ob->col[3] = 1.0; - ob = ob->id.next; - } - - /* added alpha in obcolor */ - ob = main->object.first; - while (ob) { - act = ob->actuators.first; - while (act) { - if (act->type == ACT_OBJECT) { - /* multiply velocity with 50 in old files */ - oa = act->data; - if (fabsf(oa->linearvelocity[0]) >= 0.01f) - oa->linearvelocity[0] *= 50.0f; - if (fabsf(oa->linearvelocity[1]) >= 0.01f) - oa->linearvelocity[1] *= 50.0f; - if (fabsf(oa->linearvelocity[2]) >= 0.01f) - oa->linearvelocity[2] *= 50.0f; - if (fabsf(oa->angularvelocity[0]) >= 0.01f) - oa->angularvelocity[0] *= 50.0f; - if (fabsf(oa->angularvelocity[1]) >= 0.01f) - oa->angularvelocity[1] *= 50.0f; - if (fabsf(oa->angularvelocity[2]) >= 0.01f) - oa->angularvelocity[2] *= 50.0f; - } - act = act->next; - } - ob = ob->id.next; - } - } - if (main->versionfile <= 212) { bSound *sound; - bProperty *prop; - Object *ob; Mesh *me; sound = main->sound.first; @@ -1097,21 +837,6 @@ void blo_do_versions_pre250(FileData *fd, Library *lib, Main *main) sound = sound->id.next; } - ob = main->object.first; - - while (ob) { - prop = ob->prop.first; - while (prop) { - if (prop->type == GPROP_TIME) { - // convert old GPROP_TIME values from int to float - *((float *)&prop->data) = (float) prop->data; - } - - prop = prop->next; - } - ob = ob->id.next; - } - /* me->subdiv changed to reflect the actual reparametization * better, and smeshes were removed - if it was a smesh make * it a subsurf, and reset the subdiv level because subsurf @@ -1134,29 +859,8 @@ void blo_do_versions_pre250(FileData *fd, Library *lib, Main *main) } if (main->versionfile <= 220) { - Object *ob; Mesh *me; - ob = main->object.first; - - /* adapt form factor in order to get the 'old' physics - * behavior back... - */ - - while (ob) { - /* in future, distinguish between different - * object bounding shapes - */ - ob->formfactor = 0.4f; - /* patch form factor, note that inertia equiv radius - * of a rotation symmetrical obj - */ - if (ob->inertia != 1.0f) { - ob->formfactor /= ob->inertia * ob->inertia; - } - ob = ob->id.next; - } - /* Began using alpha component of vertex colors, but * old file vertex colors are undefined, reset them * to be fully opaque. -zr @@ -1214,7 +918,6 @@ void blo_do_versions_pre250(FileData *fd, Library *lib, Main *main) if (main->versionfile <= 223) { VFont *vf; Image *ima; - Object *ob; for (vf = main->vfont.first; vf; vf = vf->id.next) { if (STREQ(vf->name + strlen(vf->name) - 6, ".Bfont")) { @@ -1226,21 +929,6 @@ void blo_do_versions_pre250(FileData *fd, Library *lib, Main *main) for (ima = main->image.first; ima; ima = ima->id.next) { ima->animspeed = 25; } - - /* Zr remapped some keyboard codes to be linear (stupid zr) */ - for (ob = main->object.first; ob; ob = ob->id.next) { - bSensor *sens; - - for (sens = ob->sensors.first; sens; sens = sens->next) { - if (sens->type == SENS_KEYBOARD) { - bKeyboardSensor *ks = sens->data; - - ks->key = map_223_keybd_code_to_224_keybd_code(ks->key); - ks->qual = map_223_keybd_code_to_224_keybd_code(ks->qual); - ks->qual2 = map_223_keybd_code_to_224_keybd_code(ks->qual2); - } - } - } } if (main->versionfile <= 224) { @@ -1284,14 +972,6 @@ void blo_do_versions_pre250(FileData *fd, Library *lib, Main *main) } } - if (main->versionfile <= 225) { - World *wo; - /* Use Sumo for old games */ - for (wo = main->world.first; wo; wo = wo->id.next) { - wo->physicsEngine = 2; - } - } - if (main->versionfile <= 227) { Scene *sce; Material *ma; @@ -1469,9 +1149,6 @@ void blo_do_versions_pre250(FileData *fd, Library *lib, Main *main) sbuts->mainb = CONTEXT_SCENE; //sbuts->tab[CONTEXT_SCENE] = TAB_SCENE_RENDER; } - else if (sbuts->mainb == BUTS_GAME) { - sbuts->mainb = CONTEXT_LOGIC; - } else if (sbuts->mainb == BUTS_FPAINT) { sbuts->mainb = CONTEXT_EDITING; } @@ -1729,15 +1406,8 @@ void blo_do_versions_pre250(FileData *fd, Library *lib, Main *main) } if (main->versionfile <= 234) { - World *wo; bScreen *sc; - /* force sumo engine to be active */ - for (wo = main->world.first; wo; wo = wo->id.next) { - if (wo->physicsEngine == 0) - wo->physicsEngine = 2; - } - for (sc = main->screen.first; sc; sc = sc->id.next) { ScrArea *sa; for (sa = sc->areabase.first; sa; sa = sa->next) { @@ -2122,10 +1792,6 @@ void blo_do_versions_pre250(FileData *fd, Library *lib, Main *main) bNodeTree *ntree; for (wo = main->world.first; wo; wo = wo->id.next) { - /* Migrate to Bullet for games, except for the NaN versions */ - /* People can still explicitly choose for Sumo (after 2.42 is out) */ - if (main->versionfile > 225) - wo->physicsEngine = WOPHY_BULLET; if (WO_AODIST == wo->aomode) wo->aocolor = WO_AOPLAIN; } @@ -3163,25 +2829,6 @@ void blo_do_versions_pre250(FileData *fd, Library *lib, Main *main) idproperties_fix_group_lengths(main->particle); } - /* sun/sky */ - if (main->versionfile < 246) { - Object *ob; - bActuator *act; - - /* dRot actuator change direction in 2.46 */ - for (ob = main->object.first; ob; ob = ob->id.next) { - for (act = ob->actuators.first; act; act = act->next) { - if (act->type == ACT_OBJECT) { - bObjectActuator *ba = act->data; - - ba->drot[0] = -ba->drot[0]; - ba->drot[1] = -ba->drot[1]; - ba->drot[2] = -ba->drot[2]; - } - } - } - } - /* convert fluids to modifier */ if (main->versionfile < 246 || (main->versionfile == 246 && main->subversionfile < 1)) { Object *ob; @@ -3211,25 +2858,6 @@ void blo_do_versions_pre250(FileData *fd, Library *lib, Main *main) } } - if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 2)) { - Object *ob; - for (ob = main->object.first; ob; ob = ob->id.next) { - ob->gameflag |= OB_COLLISION; - ob->margin = 0.06f; - } - } - - if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 3)) { - Object *ob; - for (ob = main->object.first; ob; ob = ob->id.next) { - /* Starting from subversion 3, ACTOR is a separate feature. - * Before it was conditioning all the other dynamic flags */ - if (!(ob->gameflag & OB_ACTOR)) - ob->gameflag &= ~(OB_GHOST|OB_DYNAMIC|OB_RIGID_BODY|OB_SOFT_BODY|OB_COLLISION_RESPONSE); - /* suitable default for older files */ - } - } - if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 5)) { Lamp *la = main->lamp.first; for (; la; la = la->id.next) { @@ -3261,23 +2889,6 @@ void blo_do_versions_pre250(FileData *fd, Library *lib, Main *main) } } - /* direction constraint actuators were always local in previous version */ - if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 7)) { - bActuator *act; - Object *ob; - - for (ob = main->object.first; ob; ob = ob->id.next) { - for (act = ob->actuators.first; act; act = act->next) { - if (act->type == ACT_CONSTRAINT) { - bConstraintActuator *coa = act->data; - if (coa->type == ACT_CONST_TYPE_DIST) { - coa->flag |= ACT_CONST_LOCAL; - } - } - } - } - } - if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 9)) { Lamp *la = main->lamp.first; for (; la; la = la->id.next) { @@ -3285,28 +2896,6 @@ void blo_do_versions_pre250(FileData *fd, Library *lib, Main *main) } } - /* BGE message actuators needed OB prefix, very confusing */ - if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 10)) { - bActuator *act; - Object *ob; - - for (ob = main->object.first; ob; ob = ob->id.next) { - for (act = ob->actuators.first; act; act = act->next) { - if (act->type == ACT_MESSAGE) { - bMessageActuator *msgAct = (bMessageActuator *) act->data; - - if (BLI_strnlen(msgAct->toPropName, 3) > 2) { - /* strip first 2 chars, would have only worked if these were OB anyway */ - memmove(msgAct->toPropName, msgAct->toPropName + 2, sizeof(msgAct->toPropName) - 2); - } - else { - msgAct->toPropName[0] = '\0'; - } - } - } - } - } - if (main->versionfile < 248) { Lamp *la; @@ -3400,60 +2989,6 @@ void blo_do_versions_pre250(FileData *fd, Library *lib, Main *main) } } - if (main->versionfile < 248 || (main->versionfile == 248 && main->subversionfile < 3)) { - Object *ob; - - /* Adjustments needed after Bullets update */ - for (ob = main->object.first; ob; ob = ob->id.next) { - ob->damping *= 0.635f; - ob->rdamping = 0.1f + (0.8f * ob->rdamping); - } - } - - if (main->versionfile < 248 || (main->versionfile == 248 && main->subversionfile < 4)) { - Scene *sce; - World *wrld; - - /* Dome (Fisheye) default parameters */ - for (sce = main->scene.first; sce; sce = sce->id.next) { - sce->r.domeangle = 180; - sce->r.domemode = 1; - sce->r.domeres = 4; - sce->r.domeresbuf = 1.0f; - sce->r.dometilt = 0; - } - /* DBVT culling by default */ - for (wrld = main->world.first; wrld; wrld = wrld->id.next) { - wrld->mode |= WO_DBVT_CULLING; - wrld->occlusionRes = 128; - } - } - - if (main->versionfile < 248 || (main->versionfile == 248 && main->subversionfile < 5)) { - Object *ob; - World *wrld; - for (ob = main->object.first; ob; ob = ob->id.next) { - if (ob->parent) { - /* check if top parent has compound shape set and if yes, set this object - * to compound shaper as well (was the behavior before, now it's optional) */ - Object *parent = blo_do_versions_newlibadr(fd, lib, ob->parent); - while (parent && parent != ob && parent->parent != NULL) { - parent = blo_do_versions_newlibadr(fd, lib, parent->parent); - } - if (parent) { - if (parent->gameflag & OB_CHILD) - ob->gameflag |= OB_CHILD; - } - } - } - for (wrld = main->world.first; wrld; wrld = wrld->id.next) { - wrld->ticrate = 60; - wrld->maxlogicstep = 5; - wrld->physubstep = 1; - wrld->maxphystep = 5; - } - } - /* correct introduce of seed for wind force */ if (main->versionfile < 249 && main->subversionfile < 1) { Object *ob; diff --git a/source/blender/blenloader/intern/writefile.c b/source/blender/blenloader/intern/writefile.c index c1c165bb523..c6523dc99e2 100644 --- a/source/blender/blenloader/intern/writefile.c +++ b/source/blender/blenloader/intern/writefile.c @@ -109,13 +109,11 @@ #include "DNA_anim_types.h" #include "DNA_armature_types.h" -#include "DNA_actuator_types.h" #include "DNA_brush_types.h" #include "DNA_cachefile_types.h" #include "DNA_camera_types.h" #include "DNA_cloth_types.h" #include "DNA_constraint_types.h" -#include "DNA_controller_types.h" #include "DNA_dynamicpaint_types.h" #include "DNA_genfile.h" #include "DNA_group_types.h" @@ -136,12 +134,10 @@ #include "DNA_packedFile_types.h" #include "DNA_particle_types.h" #include "DNA_lightprobe_types.h" -#include "DNA_property_types.h" #include "DNA_rigidbody_types.h" #include "DNA_scene_types.h" #include "DNA_sdna_types.h" #include "DNA_sequence_types.h" -#include "DNA_sensor_types.h" #include "DNA_smoke_types.h" #include "DNA_space_types.h" #include "DNA_screen_types.h" @@ -1466,180 +1462,6 @@ static void write_particlesystems(WriteData *wd, ListBase *particles) } } -static void write_properties(WriteData *wd, ListBase *lb) -{ - bProperty *prop; - - prop = lb->first; - while (prop) { - writestruct(wd, DATA, bProperty, 1, prop); - - if (prop->poin && prop->poin != &prop->data) { - writedata(wd, DATA, MEM_allocN_len(prop->poin), prop->poin); - } - - prop = prop->next; - } -} - -static void write_sensors(WriteData *wd, ListBase *lb) -{ - bSensor *sens; - - sens = lb->first; - while (sens) { - writestruct(wd, DATA, bSensor, 1, sens); - - writedata(wd, DATA, sizeof(void *) * sens->totlinks, sens->links); - - switch (sens->type) { - case SENS_NEAR: - writestruct(wd, DATA, bNearSensor, 1, sens->data); - break; - case SENS_MOUSE: - writestruct(wd, DATA, bMouseSensor, 1, sens->data); - break; - case SENS_KEYBOARD: - writestruct(wd, DATA, bKeyboardSensor, 1, sens->data); - break; - case SENS_PROPERTY: - writestruct(wd, DATA, bPropertySensor, 1, sens->data); - break; - case SENS_ARMATURE: - writestruct(wd, DATA, bArmatureSensor, 1, sens->data); - break; - case SENS_ACTUATOR: - writestruct(wd, DATA, bActuatorSensor, 1, sens->data); - break; - case SENS_DELAY: - writestruct(wd, DATA, bDelaySensor, 1, sens->data); - break; - case SENS_COLLISION: - writestruct(wd, DATA, bCollisionSensor, 1, sens->data); - break; - case SENS_RADAR: - writestruct(wd, DATA, bRadarSensor, 1, sens->data); - break; - case SENS_RANDOM: - writestruct(wd, DATA, bRandomSensor, 1, sens->data); - break; - case SENS_RAY: - writestruct(wd, DATA, bRaySensor, 1, sens->data); - break; - case SENS_MESSAGE: - writestruct(wd, DATA, bMessageSensor, 1, sens->data); - break; - case SENS_JOYSTICK: - writestruct(wd, DATA, bJoystickSensor, 1, sens->data); - break; - default: - ; /* error: don't know how to write this file */ - } - - sens = sens->next; - } -} - -static void write_controllers(WriteData *wd, ListBase *lb) -{ - bController *cont; - - cont = lb->first; - while (cont) { - writestruct(wd, DATA, bController, 1, cont); - - writedata(wd, DATA, sizeof(void *) * cont->totlinks, cont->links); - - switch (cont->type) { - case CONT_EXPRESSION: - writestruct(wd, DATA, bExpressionCont, 1, cont->data); - break; - case CONT_PYTHON: - writestruct(wd, DATA, bPythonCont, 1, cont->data); - break; - default: - ; /* error: don't know how to write this file */ - } - - cont = cont->next; - } -} - -static void write_actuators(WriteData *wd, ListBase *lb) -{ - bActuator *act; - - act = lb->first; - while (act) { - writestruct(wd, DATA, bActuator, 1, act); - - switch (act->type) { - case ACT_ACTION: - case ACT_SHAPEACTION: - writestruct(wd, DATA, bActionActuator, 1, act->data); - break; - case ACT_SOUND: - writestruct(wd, DATA, bSoundActuator, 1, act->data); - break; - case ACT_OBJECT: - writestruct(wd, DATA, bObjectActuator, 1, act->data); - break; - case ACT_PROPERTY: - writestruct(wd, DATA, bPropertyActuator, 1, act->data); - break; - case ACT_CAMERA: - writestruct(wd, DATA, bCameraActuator, 1, act->data); - break; - case ACT_CONSTRAINT: - writestruct(wd, DATA, bConstraintActuator, 1, act->data); - break; - case ACT_EDIT_OBJECT: - writestruct(wd, DATA, bEditObjectActuator, 1, act->data); - break; - case ACT_SCENE: - writestruct(wd, DATA, bSceneActuator, 1, act->data); - break; - case ACT_GROUP: - writestruct(wd, DATA, bGroupActuator, 1, act->data); - break; - case ACT_RANDOM: - writestruct(wd, DATA, bRandomActuator, 1, act->data); - break; - case ACT_MESSAGE: - writestruct(wd, DATA, bMessageActuator, 1, act->data); - break; - case ACT_GAME: - writestruct(wd, DATA, bGameActuator, 1, act->data); - break; - case ACT_VISIBILITY: - writestruct(wd, DATA, bVisibilityActuator, 1, act->data); - break; - case ACT_2DFILTER: - writestruct(wd, DATA, bTwoDFilterActuator, 1, act->data); - break; - case ACT_PARENT: - writestruct(wd, DATA, bParentActuator, 1, act->data); - break; - case ACT_STATE: - writestruct(wd, DATA, bStateActuator, 1, act->data); - break; - case ACT_ARMATURE: - writestruct(wd, DATA, bArmatureActuator, 1, act->data); - break; - case ACT_STEERING: - writestruct(wd, DATA, bSteeringActuator, 1, act->data); - break; - case ACT_MOUSE: - writestruct(wd, DATA, bMouseActuator, 1, act->data); - break; - default: - ; /* error: don't know how to write this file */ - } - - act = act->next; - } -} - static void write_motionpath(WriteData *wd, bMotionPath *mpath) { /* sanity checks */ @@ -1954,10 +1776,6 @@ static void write_object(WriteData *wd, Object *ob) writedata(wd, DATA, sizeof(void *) * ob->totcol, ob->mat); writedata(wd, DATA, sizeof(char) * ob->totcol, ob->matbits); /* write_effects(wd, &ob->effect); */ /* not used anymore */ - write_properties(wd, &ob->prop); - write_sensors(wd, &ob->sensors); - write_controllers(wd, &ob->controllers); - write_actuators(wd, &ob->actuators); if (ob->type == OB_ARMATURE) { bArmature *arm = ob->data; @@ -1978,7 +1796,6 @@ static void write_object(WriteData *wd, Object *ob) write_pointcaches(wd, &ob->soft->ptcaches); writestruct(wd, DATA, EffectorWeights, 1, ob->soft->effector_weights); } - writestruct(wd, DATA, BulletSoftBody, 1, ob->bsoft); if (ob->rigidbody_object) { /* TODO: if any extra data is added to handle duplis, will need separate function then */ @@ -3089,9 +2906,6 @@ static void write_area_regions(WriteData *wd, ScrArea *area) writestruct(wd, DATA, bNodeTreePath, 1, path); } } - else if (sl->spacetype == SPACE_LOGIC) { - writestruct(wd, DATA, SpaceLogic, 1, sl); - } else if (sl->spacetype == SPACE_CONSOLE) { SpaceConsole *con = (SpaceConsole *)sl; ConsoleLine *cl; diff --git a/source/blender/editors/CMakeLists.txt b/source/blender/editors/CMakeLists.txt index 06f412b7019..619b031e27a 100644 --- a/source/blender/editors/CMakeLists.txt +++ b/source/blender/editors/CMakeLists.txt @@ -49,7 +49,6 @@ if(WITH_BLENDER) add_subdirectory(space_graph) add_subdirectory(space_image) add_subdirectory(space_info) - add_subdirectory(space_logic) add_subdirectory(space_nla) add_subdirectory(space_node) add_subdirectory(space_outliner) diff --git a/source/blender/editors/include/ED_screen.h b/source/blender/editors/include/ED_screen.h index 3523e27f6ba..db19bc48fb3 100644 --- a/source/blender/editors/include/ED_screen.h +++ b/source/blender/editors/include/ED_screen.h @@ -233,7 +233,6 @@ int ED_operator_sequencer_active(struct bContext *C); int ED_operator_sequencer_active_editable(struct bContext *C); int ED_operator_image_active(struct bContext *C); int ED_operator_nla_active(struct bContext *C); -int ED_operator_logic_active(struct bContext *C); int ED_operator_info_active(struct bContext *C); int ED_operator_console_active(struct bContext *C); diff --git a/source/blender/editors/include/UI_interface.h b/source/blender/editors/include/UI_interface.h index edf15d02e73..d85c77d55fb 100644 --- a/source/blender/editors/include/UI_interface.h +++ b/source/blender/editors/include/UI_interface.h @@ -268,8 +268,6 @@ typedef enum { UI_BTYPE_SCROLL = (18 << 9), UI_BTYPE_BLOCK = (19 << 9), UI_BTYPE_LABEL = (20 << 9), - UI_BTYPE_LINK = (22 << 9), - UI_BTYPE_INLINK = (23 << 9), UI_BTYPE_KEY_EVENT = (24 << 9), UI_BTYPE_HSVCUBE = (26 << 9), UI_BTYPE_PULLDOWN = (27 << 9), /* menu (often used in headers), **_MENU /w different draw-type */ @@ -704,16 +702,6 @@ uiBut *uiDefSearchButO_ptr(uiBlock *block, struct wmOperatorType *ot, struct IDP uiBut *uiDefAutoButR(uiBlock *block, struct PointerRNA *ptr, struct PropertyRNA *prop, int index, const char *name, int icon, int x1, int y1, int x2, int y2); int uiDefAutoButsRNA(uiLayout *layout, struct PointerRNA *ptr, bool (*check_prop)(struct PointerRNA *, struct PropertyRNA *), const char label_align); -/* Links - * - * Game engine logic brick links. Non-functional currently in 2.5, - * code to handle and draw these is disabled internally. */ - -void UI_but_link_set(struct uiBut *but, void **poin, void ***ppoin, short *tot, int from, int to); - -void UI_block_links_compose(uiBlock *block); -uiBut *UI_block_links_find_inlink(uiBlock *block, void *poin); - /* use inside searchfunc to add items */ bool UI_search_item_add(uiSearchItems *items, const char *name, void *poin, int iconid); /* bfunc gets search item *poin as arg2, or if NULL the old string */ @@ -973,8 +961,6 @@ void uiTemplateColorPicker(uiLayout *layout, struct PointerRNA *ptr, const char void uiTemplatePalette(uiLayout *layout, struct PointerRNA *ptr, const char *propname, int color); void uiTemplateLayers(uiLayout *layout, struct PointerRNA *ptr, const char *propname, PointerRNA *used_ptr, const char *used_propname, int active_layer); -void uiTemplateGameStates(uiLayout *layout, struct PointerRNA *ptr, const char *propname, - PointerRNA *used_ptr, const char *used_propname, int active_state); void uiTemplateImage(uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, const char *propname, struct PointerRNA *userptr, int compact, int multiview); void uiTemplateImageSettings(uiLayout *layout, struct PointerRNA *imfptr, int color_management); void uiTemplateImageStereo3d(uiLayout *layout, struct PointerRNA *stereo3d_format_ptr); diff --git a/source/blender/editors/interface/interface.c b/source/blender/editors/interface/interface.c index a98d62be3ca..20eb0ce50e5 100644 --- a/source/blender/editors/interface/interface.c +++ b/source/blender/editors/interface/interface.c @@ -510,87 +510,6 @@ static int ui_but_calc_float_precision(uiBut *but, double value) return UI_calc_float_precision(prec, value); } -/* ************** LINK LINE DRAWING ************* */ - -/* link line drawing is not part of buttons or theme.. so we stick with it here */ - -static void ui_draw_linkline(uiLinkLine *line, int highlightActiveLines, int dashInactiveLines) -{ - rcti rect; - float color[4] = {1.0f}; - - if (line->from == NULL || line->to == NULL) return; - - rect.xmin = BLI_rctf_cent_x(&line->from->rect); - rect.ymin = BLI_rctf_cent_y(&line->from->rect); - rect.xmax = BLI_rctf_cent_x(&line->to->rect); - rect.ymax = BLI_rctf_cent_y(&line->to->rect); - - if (dashInactiveLines) - UI_GetThemeColor4fv(TH_GRID, color); - else if (line->flag & UI_SELECT) - rgba_float_args_set_ch(color, 100, 100, 100, 255); - else if (highlightActiveLines && ((line->from->flag & UI_ACTIVE) || (line->to->flag & UI_ACTIVE))) - UI_GetThemeColor4fv(TH_TEXT_HI, color); - else - rgba_float_args_set_ch(color, 0, 0, 0, 255); - - ui_draw_link_bezier(&rect, color); -} - -static void ui_draw_links(uiBlock *block) -{ - uiBut *but; - uiLinkLine *line; - - /* Draw the gray out lines. Do this first so they appear at the - * bottom of inactive or active lines. - * As we go, remember if we see any active or selected lines. */ - bool found_selectline = false; - bool found_activeline = false; - - for (but = block->buttons.first; but; but = but->next) { - if (but->type == UI_BTYPE_LINK && but->link) { - for (line = but->link->lines.first; line; line = line->next) { - if (!(line->from->flag & UI_ACTIVE) && !(line->to->flag & UI_ACTIVE)) { - if (line->deactive) - ui_draw_linkline(line, 0, true); - } - else - found_activeline = true; - - if ((line->from->flag & UI_SELECT) || (line->to->flag & UI_SELECT)) - found_selectline = true; - } - } - } - - /* Draw the inactive lines (lines with neither button being hovered over) */ - for (but = block->buttons.first; but; but = but->next) { - if (but->type == UI_BTYPE_LINK && but->link) { - for (line = but->link->lines.first; line; line = line->next) { - if (!(line->from->flag & UI_ACTIVE) && !(line->to->flag & UI_ACTIVE)) { - if (!line->deactive) - ui_draw_linkline(line, 0, false); - } - } - } - } - - /* Draw any active lines (lines with either button being hovered over). - * Do this last so they appear on top of inactive and gray out lines. */ - if (found_activeline) { - for (but = block->buttons.first; but; but = but->next) { - if (but->type == UI_BTYPE_LINK && but->link) { - for (line = but->link->lines.first; line; line = line->next) { - if ((line->from->flag & UI_ACTIVE) || (line->to->flag & UI_ACTIVE)) - ui_draw_linkline(line, !found_selectline, false); - } - } - } - } -} - /* ************** BLOCK ENDING FUNCTION ************* */ /* NOTE: if but->poin is allocated memory for every defbut, things fail... */ @@ -633,38 +552,6 @@ uiBut *ui_but_find_new(uiBlock *block_new, const uiBut *but_old) return but_new; } -/* oldbut is being inserted in new block, so we use the lines from new button, and replace button pointers */ -static void ui_but_update_linklines(uiBlock *block, uiBut *oldbut, uiBut *newbut) -{ - uiLinkLine *line; - uiBut *but; - - /* if active button is UI_BTYPE_LINK */ - if (newbut->type == UI_BTYPE_LINK && newbut->link) { - - SWAP(uiLink *, oldbut->link, newbut->link); - - for (line = oldbut->link->lines.first; line; line = line->next) { - if (line->to == newbut) - line->to = oldbut; - if (line->from == newbut) - line->from = oldbut; - } - } - - /* check all other button links */ - for (but = block->buttons.first; but; but = but->next) { - if (but != newbut && but->type == UI_BTYPE_LINK && but->link) { - for (line = but->link->lines.first; line; line = line->next) { - if (line->to == newbut) - line->to = oldbut; - if (line->from == newbut) - line->from = oldbut; - } - } - } -} - /** * \return true when \a but_p is set (only done for active buttons). */ @@ -764,8 +651,6 @@ static bool ui_but_update_from_old_block(const bContext *C, uiBlock *block, uiBu oldbut->a1 = but->a1; } - ui_but_update_linklines(block, oldbut, but); - if (!BLI_listbase_is_empty(&block->butstore)) { UI_butstore_register_update(block, oldbut, but); } @@ -1453,8 +1338,6 @@ void UI_block_draw(const bContext *C, uiBlock *block) /* restore matrix */ gpuPopProjectionMatrix(); gpuPopMatrix(); - - ui_draw_links(block); } static void ui_block_message_subscribe(ARegion *ar, struct wmMsgBus *mbus, uiBlock *block) @@ -1573,83 +1456,6 @@ static void ui_but_update_select_flag(uiBut *but, double *value) } } -static uiBut *ui_linkline_find_inlink(uiBlock *block, void *poin) -{ - uiBut *but; - - but = block->buttons.first; - while (but) { - if (but->type == UI_BTYPE_INLINK) { - if (but->poin == poin) return but; - } - but = but->next; - } - return NULL; -} - -static void ui_linkline_add(ListBase *listb, uiBut *but, uiBut *bt, short deactive) -{ - uiLinkLine *line; - - line = MEM_callocN(sizeof(uiLinkLine), "linkline"); - BLI_addtail(listb, line); - line->from = but; - line->to = bt; - line->deactive = deactive; -} - -uiBut *UI_block_links_find_inlink(uiBlock *block, void *poin) -{ - return ui_linkline_find_inlink(block, poin); -} - -void UI_block_links_compose(uiBlock *block) -{ - uiBut *but, *bt; - uiLink *link; - void ***ppoin; - int a; - - but = block->buttons.first; - while (but) { - if (but->type == UI_BTYPE_LINK) { - link = but->link; - - /* for all pointers in the array */ - if (link) { - if (link->ppoin) { - ppoin = link->ppoin; - for (a = 0; a < *(link->totlink); a++) { - bt = ui_linkline_find_inlink(block, (*ppoin)[a]); - if (bt) { - if ((but->flag & UI_BUT_SCA_LINK_GREY) || (bt->flag & UI_BUT_SCA_LINK_GREY)) { - ui_linkline_add(&link->lines, but, bt, true); - } - else { - ui_linkline_add(&link->lines, but, bt, false); - } - - } - } - } - else if (link->poin) { - bt = ui_linkline_find_inlink(block, *link->poin); - if (bt) { - if ((but->flag & UI_BUT_SCA_LINK_GREY) || (bt->flag & UI_BUT_SCA_LINK_GREY)) { - ui_linkline_add(&link->lines, but, bt, true); - } - else { - ui_linkline_add(&link->lines, but, bt, false); - } - } - } - } - } - but = but->next; - } -} - - /* ************************************************ */ void UI_block_lock_set(uiBlock *block, bool val, const char *lockstr) @@ -1666,44 +1472,6 @@ void UI_block_lock_clear(uiBlock *block) block->lockstr = NULL; } -/* *************************************************************** */ - -void ui_linkline_remove(uiLinkLine *line, uiBut *but) -{ - uiLink *link; - int a, b; - - BLI_remlink(&but->link->lines, line); - - link = line->from->link; - - /* are there more pointers allowed? */ - if (link->ppoin) { - - if (*(link->totlink) == 1) { - *(link->totlink) = 0; - MEM_freeN(*(link->ppoin)); - *(link->ppoin) = NULL; - } - else { - b = 0; - for (a = 0; a < (*(link->totlink)); a++) { - if ((*(link->ppoin))[a] != line->to->poin) { - (*(link->ppoin))[b] = (*(link->ppoin))[a]; - b++; - } - } - (*(link->totlink))--; - } - } - else { - *(link->poin) = NULL; - } - - MEM_freeN(line); - //REDRAW -} - /* *********************** data get/set *********************** * this either works with the pointed to data, or can work with * an edit override pointer while dragging for example */ @@ -2788,14 +2556,6 @@ static void ui_set_but_soft_range(uiBut *but) /* ******************* Free ********************/ -static void ui_free_link(uiLink *link) -{ - if (link) { - BLI_freelistN(&link->lines); - MEM_freeN(link); - } -} - /* can be called with C==NULL */ static void ui_but_free(const bContext *C, uiBut *but) { @@ -2836,7 +2596,6 @@ static void ui_but_free(const bContext *C, uiBut *but) if (but->str && but->str != but->strdata) { MEM_freeN(but->str); } - ui_free_link(but->link); if ((but->type == UI_BTYPE_IMAGE) && but->poin) { IMB_freeImBuf((struct ImBuf *)but->poin); @@ -4113,19 +3872,6 @@ uiBut *uiDefIconTextButO(uiBlock *block, int type, const char *opname, int opcon /* END Button containing both string label and icon */ -void UI_but_link_set(uiBut *but, void **poin, void ***ppoin, short *tot, int from, int to) -{ - uiLink *link; - - link = but->link = MEM_callocN(sizeof(uiLink), "new uilink"); - - link->poin = poin; - link->ppoin = ppoin; - link->totlink = tot; - link->fromcode = from; - link->tocode = to; -} - /* cruft to make uiBlock and uiBut private */ int UI_blocklist_min_y_get(ListBase *lb) diff --git a/source/blender/editors/interface/interface_handlers.c b/source/blender/editors/interface/interface_handlers.c index 11f78967315..63fe440b36c 100644 --- a/source/blender/editors/interface/interface_handlers.c +++ b/source/blender/editors/interface/interface_handlers.c @@ -39,9 +39,6 @@ #include "MEM_guardedalloc.h" #include "DNA_brush_types.h" -#include "DNA_sensor_types.h" -#include "DNA_controller_types.h" -#include "DNA_actuator_types.h" #include "DNA_object_types.h" #include "DNA_scene_types.h" @@ -117,8 +114,6 @@ #define USE_KEYMAP_ADD_HACK /* proto */ -static void ui_but_smart_controller_add(bContext *C, uiBut *from, uiBut *to); -static void ui_but_link_add(bContext *C, uiBut *from, uiBut *to); static int ui_do_but_EXIT(bContext *C, uiBut *but, struct uiHandleButtonData *data, const wmEvent *event); static bool ui_but_find_select_in_enum__cmp(const uiBut *but_a, const uiBut *but_b); static void ui_textedit_string_set(uiBut *but, struct uiHandleButtonData *data, const char *str); @@ -724,8 +719,7 @@ static void ui_apply_but_undo(uiBut *but) const char *str = NULL; /* define which string to use for undo */ - if (ELEM(but->type, UI_BTYPE_LINK, UI_BTYPE_INLINK)) str = "Add button link"; - else if (but->type == UI_BTYPE_MENU) str = but->drawstr; + if (but->type == UI_BTYPE_MENU) str = but->drawstr; else if (but->drawstr[0]) str = but->drawstr; else str = but->tip; @@ -1782,223 +1776,6 @@ static bool ui_but_drag_init( /* ********************** linklines *********************** */ -static void ui_linkline_remove_active(uiBlock *block) -{ - uiBut *but; - uiLink *link; - uiLinkLine *line, *nline; - int a, b; - - for (but = block->buttons.first; but; but = but->next) { - if (but->type == UI_BTYPE_LINK && but->link) { - for (line = but->link->lines.first; line; line = nline) { - nline = line->next; - - if (line->flag & UI_SELECT) { - BLI_remlink(&but->link->lines, line); - - link = line->from->link; - - /* are there more pointers allowed? */ - if (link->ppoin) { - - if (*(link->totlink) == 1) { - *(link->totlink) = 0; - MEM_freeN(*(link->ppoin)); - *(link->ppoin) = NULL; - } - else { - b = 0; - for (a = 0; a < (*(link->totlink)); a++) { - - if ((*(link->ppoin))[a] != line->to->poin) { - (*(link->ppoin))[b] = (*(link->ppoin))[a]; - b++; - } - } - (*(link->totlink))--; - } - } - else { - *(link->poin) = NULL; - } - - MEM_freeN(line); - } - } - } - } -} - - -static uiLinkLine *ui_but_find_link(uiBut *from, uiBut *to) -{ - uiLinkLine *line; - uiLink *link; - - link = from->link; - if (link) { - for (line = link->lines.first; line; line = line->next) { - if (line->from == from && line->to == to) { - return line; - } - } - } - return NULL; -} - -/* XXX BAD BAD HACK, fixme later **************** */ -/* Try to add an AND Controller between the sensor and the actuator logic bricks and to connect them all */ -static void ui_but_smart_controller_add(bContext *C, uiBut *from, uiBut *to) -{ - Object *ob = NULL; - bSensor *sens_iter; - bActuator *act_to, *act_iter; - bController *cont; - bController ***sens_from_links; - uiBut *tmp_but; - - uiLink *link = from->link; - - PointerRNA props_ptr, object_ptr; - - if (link->ppoin) - sens_from_links = (bController ***)(link->ppoin); - else return; - - act_to = (bActuator *)(to->poin); - - /* (1) get the object */ - CTX_DATA_BEGIN (C, Object *, ob_iter, selected_editable_objects) - { - for (sens_iter = ob_iter->sensors.first; sens_iter; sens_iter = sens_iter->next) { - if (&(sens_iter->links) == sens_from_links) { - ob = ob_iter; - break; - } - } - if (ob) break; - } CTX_DATA_END; - - if (!ob) return; - - /* (2) check if the sensor and the actuator are from the same object */ - for (act_iter = ob->actuators.first; act_iter; act_iter = (bActuator *)act_iter->next) { - if (act_iter == act_to) - break; - } - - /* only works if the sensor and the actuator are from the same object */ - if (!act_iter) return; - - /* in case the linked controller is not the active one */ - RNA_pointer_create((ID *)ob, &RNA_Object, ob, &object_ptr); - - WM_operator_properties_create(&props_ptr, "LOGIC_OT_controller_add"); - RNA_string_set(&props_ptr, "object", ob->id.name + 2); - - /* (3) add a new controller */ - if (WM_operator_name_call(C, "LOGIC_OT_controller_add", WM_OP_EXEC_DEFAULT, &props_ptr) & OPERATOR_FINISHED) { - cont = (bController *)ob->controllers.last; - /* Quick fix to make sure we always have an AND controller. - * It might be nicer to make sure the operator gives us the right one though... */ - cont->type = CONT_LOGIC_AND; - - /* (4) link the sensor->controller->actuator */ - tmp_but = MEM_callocN(sizeof(uiBut), "uiBut"); - UI_but_link_set( - tmp_but, (void **)&cont, (void ***)&(cont->links), - &cont->totlinks, from->link->tocode, (int)to->hardmin); - tmp_but->hardmin = from->link->tocode; - tmp_but->poin = (char *)cont; - - tmp_but->type = UI_BTYPE_INLINK; - ui_but_link_add(C, from, tmp_but); - - tmp_but->type = UI_BTYPE_LINK; - ui_but_link_add(C, tmp_but, to); - - /* (5) garbage collection */ - MEM_freeN(tmp_but->link); - MEM_freeN(tmp_but); - } - WM_operator_properties_free(&props_ptr); -} - -static void ui_but_link_add(bContext *C, uiBut *from, uiBut *to) -{ - /* in 'from' we have to add a link to 'to' */ - uiLink *link; - uiLinkLine *line; - void **oldppoin; - int a; - - if ((line = ui_but_find_link(from, to))) { - line->flag |= UI_SELECT; - ui_linkline_remove_active(from->block); - return; - } - - if (from->type == UI_BTYPE_INLINK && to->type == UI_BTYPE_INLINK) { - return; - } - else if (from->type == UI_BTYPE_LINK && to->type == UI_BTYPE_INLINK) { - if (from->link->tocode != (int)to->hardmin) { - ui_but_smart_controller_add(C, from, to); - return; - } - } - else if (from->type == UI_BTYPE_INLINK && to->type == UI_BTYPE_LINK) { - if (to->link->tocode == (int)from->hardmin) { - return; - } - } - - link = from->link; - - /* are there more pointers allowed? */ - if (link->ppoin) { - oldppoin = *(link->ppoin); - - (*(link->totlink))++; - *(link->ppoin) = MEM_callocN(*(link->totlink) * sizeof(void *), "new link"); - - for (a = 0; a < (*(link->totlink)) - 1; a++) { - (*(link->ppoin))[a] = oldppoin[a]; - } - (*(link->ppoin))[a] = to->poin; - - if (oldppoin) MEM_freeN(oldppoin); - } - else { - *(link->poin) = to->poin; - } - -} - - -static void ui_apply_but_LINK(bContext *C, uiBut *but, uiHandleButtonData *data) -{ - ARegion *ar = CTX_wm_region(C); - uiBut *bt; - - for (bt = but->block->buttons.first; bt; bt = bt->next) { - if (ui_but_contains_point_px(ar, bt, but->linkto[0] + ar->winrct.xmin, but->linkto[1] + ar->winrct.ymin) ) - break; - } - if (bt && bt != but) { - if (!ELEM(bt->type, UI_BTYPE_LINK, UI_BTYPE_INLINK) || !ELEM(but->type, UI_BTYPE_LINK, UI_BTYPE_INLINK)) - return; - - if (but->type == UI_BTYPE_LINK) ui_but_link_add(C, but, bt); - else ui_but_link_add(C, bt, but); - - ui_apply_but_func(C, but); - data->retval = but->retval; - } - data->applied = true; -} - static void ui_apply_but_IMAGE(bContext *C, uiBut *but, uiHandleButtonData *data) { ui_apply_but_func(C, but); @@ -2153,10 +1930,6 @@ static void ui_apply_but(bContext *C, uiBlock *block, uiBut *but, uiHandleButton case UI_BTYPE_HOTKEY_EVENT: ui_apply_but_BUT(C, but, data); break; - case UI_BTYPE_LINK: - case UI_BTYPE_INLINK: - ui_apply_but_LINK(C, but, data); - break; case UI_BTYPE_IMAGE: ui_apply_but_IMAGE(C, but, data); break; @@ -6445,35 +6218,6 @@ static int ui_do_but_WAVEFORM( return WM_UI_HANDLER_CONTINUE; } -static int ui_do_but_LINK( - bContext *C, uiBut *but, - uiHandleButtonData *data, const wmEvent *event) -{ - VECCOPY2D(but->linkto, event->mval); - - if (data->state == BUTTON_STATE_HIGHLIGHT) { - if (event->type == LEFTMOUSE && event->val == KM_PRESS) { - button_activate_state(C, but, BUTTON_STATE_WAIT_RELEASE); - return WM_UI_HANDLER_BREAK; - } - else if (event->type == LEFTMOUSE && but->block->handle) { - button_activate_state(C, but, BUTTON_STATE_EXIT); - return WM_UI_HANDLER_BREAK; - } - } - else if (data->state == BUTTON_STATE_WAIT_RELEASE) { - - if (event->type == LEFTMOUSE && event->val != KM_PRESS) { - if (!(but->flag & UI_SELECT)) - data->cancel = true; - button_activate_state(C, but, BUTTON_STATE_EXIT); - return WM_UI_HANDLER_BREAK; - } - } - - return WM_UI_HANDLER_CONTINUE; -} - static bool ui_numedit_but_TRACKPREVIEW( bContext *C, uiBut *but, uiHandleButtonData *data, int mx, int my, @@ -7289,10 +7033,6 @@ static int ui_do_button(bContext *C, uiBlock *block, uiBut *but, const wmEvent * case UI_BTYPE_HSVCIRCLE: retval = ui_do_but_HSVCIRCLE(C, block, but, data, event); break; - case UI_BTYPE_LINK: - case UI_BTYPE_INLINK: - retval = ui_do_but_LINK(C, but, data, event); - break; case UI_BTYPE_TRACK_PREVIEW: retval = ui_do_but_TRACKPREVIEW(C, block, but, data, event); break; @@ -8520,12 +8260,7 @@ static int ui_handle_button_event(bContext *C, const wmEvent *event, uiBut *but) break; } case MOUSEMOVE: - if (ELEM(but->type, UI_BTYPE_LINK, UI_BTYPE_INLINK)) { - but->flag |= UI_SELECT; - ui_do_button(C, block, but, event); - ED_region_tag_redraw(ar); - } - else { + { /* deselect the button when moving the mouse away */ /* also de-activate for buttons that only show higlights */ if (ui_but_contains_point_px(ar, but, event->x, event->y)) { diff --git a/source/blender/editors/interface/interface_intern.h b/source/blender/editors/interface/interface_intern.h index bb9bfdd4429..0d2a8da265d 100644 --- a/source/blender/editors/interface/interface_intern.h +++ b/source/blender/editors/interface/interface_intern.h @@ -270,9 +270,6 @@ struct uiBut { uiButHandleHoldFunc hold_func; void *hold_argN; - uiLink *link; - short linkto[2]; /* region relative coords */ - const char *tip; uiButToolTipFunc tip_func; void *tip_argN; @@ -451,8 +448,6 @@ typedef struct uiSafetyRct { /* interface.c */ -extern void ui_linkline_remove(uiLinkLine *line, uiBut *but); - void ui_fontscale(short *points, float aspect); extern bool ui_block_is_menu(const uiBlock *block) ATTR_WARN_UNUSED_RESULT; diff --git a/source/blender/editors/interface/interface_templates.c b/source/blender/editors/interface/interface_templates.c index 375027a84d0..ae2b8c8060c 100644 --- a/source/blender/editors/interface/interface_templates.c +++ b/source/blender/editors/interface/interface_templates.c @@ -70,7 +70,6 @@ #include "BKE_particle.h" #include "BKE_paint.h" #include "BKE_report.h" -#include "BKE_sca.h" #include "BKE_screen.h" #include "DEG_depsgraph.h" @@ -1316,8 +1315,7 @@ static uiLayout *draw_modifier( UI_block_emboss_set(block, UI_EMBOSS_NONE); /* When Modifier is a simulation, show button to switch to context rather than the delete button. */ if (modifier_can_delete(md) && - (!modifier_is_simulation(md) || - STREQ(scene->view_render.engine_id, RE_engine_id_BLENDER_GAME))) + !modifier_is_simulation(md)) { uiItemO(row, "", ICON_X, "OBJECT_OT_modifier_remove"); } @@ -2927,77 +2925,6 @@ void uiTemplateLayers( } } -void uiTemplateGameStates( - uiLayout *layout, PointerRNA *ptr, const char *propname, - PointerRNA *used_ptr, const char *used_propname, int active_state) -{ - uiLayout *uRow, *uCol; - PropertyRNA *prop, *used_prop = NULL; - int groups, cols, states; - int group, col, state, row; - int cols_per_group = 5; - Object *ob = (Object *)ptr->id.data; - - prop = RNA_struct_find_property(ptr, propname); - if (!prop) { - RNA_warning("states property not found: %s.%s", RNA_struct_identifier(ptr->type), propname); - return; - } - - /* the number of states determines the way we group them - * - we want 2 rows only (for now) - * - the number of columns (cols) is the total number of buttons per row - * the 'remainder' is added to this, as it will be ok to have first row slightly wider if need be - * - for now, only split into groups if group will have at least 5 items - */ - states = RNA_property_array_length(ptr, prop); - cols = (states / 2) + (states % 2); - groups = ((cols / 2) < cols_per_group) ? (1) : (cols / cols_per_group); - - if (used_ptr && used_propname) { - used_prop = RNA_struct_find_property(used_ptr, used_propname); - if (!used_prop) { - RNA_warning("used layers property not found: %s.%s", RNA_struct_identifier(ptr->type), used_propname); - return; - } - - if (RNA_property_array_length(used_ptr, used_prop) < states) - used_prop = NULL; - } - - /* layers are laid out going across rows, with the columns being divided into groups */ - - for (group = 0; group < groups; group++) { - uCol = uiLayoutColumn(layout, true); - - for (row = 0; row < 2; row++) { - uiBlock *block; - uiBut *but; - - uRow = uiLayoutRow(uCol, true); - block = uiLayoutGetBlock(uRow); - state = groups * cols_per_group * row + cols_per_group * group; - - /* add layers as toggle buts */ - for (col = 0; (col < cols_per_group) && (state < states); col++, state++) { - int icon = 0; - int butlay = 1 << state; - - if (active_state & butlay) - icon = ICON_LAYER_ACTIVE; - else if (used_prop && RNA_property_boolean_get_index(used_ptr, used_prop, state)) - icon = ICON_LAYER_USED; - - but = uiDefIconButR_prop(block, UI_BTYPE_ICON_TOGGLE, 0, icon, 0, 0, UI_UNIT_X / 2, UI_UNIT_Y / 2, ptr, prop, - state, 0, 0, -1, -1, sca_state_name_get(ob, state)); - UI_but_func_set(but, handle_layer_buttons, but, SET_INT_IN_POINTER(state)); - but->type = UI_BTYPE_TOGGLE; - } - } - } -} - - /************************* List Template **************************/ static void uilist_draw_item_default( struct uiList *ui_list, struct bContext *UNUSED(C), struct uiLayout *layout, diff --git a/source/blender/editors/interface/interface_widgets.c b/source/blender/editors/interface/interface_widgets.c index d72e59beb91..71eb764918d 100644 --- a/source/blender/editors/interface/interface_widgets.c +++ b/source/blender/editors/interface/interface_widgets.c @@ -3177,36 +3177,6 @@ bool ui_link_bezier_points(const rcti *rect, float coord_array[][2], int resol) return true; } -#define LINK_RESOL 24 -void ui_draw_link_bezier(const rcti *rect, const float color[4]) -{ - float coord_array[LINK_RESOL + 1][2]; - - if (ui_link_bezier_points(rect, coord_array, LINK_RESOL)) { - unsigned int pos = GWN_vertformat_attr_add(immVertexFormat(), "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT); - immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR); - -#if 0 /* unused */ - /* we can reuse the dist variable here to increment the GL curve eval amount*/ - const float dist = 1.0f / (float)LINK_RESOL; -#endif - glEnable(GL_BLEND); - glEnable(GL_LINE_SMOOTH); - - immUniformColor4fv(color); - - immBegin(GWN_PRIM_LINE_STRIP, LINK_RESOL + 1); - for (int i = 0; i <= LINK_RESOL; ++i) - immVertex2fv(pos, coord_array[i]); - immEnd(); - - glDisable(GL_BLEND); - glDisable(GL_LINE_SMOOTH); - - immUnbindProgram(); - } -} - /* function in use for buttons and for view2d sliders */ void UI_draw_widget_scroll(uiWidgetColors *wcol, const rcti *rect, const rcti *slider, int state) { @@ -3380,24 +3350,6 @@ static void widget_progressbar(uiBut *but, uiWidgetColors *wcol, rcti *rect, int rect->xmax += (BLI_rcti_size_x(&rect_prog) / 2); } -static void widget_link(uiBut *but, uiWidgetColors *UNUSED(wcol), rcti *rect, int UNUSED(state), int UNUSED(roundboxalign)) -{ - - if (but->flag & UI_SELECT) { - rcti rectlink; - float color[4]; - - UI_GetThemeColor4fv(TH_TEXT_HI, color); - - rectlink.xmin = BLI_rcti_cent_x(rect); - rectlink.ymin = BLI_rcti_cent_y(rect); - rectlink.xmax = but->linkto[0]; - rectlink.ymax = but->linkto[1]; - - ui_draw_link_bezier(&rectlink, color); - } -} - static void widget_numslider(uiBut *but, uiWidgetColors *wcol, rcti *rect, int state, int roundboxalign) { uiWidgetBase wtb, wtb1; @@ -4342,14 +4294,7 @@ void ui_draw_but(const bContext *C, ARegion *ar, uiStyle *style, uiBut *but, rct case UI_BTYPE_LISTBOX: wt = widget_type(UI_WTYPE_BOX); break; - - case UI_BTYPE_LINK: - case UI_BTYPE_INLINK: - wt = widget_type(UI_WTYPE_ICON); - wt->custom = widget_link; - - break; - + case UI_BTYPE_EXTRA: widget_draw_extra_mask(C, but, widget_type(UI_WTYPE_BOX), rect); break; diff --git a/source/blender/editors/interface/resources.c b/source/blender/editors/interface/resources.c index de9469a48cb..d13b7e8ea74 100644 --- a/source/blender/editors/interface/resources.c +++ b/source/blender/editors/interface/resources.c @@ -162,9 +162,6 @@ const unsigned char *UI_ThemeGetColorPtr(bTheme *btheme, int spacetype, int colo case SPACE_NODE: ts = &btheme->tnode; break; - case SPACE_LOGIC: - ts = &btheme->tlogic; - break; case SPACE_CLIP: ts = &btheme->tclip; break; @@ -1210,10 +1207,6 @@ void ui_theme_init_default(void) rgba_char_args_set(btheme->tnode.console_output, 223, 202, 53, 255); /* interface nodes */ btheme->tnode.noodle_curving = 5; - /* space logic */ - btheme->tlogic = btheme->tv3d; - rgba_char_args_set(btheme->tlogic.back, 100, 100, 100, 255); - /* space clip */ btheme->tclip = btheme->tv3d; @@ -2104,13 +2097,6 @@ void init_userdef_do_versions(void) if (btheme->tui.wcol_num.outline[3] == 0) ui_widget_color_init(&btheme->tui); - - /* Logic editor theme, check for alpha==0 is safe, then color was never set */ - if (btheme->tlogic.syntaxn[3] == 0) { - /* re-uses syntax color storage */ - btheme->tlogic = btheme->tv3d; - rgba_char_args_set(btheme->tlogic.back, 100, 100, 100, 255); - } rgba_char_args_set_fl(btheme->tinfo.back, 0.45, 0.45, 0.45, 1.0); rgba_char_args_set_fl(btheme->tuserpref.back, 0.45, 0.45, 0.45, 1.0); @@ -2924,9 +2910,6 @@ void init_userdef_do_versions(void) U.transopts &= ~( USER_TR_DEPRECATED_2 | USER_TR_DEPRECATED_3 | USER_TR_DEPRECATED_4 | USER_TR_DEPRECATED_6 | USER_TR_DEPRECATED_7); - U.gameflags &= ~( - USER_GL_RENDER_DEPRECATED_0 | USER_GL_RENDER_DEPRECATED_1 | - USER_GL_RENDER_DEPRECATED_3 | USER_GL_RENDER_DEPRECATED_4); U.uiflag |= USER_LOCK_CURSOR_ADJUST; } diff --git a/source/blender/editors/mesh/CMakeLists.txt b/source/blender/editors/mesh/CMakeLists.txt index eae6b7192d7..91656bf6bd0 100644 --- a/source/blender/editors/mesh/CMakeLists.txt +++ b/source/blender/editors/mesh/CMakeLists.txt @@ -68,18 +68,6 @@ set(SRC mesh_intern.h ) -if(WITH_GAMEENGINE) - add_definitions(-DWITH_GAMEENGINE) - - list(APPEND INC - ../../../../extern/recastnavigation - ) - - list(APPEND SRC - mesh_navmesh.c - ) -endif() - if(WITH_INTERNATIONAL) add_definitions(-DWITH_INTERNATIONAL) endif() diff --git a/source/blender/editors/mesh/mesh_intern.h b/source/blender/editors/mesh/mesh_intern.h index 99342222d52..788887e872a 100644 --- a/source/blender/editors/mesh/mesh_intern.h +++ b/source/blender/editors/mesh/mesh_intern.h @@ -254,12 +254,4 @@ void MESH_OT_customdata_custom_splitnormals_clear(struct wmOperatorType *ot); void MESH_OT_drop_named_image(struct wmOperatorType *ot); -/* *** mesh_navmesh.c *** */ -void MESH_OT_navmesh_make(struct wmOperatorType *ot); -void MESH_OT_navmesh_face_copy(struct wmOperatorType *ot); -void MESH_OT_navmesh_face_add(struct wmOperatorType *ot); -void MESH_OT_navmesh_reset(struct wmOperatorType *ot); -void MESH_OT_navmesh_clear(struct wmOperatorType *ot); - - #endif /* __MESH_INTERN_H__ */ diff --git a/source/blender/editors/mesh/mesh_navmesh.c b/source/blender/editors/mesh/mesh_navmesh.c deleted file mode 100644 index c94015de0f6..00000000000 --- a/source/blender/editors/mesh/mesh_navmesh.c +++ /dev/null @@ -1,736 +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) 2011 by Blender Foundation - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): Benoit Bolsee, - * Nick Samarin - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file blender/editors/mesh/mesh_navmesh.c - * \ingroup edmesh - */ - -#include "MEM_guardedalloc.h" - -#include "DNA_scene_types.h" -#include "DNA_object_types.h" -#include "DNA_mesh_types.h" - -#include "BLI_listbase.h" -#include "BLI_math_vector.h" -#include "BLI_linklist.h" - -#include "BKE_layer.h" -#include "BKE_library.h" -#include "BKE_context.h" -#include "BKE_mesh.h" -#include "BKE_scene.h" -#include "BKE_DerivedMesh.h" -#include "BKE_report.h" -#include "BKE_editmesh.h" - -#include "ED_object.h" -#include "ED_mesh.h" -#include "ED_screen.h" - -#include "WM_api.h" -#include "WM_types.h" - -#include "recast-capi.h" - -#include "DEG_depsgraph.h" - -#include "mesh_intern.h" /* own include */ - - -static void createVertsTrisData(bContext *C, LinkNode *obs, - int *nverts_r, float **verts_r, int *ntris_r, int **tris_r, unsigned int *r_lay) -{ - MVert *mvert; - int nfaces = 0, *tri, i, curnverts, basenverts, curnfaces; - MFace *mface; - float co[3], wco[3]; - Object *ob; - LinkNode *oblink, *dmlink; - DerivedMesh *dm; - Depsgraph *depsgraph = CTX_data_depsgraph(C); - Scene *scene = CTX_data_scene(C); - LinkNodePair dms_pair = {NULL, NULL}; - - int nverts, ntris, *tris; - float *verts; - - nverts = 0; - ntris = 0; - - /* calculate number of verts and tris */ - for (oblink = obs; oblink; oblink = oblink->next) { - ob = (Object *) oblink->link; - dm = mesh_create_derived_no_virtual(depsgraph, scene, ob, NULL, CD_MASK_MESH); - DM_ensure_tessface(dm); - BLI_linklist_append(&dms_pair, dm); - - nverts += dm->getNumVerts(dm); - nfaces = dm->getNumTessFaces(dm); - ntris += nfaces; - - /* resolve quad faces */ - mface = dm->getTessFaceArray(dm); - for (i = 0; i < nfaces; i++) { - MFace *mf = &mface[i]; - if (mf->v4) - ntris += 1; - } - - *r_lay |= ob->lay; - } - LinkNode *dms = dms_pair.list; - - /* create data */ - verts = MEM_mallocN(sizeof(float) * 3 * nverts, "createVertsTrisData verts"); - tris = MEM_mallocN(sizeof(int) * 3 * ntris, "createVertsTrisData faces"); - - basenverts = 0; - tri = tris; - for (oblink = obs, dmlink = dms; oblink && dmlink; - oblink = oblink->next, dmlink = dmlink->next) - { - ob = (Object *) oblink->link; - dm = (DerivedMesh *) dmlink->link; - - curnverts = dm->getNumVerts(dm); - mvert = dm->getVertArray(dm); - - /* copy verts */ - for (i = 0; i < curnverts; i++) { - MVert *v = &mvert[i]; - - copy_v3_v3(co, v->co); - mul_v3_m4v3(wco, ob->obmat, co); - - verts[3 * (basenverts + i) + 0] = wco[0]; - verts[3 * (basenverts + i) + 1] = wco[2]; - verts[3 * (basenverts + i) + 2] = wco[1]; - } - - /* create tris */ - curnfaces = dm->getNumTessFaces(dm); - mface = dm->getTessFaceArray(dm); - - for (i = 0; i < curnfaces; i++) { - MFace *mf = &mface[i]; - - tri[0] = basenverts + mf->v1; - tri[1] = basenverts + mf->v3; - tri[2] = basenverts + mf->v2; - tri += 3; - - if (mf->v4) { - tri[0] = basenverts + mf->v1; - tri[1] = basenverts + mf->v4; - tri[2] = basenverts + mf->v3; - tri += 3; - } - } - - basenverts += curnverts; - } - - /* release derived mesh */ - for (dmlink = dms; dmlink; dmlink = dmlink->next) { - dm = (DerivedMesh *) dmlink->link; - dm->release(dm); - } - - BLI_linklist_free(dms, NULL); - - *nverts_r = nverts; - *verts_r = verts; - *ntris_r = ntris; - *tris_r = tris; -} - -static bool buildNavMesh(const RecastData *recastParams, int nverts, float *verts, int ntris, int *tris, - struct recast_polyMesh **pmesh, struct recast_polyMeshDetail **dmesh, - ReportList *reports) -{ - float bmin[3], bmax[3]; - struct recast_heightfield *solid; - unsigned char *triflags; - struct recast_compactHeightfield *chf; - struct recast_contourSet *cset; - int width, height, walkableHeight, walkableClimb, walkableRadius; - int minRegionArea, mergeRegionArea, maxEdgeLen; - float detailSampleDist, detailSampleMaxError; - - recast_calcBounds(verts, nverts, bmin, bmax); - - /* ** Step 1. Initialize build config ** */ - walkableHeight = (int)ceilf(recastParams->agentheight / recastParams->cellheight); - walkableClimb = (int)floorf(recastParams->agentmaxclimb / recastParams->cellheight); - walkableRadius = (int)ceilf(recastParams->agentradius / recastParams->cellsize); - minRegionArea = (int)(recastParams->regionminsize * recastParams->regionminsize); - mergeRegionArea = (int)(recastParams->regionmergesize * recastParams->regionmergesize); - maxEdgeLen = (int)(recastParams->edgemaxlen / recastParams->cellsize); - detailSampleDist = recastParams->detailsampledist < 0.9f ? 0 : - recastParams->cellsize * recastParams->detailsampledist; - detailSampleMaxError = recastParams->cellheight * recastParams->detailsamplemaxerror; - - /* Set the area where the navigation will be build. */ - recast_calcGridSize(bmin, bmax, recastParams->cellsize, &width, &height); - - /* zero dimensions cause zero alloc later on [#33758] */ - if (width <= 0 || height <= 0) { - BKE_report(reports, RPT_ERROR, "Object has a width or height of zero"); - return false; - } - - /* ** Step 2: Rasterize input polygon soup ** */ - /* Allocate voxel heightfield where we rasterize our input data to */ - solid = recast_newHeightfield(); - - if (!recast_createHeightfield(solid, width, height, bmin, bmax, recastParams->cellsize, recastParams->cellheight)) { - recast_destroyHeightfield(solid); - BKE_report(reports, RPT_ERROR, "Failed to create height field"); - return false; - } - - /* Allocate array that can hold triangle flags */ - triflags = MEM_callocN(sizeof(unsigned char) * ntris, "buildNavMesh triflags"); - - /* Find triangles which are walkable based on their slope and rasterize them */ - recast_markWalkableTriangles(RAD2DEGF(recastParams->agentmaxslope), verts, nverts, tris, ntris, triflags); - recast_rasterizeTriangles(verts, nverts, tris, triflags, ntris, solid, 1); - MEM_freeN(triflags); - - /* ** Step 3: Filter walkables surfaces ** */ - recast_filterLowHangingWalkableObstacles(walkableClimb, solid); - recast_filterLedgeSpans(walkableHeight, walkableClimb, solid); - recast_filterWalkableLowHeightSpans(walkableHeight, solid); - - /* ** Step 4: Partition walkable surface to simple regions ** */ - - chf = recast_newCompactHeightfield(); - if (!recast_buildCompactHeightfield(walkableHeight, walkableClimb, solid, chf)) { - recast_destroyHeightfield(solid); - recast_destroyCompactHeightfield(chf); - - BKE_report(reports, RPT_ERROR, "Failed to create compact height field"); - return false; - } - - recast_destroyHeightfield(solid); - solid = NULL; - - if (!recast_erodeWalkableArea(walkableRadius, chf)) { - recast_destroyCompactHeightfield(chf); - - BKE_report(reports, RPT_ERROR, "Failed to erode walkable area"); - return false; - } - - if (recastParams->partitioning == RC_PARTITION_WATERSHED) { - /* Prepare for region partitioning, by calculating distance field along the walkable surface */ - if (!recast_buildDistanceField(chf)) { - recast_destroyCompactHeightfield(chf); - - BKE_report(reports, RPT_ERROR, "Failed to build distance field"); - return false; - } - - /* Partition the walkable surface into simple regions without holes */ - if (!recast_buildRegions(chf, 0, minRegionArea, mergeRegionArea)) { - recast_destroyCompactHeightfield(chf); - - BKE_report(reports, RPT_ERROR, "Failed to build watershed regions"); - return false; - } - } - else if (recastParams->partitioning == RC_PARTITION_MONOTONE) { - /* Partition the walkable surface into simple regions without holes */ - /* Monotone partitioning does not need distancefield. */ - if (!recast_buildRegionsMonotone(chf, 0, minRegionArea, mergeRegionArea)) { - recast_destroyCompactHeightfield(chf); - - BKE_report(reports, RPT_ERROR, "Failed to build monotone regions"); - return false; - } - } - else { /* RC_PARTITION_LAYERS */ - /* Partition the walkable surface into simple regions without holes */ - if (!recast_buildLayerRegions(chf, 0, minRegionArea)) { - recast_destroyCompactHeightfield(chf); - - BKE_report(reports, RPT_ERROR, "Failed to build layer regions"); - return false; - } - } - - /* ** Step 5: Trace and simplify region contours ** */ - /* Create contours */ - cset = recast_newContourSet(); - - if (!recast_buildContours(chf, recastParams->edgemaxerror, maxEdgeLen, cset, RECAST_CONTOUR_TESS_WALL_EDGES)) { - recast_destroyCompactHeightfield(chf); - recast_destroyContourSet(cset); - - BKE_report(reports, RPT_ERROR, "Failed to build contours"); - return false; - } - - /* ** Step 6: Build polygons mesh from contours ** */ - *pmesh = recast_newPolyMesh(); - if (!recast_buildPolyMesh(cset, recastParams->vertsperpoly, *pmesh)) { - recast_destroyCompactHeightfield(chf); - recast_destroyContourSet(cset); - recast_destroyPolyMesh(*pmesh); - - BKE_report(reports, RPT_ERROR, "Failed to build poly mesh"); - return false; - } - - - /* ** Step 7: Create detail mesh which allows to access approximate height on each polygon ** */ - - *dmesh = recast_newPolyMeshDetail(); - if (!recast_buildPolyMeshDetail(*pmesh, chf, detailSampleDist, detailSampleMaxError, *dmesh)) { - recast_destroyCompactHeightfield(chf); - recast_destroyContourSet(cset); - recast_destroyPolyMesh(*pmesh); - recast_destroyPolyMeshDetail(*dmesh); - - BKE_report(reports, RPT_ERROR, "Failed to build poly mesh detail"); - return false; - } - - recast_destroyCompactHeightfield(chf); - recast_destroyContourSet(cset); - - return true; -} - -static Object *createRepresentation(bContext *C, struct recast_polyMesh *pmesh, struct recast_polyMeshDetail *dmesh, - Base *base, unsigned int lay) -{ - float co[3], rot[3]; - BMEditMesh *em; - int i, j, k; - unsigned short *v; - int face[3]; - ViewLayer *view_layer = CTX_data_view_layer(C); - Object *obedit; - int createob = base == NULL; - int nverts, nmeshes, nvp; - unsigned short *verts, *polys; - unsigned int *meshes; - float bmin[3], cs, ch, *dverts; - unsigned char *tris; - - zero_v3(co); - zero_v3(rot); - - if (createob) { - /* create new object */ - obedit = ED_object_add_type(C, OB_MESH, "Navmesh", co, rot, false, lay); - } - else { - obedit = base->object; - BKE_view_layer_base_deselect_all(view_layer); - BKE_view_layer_base_select(view_layer, base); - copy_v3_v3(obedit->loc, co); - copy_v3_v3(obedit->rot, rot); - } - - ED_object_editmode_enter(C, EM_DO_UNDO | EM_IGNORE_LAYER); - em = BKE_editmesh_from_object(obedit); - - if (!createob) { - /* clear */ - EDBM_mesh_clear(em); - } - - /* create verts for polygon mesh */ - verts = recast_polyMeshGetVerts(pmesh, &nverts); - recast_polyMeshGetBoundbox(pmesh, bmin, NULL); - recast_polyMeshGetCell(pmesh, &cs, &ch); - - for (i = 0; i < nverts; i++) { - v = &verts[3 * i]; - co[0] = bmin[0] + v[0] * cs; - co[1] = bmin[1] + v[1] * ch; - co[2] = bmin[2] + v[2] * cs; - SWAP(float, co[1], co[2]); - BM_vert_create(em->bm, co, NULL, BM_CREATE_NOP); - } - - /* create custom data layer to save polygon idx */ - CustomData_add_layer_named(&em->bm->pdata, CD_RECAST, CD_CALLOC, NULL, 0, "createRepresentation recastData"); - CustomData_bmesh_init_pool(&em->bm->pdata, 0, BM_FACE); - - /* create verts and faces for detailed mesh */ - meshes = recast_polyMeshDetailGetMeshes(dmesh, &nmeshes); - polys = recast_polyMeshGetPolys(pmesh, NULL, &nvp); - dverts = recast_polyMeshDetailGetVerts(dmesh, NULL); - tris = recast_polyMeshDetailGetTris(dmesh, NULL); - - for (i = 0; i < nmeshes; i++) { - int uniquevbase = em->bm->totvert; - unsigned int vbase = meshes[4 * i + 0]; - unsigned short ndv = meshes[4 * i + 1]; - unsigned short tribase = meshes[4 * i + 2]; - unsigned short trinum = meshes[4 * i + 3]; - const unsigned short *p = &polys[i * nvp * 2]; - int nv = 0; - - for (j = 0; j < nvp; ++j) { - if (p[j] == 0xffff) break; - nv++; - } - - /* create unique verts */ - for (j = nv; j < ndv; j++) { - copy_v3_v3(co, &dverts[3 * (vbase + j)]); - SWAP(float, co[1], co[2]); - BM_vert_create(em->bm, co, NULL, BM_CREATE_NOP); - } - - /* need to rebuild entirely because array size changes */ - BM_mesh_elem_table_init(em->bm, BM_VERT); - - /* create faces */ - for (j = 0; j < trinum; j++) { - unsigned char *tri = &tris[4 * (tribase + j)]; - BMFace *newFace; - int *polygonIdx; - - for (k = 0; k < 3; k++) { - if (tri[k] < nv) - face[k] = p[tri[k]]; /* shared vertex */ - else - face[k] = uniquevbase + tri[k] - nv; /* unique vertex */ - } - newFace = BM_face_create_quad_tri(em->bm, - BM_vert_at_index(em->bm, face[0]), - BM_vert_at_index(em->bm, face[2]), - BM_vert_at_index(em->bm, face[1]), NULL, - NULL, BM_CREATE_NOP); - - /* set navigation polygon idx to the custom layer */ - polygonIdx = (int *)CustomData_bmesh_get(&em->bm->pdata, newFace->head.data, CD_RECAST); - *polygonIdx = i + 1; /* add 1 to avoid zero idx */ - } - } - - recast_destroyPolyMesh(pmesh); - recast_destroyPolyMeshDetail(dmesh); - - DEG_id_tag_update((ID *)obedit->data, OB_RECALC_DATA); - WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data); - - - ED_object_editmode_exit(C, EM_FREEDATA); - WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, obedit); - - if (createob) { - obedit->gameflag &= ~OB_COLLISION; - obedit->gameflag |= OB_NAVMESH; - obedit->body_type = OB_BODY_TYPE_NAVMESH; - } - - BKE_mesh_ensure_navmesh(obedit->data); - - return obedit; -} - -static int navmesh_create_exec(bContext *C, wmOperator *op) -{ - Scene *scene = CTX_data_scene(C); - ViewLayer *view_layer = CTX_data_view_layer(C); - LinkNode *obs = NULL; - Base *navmeshBase = NULL; - - CTX_DATA_BEGIN (C, Base *, base, selected_editable_bases) - { - if (base->object->type == OB_MESH) { - if (base->object->body_type == OB_BODY_TYPE_NAVMESH) { - if (!navmeshBase || base == view_layer->basact) { - navmeshBase = base; - } - } - else { - BLI_linklist_prepend(&obs, base->object); - } - } - } - CTX_DATA_END; - - if (obs) { - struct recast_polyMesh *pmesh = NULL; - struct recast_polyMeshDetail *dmesh = NULL; - bool ok; - unsigned int lay = 0; - - int nverts = 0, ntris = 0; - int *tris = NULL; - float *verts = NULL; - - createVertsTrisData(C, obs, &nverts, &verts, &ntris, &tris, &lay); - BLI_linklist_free(obs, NULL); - if ((ok = buildNavMesh(&scene->gm.recastData, nverts, verts, ntris, tris, &pmesh, &dmesh, op->reports))) { - createRepresentation(C, pmesh, dmesh, navmeshBase, lay); - } - - MEM_freeN(verts); - MEM_freeN(tris); - - return ok ? OPERATOR_FINISHED : OPERATOR_CANCELLED; - } - else { - BKE_report(op->reports, RPT_ERROR, "No mesh objects found"); - - return OPERATOR_CANCELLED; - } -} - -void MESH_OT_navmesh_make(wmOperatorType *ot) -{ - /* identifiers */ - ot->name = "Create Navigation Mesh"; - ot->description = "Create navigation mesh for selected objects"; - ot->idname = "MESH_OT_navmesh_make"; - - /* api callbacks */ - ot->exec = navmesh_create_exec; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; -} - -static int navmesh_face_copy_exec(bContext *C, wmOperator *op) -{ - Object *obedit = CTX_data_edit_object(C); - BMEditMesh *em = BKE_editmesh_from_object(obedit); - - /* do work here */ - BMFace *efa_act = BM_mesh_active_face_get(em->bm, false, false); - - if (efa_act) { - if (CustomData_has_layer(&em->bm->pdata, CD_RECAST)) { - BMFace *efa; - BMIter iter; - int targetPolyIdx = *(int *)CustomData_bmesh_get(&em->bm->pdata, efa_act->head.data, CD_RECAST); - targetPolyIdx = targetPolyIdx >= 0 ? targetPolyIdx : -targetPolyIdx; - - if (targetPolyIdx > 0) { - /* set target poly idx to other selected faces */ - BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) { - if (BM_elem_flag_test(efa, BM_ELEM_SELECT) && efa != efa_act) { - int *recastDataBlock = (int *)CustomData_bmesh_get(&em->bm->pdata, efa->head.data, CD_RECAST); - *recastDataBlock = targetPolyIdx; - } - } - } - else { - BKE_report(op->reports, RPT_ERROR, "Active face has no index set"); - } - } - } - - DEG_id_tag_update((ID *)obedit->data, OB_RECALC_DATA); - WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data); - - return OPERATOR_FINISHED; -} - -void MESH_OT_navmesh_face_copy(struct wmOperatorType *ot) -{ - /* identifiers */ - ot->name = "NavMesh Copy Face Index"; - ot->description = "Copy the index from the active face"; - ot->idname = "MESH_OT_navmesh_face_copy"; - - /* api callbacks */ - ot->poll = ED_operator_editmesh; - ot->exec = navmesh_face_copy_exec; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; -} - -static int compare(const void *a, const void *b) -{ - return (*(int *)a - *(int *)b); -} - -static int findFreeNavPolyIndex(BMEditMesh *em) -{ - /* construct vector of indices */ - int numfaces = em->bm->totface; - int *indices = MEM_callocN(sizeof(int) * numfaces, "findFreeNavPolyIndex(indices)"); - BMFace *ef; - BMIter iter; - int i, idx = em->bm->totface - 1, freeIdx = 1; - - /*XXX this originally went last to first, but that isn't possible anymore*/ - BM_ITER_MESH (ef, &iter, em->bm, BM_FACES_OF_MESH) { - int polyIdx = *(int *)CustomData_bmesh_get(&em->bm->pdata, ef->head.data, CD_RECAST); - indices[idx] = polyIdx; - idx--; - } - - qsort(indices, numfaces, sizeof(int), compare); - - /* search first free index */ - freeIdx = 1; - for (i = 0; i < numfaces; i++) { - if (indices[i] == freeIdx) - freeIdx++; - else if (indices[i] > freeIdx) - break; - } - - MEM_freeN(indices); - - return freeIdx; -} - -static int navmesh_face_add_exec(bContext *C, wmOperator *UNUSED(op)) -{ - Object *obedit = CTX_data_edit_object(C); - BMEditMesh *em = BKE_editmesh_from_object(obedit); - BMFace *ef; - BMIter iter; - - if (CustomData_has_layer(&em->bm->pdata, CD_RECAST)) { - int targetPolyIdx = findFreeNavPolyIndex(em); - - if (targetPolyIdx > 0) { - /* set target poly idx to selected faces */ - /*XXX this originally went last to first, but that isn't possible anymore*/ - - BM_ITER_MESH (ef, &iter, em->bm, BM_FACES_OF_MESH) { - if (BM_elem_flag_test(ef, BM_ELEM_SELECT)) { - int *recastDataBlock = (int *)CustomData_bmesh_get(&em->bm->pdata, ef->head.data, CD_RECAST); - *recastDataBlock = targetPolyIdx; - } - } - } - } - - DEG_id_tag_update((ID *)obedit->data, OB_RECALC_DATA); - WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data); - - return OPERATOR_FINISHED; -} - -void MESH_OT_navmesh_face_add(struct wmOperatorType *ot) -{ - /* identifiers */ - ot->name = "NavMesh New Face Index"; - ot->description = "Add a new index and assign it to selected faces"; - ot->idname = "MESH_OT_navmesh_face_add"; - - /* api callbacks */ - ot->poll = ED_operator_editmesh; - ot->exec = navmesh_face_add_exec; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; -} - -static int navmesh_obmode_data_poll(bContext *C) -{ - Object *ob = ED_object_active_context(C); - if (ob && (ob->mode == OB_MODE_OBJECT) && (ob->type == OB_MESH)) { - Mesh *me = ob->data; - return CustomData_has_layer(&me->pdata, CD_RECAST); - } - return false; -} - -static int navmesh_obmode_poll(bContext *C) -{ - Object *ob = ED_object_active_context(C); - if (ob && (ob->mode == OB_MODE_OBJECT) && (ob->type == OB_MESH)) { - return true; - } - return false; -} - -static int navmesh_reset_exec(bContext *C, wmOperator *UNUSED(op)) -{ - Object *ob = ED_object_active_context(C); - Mesh *me = ob->data; - - CustomData_free_layers(&me->pdata, CD_RECAST, me->totpoly); - - BKE_mesh_ensure_navmesh(me); - - DEG_id_tag_update(&me->id, OB_RECALC_DATA); - WM_event_add_notifier(C, NC_GEOM | ND_DATA, &me->id); - - return OPERATOR_FINISHED; -} - -void MESH_OT_navmesh_reset(struct wmOperatorType *ot) -{ - /* identifiers */ - ot->name = "NavMesh Reset Index Values"; - ot->description = "Assign a new index to every face"; - ot->idname = "MESH_OT_navmesh_reset"; - - /* api callbacks */ - ot->poll = navmesh_obmode_poll; - ot->exec = navmesh_reset_exec; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; -} - -static int navmesh_clear_exec(bContext *C, wmOperator *UNUSED(op)) -{ - Object *ob = ED_object_active_context(C); - Mesh *me = ob->data; - - CustomData_free_layers(&me->pdata, CD_RECAST, me->totpoly); - - DEG_id_tag_update(&me->id, OB_RECALC_DATA); - WM_event_add_notifier(C, NC_GEOM | ND_DATA, &me->id); - - return OPERATOR_FINISHED; -} - -void MESH_OT_navmesh_clear(struct wmOperatorType *ot) -{ - /* identifiers */ - ot->name = "NavMesh Clear Data"; - ot->description = "Remove navmesh data from this mesh"; - ot->idname = "MESH_OT_navmesh_clear"; - - /* api callbacks */ - ot->poll = navmesh_obmode_data_poll; - ot->exec = navmesh_clear_exec; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; -} diff --git a/source/blender/editors/mesh/mesh_ops.c b/source/blender/editors/mesh/mesh_ops.c index b9920f9deca..a2c996c7f42 100644 --- a/source/blender/editors/mesh/mesh_ops.c +++ b/source/blender/editors/mesh/mesh_ops.c @@ -197,14 +197,6 @@ void ED_operatortypes_mesh(void) WM_operatortype_append(MESH_OT_bisect); WM_operatortype_append(MESH_OT_symmetrize); WM_operatortype_append(MESH_OT_symmetry_snap); - -#ifdef WITH_GAMEENGINE - WM_operatortype_append(MESH_OT_navmesh_make); - WM_operatortype_append(MESH_OT_navmesh_face_copy); - WM_operatortype_append(MESH_OT_navmesh_face_add); - WM_operatortype_append(MESH_OT_navmesh_reset); - WM_operatortype_append(MESH_OT_navmesh_clear); -#endif } #if 0 /* UNUSED, remove? */ diff --git a/source/blender/editors/object/CMakeLists.txt b/source/blender/editors/object/CMakeLists.txt index 646b8137b2d..e25b04668bc 100644 --- a/source/blender/editors/object/CMakeLists.txt +++ b/source/blender/editors/object/CMakeLists.txt @@ -50,7 +50,6 @@ set(SRC object_facemap_ops.c object_group.c object_hook.c - object_lod.c object_modes.c object_modifier.c object_ops.c @@ -72,10 +71,6 @@ if(WITH_PYTHON) add_definitions(-DWITH_PYTHON) endif() -if(WITH_GAMEENGINE) - add_definitions(-DWITH_GAMEENGINE) -endif() - if(WITH_INTERNATIONAL) add_definitions(-DWITH_INTERNATIONAL) endif() diff --git a/source/blender/editors/object/object_add.c b/source/blender/editors/object/object_add.c index 4abd80a18e8..6f9f18d301e 100644 --- a/source/blender/editors/object/object_add.c +++ b/source/blender/editors/object/object_add.c @@ -48,7 +48,6 @@ #include "DNA_lightprobe_types.h" #include "DNA_scene_types.h" #include "DNA_vfont_types.h" -#include "DNA_actuator_types.h" #include "DNA_gpencil_types.h" #include "BLI_utildefines.h" @@ -88,7 +87,6 @@ #include "BKE_object.h" #include "BKE_particle.h" #include "BKE_report.h" -#include "BKE_sca.h" #include "BKE_scene.h" #include "BKE_screen.h" #include "BKE_speaker.h" @@ -440,12 +438,6 @@ Object *ED_object_add_type( /* more editor stuff */ ED_object_base_init_transform(C, view_layer->basact, loc, rot); - /* Ignore collisions by default for non-mesh objects */ - if (type != OB_MESH) { - ob->body_type = OB_BODY_TYPE_NO_COLLISION; - ob->gameflag &= ~(OB_SENSOR | OB_RIGID_BODY | OB_SOFT_BODY | OB_COLLISION | OB_CHARACTER | OB_OCCLUDER | OB_DYNAMIC | OB_NAVMESH); /* copied from rna_object.c */ - } - /* TODO(sergey): This is weird to manually tag objects for update, better to * use DEG_id_tag_update here perhaps. */ @@ -1347,8 +1339,6 @@ static void copy_object_set_idnew(bContext *C) } CTX_DATA_END; - set_sca_new_poins(); - BKE_main_id_clear_newpoins(bmain); } @@ -1502,7 +1492,6 @@ static void make_object_duplilist_real(bContext *C, Scene *scene, Base *base, /* Remap new object to itself, and clear again newid pointer of orig object. */ BKE_libblock_relink_to_newid(&ob_dst->id); - set_sca_new_poins_ob(ob_dst); DEG_id_tag_update(&ob_dst->id, OB_RECALC_DATA); @@ -1659,10 +1648,6 @@ static void curvetomesh(Depsgraph *depsgraph, Scene *scene, Object *ob) if (ob->type == OB_MESH) { BKE_object_free_modifiers(ob, 0); - - /* Game engine defaults for mesh objects */ - ob->body_type = OB_BODY_TYPE_STATIC; - ob->gameflag = OB_PROP | OB_COLLISION; } } @@ -2277,25 +2262,10 @@ static Base *object_add_duplicate_internal(Main *bmain, Scene *scene, ViewLayer } if (dupflag & USER_DUP_ACT) { - bActuator *act; - BKE_animdata_copy_id_action((ID *)obn->data, true); if (key) { BKE_animdata_copy_id_action((ID *)key, true); } - - /* Update the duplicated action in the action actuators */ - /* XXX TODO this code is all wrong! actact->act is user-refcounted (see readfile.c), - * and what about other ID pointers of other BGE logic bricks, - * and since this is object-level, why is it only ran if obdata was duplicated??? -mont29 */ - for (act = obn->actuators.first; act; act = act->next) { - if (act->type == ACT_ACTION) { - bActionActuator *actact = (bActionActuator *) act->data; - if (ob->adt && actact->act == ob->adt->action) { - actact->act = obn->adt->action; - } - } - } } if (dupflag & USER_DUP_MAT) { @@ -2331,8 +2301,6 @@ Base *ED_object_add_duplicate(Main *bmain, Scene *scene, ViewLayer *view_layer, Base *basen; Object *ob; - clear_sca_new_poins(); /* BGE logic */ - basen = object_add_duplicate_internal(bmain, scene, view_layer, base->object, dupflag); if (basen == NULL) { return NULL; @@ -2342,7 +2310,6 @@ Base *ED_object_add_duplicate(Main *bmain, Scene *scene, ViewLayer *view_layer, /* link own references to the newly duplicated data [#26816] */ BKE_libblock_relink_to_newid(&ob->id); - set_sca_new_poins_ob(ob); /* DAG_relations_tag_update(bmain); */ /* caller must do */ @@ -2364,8 +2331,6 @@ static int duplicate_exec(bContext *C, wmOperator *op) const bool linked = RNA_boolean_get(op->ptr, "linked"); int dupflag = (linked) ? 0 : U.dupflag; - clear_sca_new_poins(); /* BGE logic */ - CTX_DATA_BEGIN (C, Base *, base, selected_bases) { Base *basen = object_add_duplicate_internal(bmain, scene, view_layer, base->object, dupflag); @@ -2449,8 +2414,6 @@ static int add_named_exec(bContext *C, wmOperator *op) } /* prepare dupli */ - clear_sca_new_poins(); /* BGE logic */ - basen = object_add_duplicate_internal(bmain, scene, view_layer, ob, dupflag); if (basen == NULL) { diff --git a/source/blender/editors/object/object_constraint.c b/source/blender/editors/object/object_constraint.c index ca742222d81..95778b73e55 100644 --- a/source/blender/editors/object/object_constraint.c +++ b/source/blender/editors/object/object_constraint.c @@ -1615,11 +1615,6 @@ static bool get_new_constraint_target(bContext *C, int con_type, Object **tar_ob only_ob = true; add = false; break; - - /* object only - add here is ok? */ - case CONSTRAINT_TYPE_RIGIDBODYJOINT: - only_ob = true; - break; } /* if the active Object is Armature, and we can search for bones, do so... */ @@ -1748,10 +1743,6 @@ static int constraint_add_exec(bContext *C, wmOperator *op, Object *ob, ListBase if (type == CONSTRAINT_TYPE_NULL) { return OPERATOR_CANCELLED; } - if ((type == CONSTRAINT_TYPE_RIGIDBODYJOINT) && (list != &ob->constraints)) { - BKE_report(op->reports, RPT_ERROR, "Rigid Body Joint constraint can only be added to objects"); - return OPERATOR_CANCELLED; - } if ((type == CONSTRAINT_TYPE_KINEMATIC) && ((!pchan) || (list != &pchan->constraints))) { BKE_report(op->reports, RPT_ERROR, "IK constraint can only be added to bones"); return OPERATOR_CANCELLED; diff --git a/source/blender/editors/object/object_edit.c b/source/blender/editors/object/object_edit.c index e884989b6b5..5565565c679 100644 --- a/source/blender/editors/object/object_edit.c +++ b/source/blender/editors/object/object_edit.c @@ -51,7 +51,6 @@ #include "DNA_group_types.h" #include "DNA_material_types.h" #include "DNA_meta_types.h" -#include "DNA_property_types.h" #include "DNA_scene_types.h" #include "DNA_object_types.h" #include "DNA_object_force_types.h" @@ -80,8 +79,6 @@ #include "BKE_object.h" #include "BKE_paint.h" #include "BKE_pointcache.h" -#include "BKE_property.h" -#include "BKE_sca.h" #include "BKE_softbody.h" #include "BKE_modifier.h" #include "BKE_editlattice.h" @@ -613,102 +610,6 @@ void OBJECT_OT_posemode_toggle(wmOperatorType *ot) ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } -static void copymenu_properties(ViewLayer *view_layer, Object *ob) -{ -//XXX no longer used - to be removed - replaced by game_properties_copy_exec - bProperty *prop; - Base *base; - int nr, tot = 0; - char *str; - - prop = ob->prop.first; - while (prop) { - tot++; - prop = prop->next; - } - - str = MEM_callocN(50 + 33 * tot, "copymenu prop"); - - if (tot) - strcpy(str, "Copy Property %t|Replace All|Merge All|%l"); - else - strcpy(str, "Copy Property %t|Clear All (no properties on active)"); - - tot = 0; - prop = ob->prop.first; - while (prop) { - tot++; - strcat(str, "|"); - strcat(str, prop->name); - prop = prop->next; - } - - nr = pupmenu(str); - - if (nr == 1 || nr == 2) { - for (base = FIRSTBASE(view_layer); base; base = base->next) { - if ((base != BASACT(view_layer)) && (TESTBASELIB(base))) { - if (nr == 1) { /* replace */ - BKE_bproperty_copy_list(&base->object->prop, &ob->prop); - } - else { - for (prop = ob->prop.first; prop; prop = prop->next) { - BKE_bproperty_object_set(base->object, prop); - } - } - } - } - } - else if (nr > 0) { - prop = BLI_findlink(&ob->prop, nr - 4); /* account for first 3 menu items & menu index starting at 1*/ - - if (prop) { - for (base = FIRSTBASE(view_layer); base; base = base->next) { - if ((base != BASACT(view_layer)) && (TESTBASELIB(base))) { - BKE_bproperty_object_set(base->object, prop); - } - } - } - } - MEM_freeN(str); - -} - -static void copymenu_logicbricks(ViewLayer *view_layer, Object *ob) -{ -//XXX no longer used - to be removed - replaced by logicbricks_copy_exec - Base *base; - - for (base = FIRSTBASE(view_layer); base; base = base->next) { - if (base->object != ob) { - if (TESTBASELIB(base)) { - - /* first: free all logic */ - free_sensors(&base->object->sensors); - unlink_controllers(&base->object->controllers); - free_controllers(&base->object->controllers); - unlink_actuators(&base->object->actuators); - free_actuators(&base->object->actuators); - - /* now copy it, this also works without logicbricks! */ - clear_sca_new_poins_ob(ob); - copy_sensors(&base->object->sensors, &ob->sensors, 0); - copy_controllers(&base->object->controllers, &ob->controllers, 0); - copy_actuators(&base->object->actuators, &ob->actuators, 0); - set_sca_new_poins_ob(base->object); - - /* some menu settings */ - base->object->scavisflag = ob->scavisflag; - base->object->scaflag = ob->scaflag; - - /* set the initial state */ - base->object->state = ob->state; - base->object->init_state = ob->init_state; - } - } - } -} - /* both pointers should exist */ static void copy_texture_space(Object *to, Object *ob) { @@ -776,15 +677,8 @@ static void copy_attr(Main *bmain, Scene *scene, ViewLayer *view_layer, short ev /* obedit_copymenu(); */ return; } - if (event == 9) { - copymenu_properties(view_layer, ob); - return; - } - else if (event == 10) { - copymenu_logicbricks(view_layer, ob); - return; - } - else if (event == 24) { + + if (event == 24) { /* moved to BKE_object_link_modifiers */ /* copymenu_modifiers(bmain, scene, v3d, ob); */ return; @@ -832,30 +726,6 @@ static void copy_attr(Main *bmain, Scene *scene, ViewLayer *view_layer, short ev if (ob->dup_group) id_us_plus(&ob->dup_group->id); } - else if (event == 7) { /* mass */ - base->object->mass = ob->mass; - } - else if (event == 8) { /* damping */ - base->object->damping = ob->damping; - base->object->rdamping = ob->rdamping; - } - else if (event == 11) { /* all physical attributes */ - base->object->gameflag = ob->gameflag; - base->object->inertia = ob->inertia; - base->object->formfactor = ob->formfactor; - base->object->damping = ob->damping; - base->object->rdamping = ob->rdamping; - base->object->min_vel = ob->min_vel; - base->object->max_vel = ob->max_vel; - base->object->min_angvel = ob->min_angvel; - base->object->max_angvel = ob->max_angvel; - if (ob->gameflag & OB_BOUNDS) { - base->object->collision_boundtype = ob->collision_boundtype; - } - base->object->margin = ob->margin; - base->object->bsoft = copy_bulletsoftbody(ob->bsoft, 0); - - } else if (event == 17) { /* tex space */ copy_texture_space(base->object, ob); } @@ -1641,393 +1511,6 @@ void OBJECT_OT_mode_set(wmOperatorType *ot) RNA_def_property_flag(prop, PROP_SKIP_SAVE); } -/************************ Game Properties ***********************/ - -static int game_property_new_exec(bContext *C, wmOperator *op) -{ - Object *ob = CTX_data_active_object(C); - bProperty *prop; - char name[MAX_NAME]; - int type = RNA_enum_get(op->ptr, "type"); - - prop = BKE_bproperty_new(type); - BLI_addtail(&ob->prop, prop); - - RNA_string_get(op->ptr, "name", name); - if (name[0] != '\0') { - BLI_strncpy(prop->name, name, sizeof(prop->name)); - } - - BLI_uniquename(&ob->prop, prop, DATA_("Property"), '.', offsetof(bProperty, name), sizeof(prop->name)); - - WM_event_add_notifier(C, NC_LOGIC, NULL); - return OPERATOR_FINISHED; -} - - -void OBJECT_OT_game_property_new(wmOperatorType *ot) -{ - /* identifiers */ - ot->name = "New Game Property"; - ot->description = "Create a new property available to the game engine"; - ot->idname = "OBJECT_OT_game_property_new"; - - /* api callbacks */ - ot->exec = game_property_new_exec; - ot->poll = ED_operator_object_active_editable; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; - - RNA_def_enum(ot->srna, "type", rna_enum_gameproperty_type_items, GPROP_FLOAT, "Type", "Type of game property to add"); - RNA_def_string(ot->srna, "name", NULL, MAX_NAME, "Name", "Name of the game property to add"); -} - -static int game_property_remove_exec(bContext *C, wmOperator *op) -{ - Object *ob = CTX_data_active_object(C); - bProperty *prop; - int index = RNA_int_get(op->ptr, "index"); - - if (!ob) - return OPERATOR_CANCELLED; - - prop = BLI_findlink(&ob->prop, index); - - if (prop) { - BLI_remlink(&ob->prop, prop); - BKE_bproperty_free(prop); - - WM_event_add_notifier(C, NC_LOGIC, NULL); - return OPERATOR_FINISHED; - } - else { - return OPERATOR_CANCELLED; - } -} - -void OBJECT_OT_game_property_remove(wmOperatorType *ot) -{ - /* identifiers */ - ot->name = "Remove Game Property"; - ot->description = "Remove game property"; - ot->idname = "OBJECT_OT_game_property_remove"; - - /* api callbacks */ - ot->exec = game_property_remove_exec; - ot->poll = ED_operator_object_active_editable; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; - - RNA_def_int(ot->srna, "index", 0, 0, INT_MAX, "Index", "Property index to remove ", 0, INT_MAX); -} - -#define GAME_PROPERTY_MOVE_UP 1 -#define GAME_PROPERTY_MOVE_DOWN -1 - -static int game_property_move(bContext *C, wmOperator *op) -{ - Object *ob = CTX_data_active_object(C); - bProperty *prop; - bProperty *otherprop = NULL; - const int index = RNA_int_get(op->ptr, "index"); - const int dir = RNA_enum_get(op->ptr, "direction"); - - if (ob == NULL) - return OPERATOR_CANCELLED; - - prop = BLI_findlink(&ob->prop, index); - /* invalid index */ - if (prop == NULL) - return OPERATOR_CANCELLED; - - if (dir == GAME_PROPERTY_MOVE_UP) { - otherprop = prop->prev; - } - else if (dir == GAME_PROPERTY_MOVE_DOWN) { - otherprop = prop->next; - } - else { - BLI_assert(0); - } - - if (prop && otherprop) { - BLI_listbase_swaplinks(&ob->prop, prop, otherprop); - - WM_event_add_notifier(C, NC_LOGIC, NULL); - return OPERATOR_FINISHED; - } - else { - return OPERATOR_CANCELLED; - } -} - -void OBJECT_OT_game_property_move(wmOperatorType *ot) -{ - static const EnumPropertyItem direction_property_move[] = { - {GAME_PROPERTY_MOVE_UP, "UP", 0, "Up", ""}, - {GAME_PROPERTY_MOVE_DOWN, "DOWN", 0, "Down", ""}, - {0, NULL, 0, NULL, NULL} - }; - PropertyRNA *prop; - - /* identifiers */ - ot->name = "Move Game Property"; - ot->description = "Move game property"; - ot->idname = "OBJECT_OT_game_property_move"; - - /* api callbacks */ - ot->exec = game_property_move; - ot->poll = ED_operator_object_active_editable; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; - - /* properties */ - prop = RNA_def_int(ot->srna, "index", 0, 0, INT_MAX, "Index", "Property index to move", 0, INT_MAX); - RNA_def_property_flag(prop, PROP_HIDDEN); - RNA_def_enum(ot->srna, "direction", direction_property_move, 0, "Direction", - "Direction for moving the property"); -} - -#undef GAME_PROPERTY_MOVE_UP -#undef GAME_PROPERTY_MOVE_DOWN - -#define COPY_PROPERTIES_REPLACE 1 -#define COPY_PROPERTIES_MERGE 2 -#define COPY_PROPERTIES_COPY 3 - -static const EnumPropertyItem game_properties_copy_operations[] = { - {COPY_PROPERTIES_REPLACE, "REPLACE", 0, "Replace Properties", ""}, - {COPY_PROPERTIES_MERGE, "MERGE", 0, "Merge Properties", ""}, - {COPY_PROPERTIES_COPY, "COPY", 0, "Copy a Property", ""}, - {0, NULL, 0, NULL, NULL} -}; - -static const EnumPropertyItem *gameprops_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free) -{ - Object *ob = ED_object_active_context(C); - EnumPropertyItem tmp = {0, "", 0, "", ""}; - EnumPropertyItem *item = NULL; - bProperty *prop; - int a, totitem = 0; - - if (!ob) - return DummyRNA_NULL_items; - - for (a = 1, prop = ob->prop.first; prop; prop = prop->next, a++) { - tmp.value = a; - tmp.identifier = prop->name; - tmp.name = prop->name; - RNA_enum_item_add(&item, &totitem, &tmp); - } - - RNA_enum_item_end(&item, &totitem); - *r_free = true; - - return item; -} - -static int game_property_copy_exec(bContext *C, wmOperator *op) -{ - Object *ob = ED_object_active_context(C); - bProperty *prop; - int type = RNA_enum_get(op->ptr, "operation"); - int propid = RNA_enum_get(op->ptr, "property"); - - if (propid > 0) { /* copy */ - prop = BLI_findlink(&ob->prop, propid - 1); - - if (prop) { - CTX_DATA_BEGIN(C, Object *, ob_iter, selected_editable_objects) - { - if (ob != ob_iter) - BKE_bproperty_object_set(ob_iter, prop); - } CTX_DATA_END; - } - } - - else { - CTX_DATA_BEGIN(C, Object *, ob_iter, selected_editable_objects) - { - if (ob != ob_iter) { - if (type == COPY_PROPERTIES_REPLACE) { - BKE_bproperty_copy_list(&ob_iter->prop, &ob->prop); - } - else { - /* merge - the default when calling with no argument */ - for (prop = ob->prop.first; prop; prop = prop->next) { - BKE_bproperty_object_set(ob_iter, prop); - } - } - } - } - CTX_DATA_END; - } - - return OPERATOR_FINISHED; -} - -void OBJECT_OT_game_property_copy(wmOperatorType *ot) -{ - PropertyRNA *prop; - /* identifiers */ - ot->name = "Copy Game Property"; - ot->idname = "OBJECT_OT_game_property_copy"; - ot->description = "Copy/merge/replace a game property from active object to all selected objects"; - - /* api callbacks */ - ot->exec = game_property_copy_exec; - ot->poll = ED_operator_object_active_editable; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; - - RNA_def_enum(ot->srna, "operation", game_properties_copy_operations, 3, "Operation", ""); - prop = RNA_def_enum(ot->srna, "property", DummyRNA_NULL_items, 0, "Property", "Properties to copy"); - RNA_def_property_flag(prop, PROP_SKIP_SAVE | PROP_ENUM_NO_TRANSLATE); - RNA_def_enum_funcs(prop, gameprops_itemf); - ot->prop = prop; -} - -static int game_property_clear_exec(bContext *C, wmOperator *UNUSED(op)) -{ - CTX_DATA_BEGIN(C, Object *, ob_iter, selected_editable_objects) - { - BKE_bproperty_free_list(&ob_iter->prop); - } - CTX_DATA_END; - - WM_event_add_notifier(C, NC_LOGIC, NULL); - return OPERATOR_FINISHED; -} -void OBJECT_OT_game_property_clear(wmOperatorType *ot) -{ - /* identifiers */ - ot->name = "Clear Game Properties"; - ot->idname = "OBJECT_OT_game_property_clear"; - ot->description = "Remove all game properties from all selected objects"; - - /* api callbacks */ - ot->exec = game_property_clear_exec; - ot->poll = ED_operator_object_active_editable; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; -} - -/************************ Copy Logic Bricks ***********************/ - -static int logicbricks_copy_exec(bContext *C, wmOperator *UNUSED(op)) -{ - Object *ob = ED_object_active_context(C); - - CTX_DATA_BEGIN(C, Object *, ob_iter, selected_editable_objects) - { - if (ob != ob_iter) { - /* first: free all logic */ - free_sensors(&ob_iter->sensors); - unlink_controllers(&ob_iter->controllers); - free_controllers(&ob_iter->controllers); - unlink_actuators(&ob_iter->actuators); - free_actuators(&ob_iter->actuators); - - /* now copy it, this also works without logicbricks! */ - clear_sca_new_poins_ob(ob); - copy_sensors(&ob_iter->sensors, &ob->sensors, 0); - copy_controllers(&ob_iter->controllers, &ob->controllers, 0); - copy_actuators(&ob_iter->actuators, &ob->actuators, 0); - set_sca_new_poins_ob(ob_iter); - - /* some menu settings */ - ob_iter->scavisflag = ob->scavisflag; - ob_iter->scaflag = ob->scaflag; - - /* set the initial state */ - ob_iter->state = ob->state; - ob_iter->init_state = ob->init_state; - - if (ob_iter->totcol == ob->totcol) { - ob_iter->actcol = ob->actcol; - WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob_iter); - } - } - } - CTX_DATA_END; - - WM_event_add_notifier(C, NC_LOGIC, NULL); - - return OPERATOR_FINISHED; -} - -void OBJECT_OT_logic_bricks_copy(wmOperatorType *ot) -{ - /* identifiers */ - ot->name = "Copy Logic Bricks to Selected"; - ot->description = "Copy logic bricks to other selected objects"; - ot->idname = "OBJECT_OT_logic_bricks_copy"; - - /* api callbacks */ - ot->exec = logicbricks_copy_exec; - ot->poll = ED_operator_object_active_editable; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; -} - -static int game_physics_copy_exec(bContext *C, wmOperator *UNUSED(op)) -{ - Object *ob = ED_object_active_context(C); - - CTX_DATA_BEGIN(C, Object *, ob_iter, selected_editable_objects) - { - if (ob != ob_iter) { - ob_iter->gameflag = ob->gameflag; - ob_iter->gameflag2 = ob->gameflag2; - ob_iter->inertia = ob->inertia; - ob_iter->formfactor = ob->formfactor; - ob_iter->damping = ob->damping; - ob_iter->rdamping = ob->rdamping; - ob_iter->min_vel = ob->min_vel; - ob_iter->max_vel = ob->max_vel; - ob_iter->min_angvel = ob->min_angvel; - ob_iter->max_angvel = ob->max_angvel; - ob_iter->obstacleRad = ob->obstacleRad; - ob_iter->mass = ob->mass; - copy_v3_v3(ob_iter->anisotropicFriction, ob->anisotropicFriction); - ob_iter->collision_boundtype = ob->collision_boundtype; - ob_iter->margin = ob->margin; - ob_iter->bsoft = copy_bulletsoftbody(ob->bsoft, 0); - if (ob->restrictflag & OB_RESTRICT_RENDER) - ob_iter->restrictflag |= OB_RESTRICT_RENDER; - else - ob_iter->restrictflag &= ~OB_RESTRICT_RENDER; - - ob_iter->col_group = ob->col_group; - ob_iter->col_mask = ob->col_mask; - } - } - CTX_DATA_END; - - return OPERATOR_FINISHED; -} - -void OBJECT_OT_game_physics_copy(struct wmOperatorType *ot) -{ - /* identifiers */ - ot->name = "Copy Game Physics Properties to Selected"; - ot->description = "Copy game physics properties to other selected objects"; - ot->idname = "OBJECT_OT_game_physics_copy"; - - /* api callbacks */ - ot->exec = game_physics_copy_exec; - ot->poll = ED_operator_object_active_editable; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; -} - bool ED_object_editmode_calc_active_center(Object *obedit, const bool select_only, float r_center[3]) { switch (obedit->type) { diff --git a/source/blender/editors/object/object_intern.h b/source/blender/editors/object/object_intern.h index 75117ccdce3..5025ca5bb96 100644 --- a/source/blender/editors/object/object_intern.h +++ b/source/blender/editors/object/object_intern.h @@ -87,14 +87,6 @@ void OBJECT_OT_paths_update(struct wmOperatorType *ot); void OBJECT_OT_paths_clear(struct wmOperatorType *ot); void OBJECT_OT_forcefield_toggle(struct wmOperatorType *ot); -void OBJECT_OT_game_property_new(struct wmOperatorType *ot); -void OBJECT_OT_game_property_remove(struct wmOperatorType *ot); -void OBJECT_OT_game_property_copy(struct wmOperatorType *ot); -void OBJECT_OT_game_property_clear(struct wmOperatorType *ot); -void OBJECT_OT_game_property_move(struct wmOperatorType *ot); -void OBJECT_OT_logic_bricks_copy(struct wmOperatorType *ot); -void OBJECT_OT_game_physics_copy(struct wmOperatorType *ot); - void OBJECT_OT_move_to_collection(struct wmOperatorType *ot); /* object_select.c */ diff --git a/source/blender/editors/object/object_lod.c b/source/blender/editors/object/object_lod.c deleted file mode 100644 index ced306178b8..00000000000 --- a/source/blender/editors/object/object_lod.c +++ /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) Blender Foundation - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file blender/editors/object/object_lod.c - * \ingroup edobj - */ - -#include "DNA_object_types.h" - -#include "BKE_context.h" - -#include "WM_api.h" -#include "WM_types.h" - -#include "RNA_access.h" -#include "RNA_define.h" - -#include "ED_screen.h" -#include "ED_object.h" - -#ifdef WITH_GAMEENGINE -# include "BKE_object.h" - -# include "RNA_enum_types.h" -#endif - -#include "object_intern.h" - -static int object_lod_add_exec(bContext *C, wmOperator *UNUSED(op)) -{ - Object *ob = ED_object_context(C); - -#ifdef WITH_GAMEENGINE - BKE_object_lod_add(ob); -#else - (void)ob; -#endif - - return OPERATOR_FINISHED; -} - -void OBJECT_OT_lod_add(wmOperatorType *ot) -{ - /* identifiers */ - ot->name = "Add Level of Detail"; - ot->description = "Add a level of detail to this object"; - ot->idname = "OBJECT_OT_lod_add"; - - /* api callbacks */ - ot->exec = object_lod_add_exec; - ot->poll = ED_operator_object_active; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; -} - -static int object_lod_remove_exec(bContext *C, wmOperator *op) -{ - Object *ob = ED_object_context(C); - int index = RNA_int_get(op->ptr, "index"); - -#ifdef WITH_GAMEENGINE - if (!BKE_object_lod_remove(ob, index)) - return OPERATOR_CANCELLED; -#else - (void)ob; - (void)index; -#endif - - WM_event_add_notifier(C, NC_OBJECT | ND_LOD, CTX_wm_view3d(C)); - return OPERATOR_FINISHED; -} - -void OBJECT_OT_lod_remove(wmOperatorType *ot) -{ - /* identifiers */ - ot->name = "Remove Level of Detail"; - ot->description = "Remove a level of detail from this object"; - ot->idname = "OBJECT_OT_lod_remove"; - - /* api callbacks */ - ot->exec = object_lod_remove_exec; - ot->poll = ED_operator_object_active; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; - - /* properties */ - ot->prop = RNA_def_int(ot->srna, "index", 1, 1, INT_MAX, "Index", "", 1, INT_MAX); -} diff --git a/source/blender/editors/object/object_ops.c b/source/blender/editors/object/object_ops.c index 66dc17fe77d..c4c86b3932d 100644 --- a/source/blender/editors/object/object_ops.c +++ b/source/blender/editors/object/object_ops.c @@ -212,14 +212,6 @@ void ED_operatortypes_object(void) WM_operatortype_append(TRANSFORM_OT_vertex_warp); - WM_operatortype_append(OBJECT_OT_game_property_new); - WM_operatortype_append(OBJECT_OT_game_property_remove); - WM_operatortype_append(OBJECT_OT_game_property_copy); - WM_operatortype_append(OBJECT_OT_game_property_clear); - WM_operatortype_append(OBJECT_OT_game_property_move); - WM_operatortype_append(OBJECT_OT_logic_bricks_copy); - WM_operatortype_append(OBJECT_OT_game_physics_copy); - WM_operatortype_append(OBJECT_OT_move_to_collection); WM_operatortype_append(OBJECT_OT_shape_key_add); @@ -249,9 +241,6 @@ void ED_operatortypes_object(void) WM_operatortype_append(OBJECT_OT_unlink_data); WM_operatortype_append(OBJECT_OT_laplaciandeform_bind); - WM_operatortype_append(OBJECT_OT_lod_add); - WM_operatortype_append(OBJECT_OT_lod_remove); - WM_operatortype_append(TRANSFORM_OT_vertex_random); WM_operatortype_append(OBJECT_OT_data_transfer); @@ -327,9 +316,6 @@ void ED_keymap_object(wmKeyConfig *keyconf) ED_keymap_proportional_cycle(keyconf, keymap); ED_keymap_proportional_obmode(keyconf, keymap); - /* game-engine only, leave free for users to define */ - WM_keymap_add_item(keymap, "VIEW3D_OT_game_start", PKEY, KM_PRESS, 0, 0); - kmi = WM_keymap_add_item(keymap, "OBJECT_OT_select_all", AKEY, KM_PRESS, 0, 0); RNA_enum_set(kmi->ptr, "action", SEL_TOGGLE); kmi = WM_keymap_add_item(keymap, "OBJECT_OT_select_all", IKEY, KM_PRESS, KM_CTRL, 0); diff --git a/source/blender/editors/object/object_relations.c b/source/blender/editors/object/object_relations.c index 417c32a71e9..0e0f2784936 100644 --- a/source/blender/editors/object/object_relations.c +++ b/source/blender/editors/object/object_relations.c @@ -89,7 +89,6 @@ #include "BKE_node.h" #include "BKE_object.h" #include "BKE_report.h" -#include "BKE_sca.h" #include "BKE_scene.h" #include "BKE_speaker.h" #include "BKE_texture.h" @@ -1681,8 +1680,6 @@ static void single_object_users(Main *bmain, Scene *scene, View3D *v3d, const in { Group *group, *groupn; - clear_sca_new_poins(); /* BGE logic */ - /* duplicate all the objects of the scene */ SceneCollection *msc = BKE_collection_master(&scene->id); single_object_users_scene_collection(bmain, scene, msc, flag, copy_groups); @@ -1728,8 +1725,6 @@ static void single_object_users(Main *bmain, Scene *scene, View3D *v3d, const in /* object and group pointers */ libblock_relink_scene_collection(msc); - - set_sca_new_poins(); } /* not an especially efficient function, only added so the single user diff --git a/source/blender/editors/object/object_select.c b/source/blender/editors/object/object_select.c index cd1300dd52e..d958381efe7 100644 --- a/source/blender/editors/object/object_select.c +++ b/source/blender/editors/object/object_select.c @@ -37,7 +37,6 @@ #include "DNA_group_types.h" #include "DNA_material_types.h" #include "DNA_modifier_types.h" -#include "DNA_property_types.h" #include "DNA_scene_types.h" #include "DNA_armature_types.h" #include "DNA_lamp_types.h" @@ -59,7 +58,6 @@ #include "BKE_object.h" #include "BKE_particle.h" #include "BKE_paint.h" -#include "BKE_property.h" #include "BKE_report.h" #include "BKE_scene.h" #include "BKE_workspace.h" @@ -504,9 +502,8 @@ enum { OBJECT_GRPSEL_HOOK = 7, OBJECT_GRPSEL_PASS = 8, OBJECT_GRPSEL_COLOR = 9, - OBJECT_GRPSEL_PROPERTIES = 10, - OBJECT_GRPSEL_KEYINGSET = 11, - OBJECT_GRPSEL_LAMP_TYPE = 12, + OBJECT_GRPSEL_KEYINGSET = 10, + OBJECT_GRPSEL_LAMP_TYPE = 11, }; static const EnumPropertyItem prop_select_grouped_types[] = { @@ -520,7 +517,6 @@ static const EnumPropertyItem prop_select_grouped_types[] = { {OBJECT_GRPSEL_HOOK, "HOOK", 0, "Hook", ""}, {OBJECT_GRPSEL_PASS, "PASS", 0, "Pass", "Render pass Index"}, {OBJECT_GRPSEL_COLOR, "COLOR", 0, "Color", "Object Color"}, - {OBJECT_GRPSEL_PROPERTIES, "PROPERTIES", 0, "Properties", "Game Properties"}, {OBJECT_GRPSEL_KEYINGSET, "KEYINGSET", 0, "Keying Set", "Objects included in active Keying Set"}, {OBJECT_GRPSEL_LAMP_TYPE, "LAMP_TYPE", 0, "Lamp Type", "Matching lamp types"}, {0, NULL, 0, NULL, NULL} @@ -773,33 +769,6 @@ static bool select_grouped_color(bContext *C, Object *ob) return changed; } -static bool objects_share_gameprop(Object *a, Object *b) -{ - bProperty *prop; - - for (prop = a->prop.first; prop; prop = prop->next) { - if (BKE_bproperty_object_get(b, prop->name)) { - return 1; - } - } - return 0; -} - -static bool select_grouped_gameprops(bContext *C, Object *ob) -{ - bool changed = false; - - CTX_DATA_BEGIN (C, Base *, base, selectable_bases) - { - if (((base->flag & BASE_SELECTED) == 0) && (objects_share_gameprop(base->object, ob))) { - ED_object_base_select(base, BA_SELECT); - changed = true; - } - } - CTX_DATA_END; - return changed; -} - static bool select_grouped_keyingset(bContext *C, Object *UNUSED(ob), ReportList *reports) { KeyingSet *ks = ANIM_scene_get_active_keyingset(CTX_data_scene(C)); @@ -907,9 +876,6 @@ static int object_select_grouped_exec(bContext *C, wmOperator *op) case OBJECT_GRPSEL_COLOR: changed |= select_grouped_color(C, ob); break; - case OBJECT_GRPSEL_PROPERTIES: - changed |= select_grouped_gameprops(C, ob); - break; case OBJECT_GRPSEL_KEYINGSET: changed |= select_grouped_keyingset(C, ob, op->reports); break; diff --git a/source/blender/editors/screen/screen_ops.c b/source/blender/editors/screen/screen_ops.c index c944d94fac5..25d5fbbdc4c 100644 --- a/source/blender/editors/screen/screen_ops.c +++ b/source/blender/editors/screen/screen_ops.c @@ -288,11 +288,6 @@ int ED_operator_nla_active(bContext *C) return ed_spacetype_test(C, SPACE_NLA); } -int ED_operator_logic_active(bContext *C) -{ - return ed_spacetype_test(C, SPACE_LOGIC); -} - int ED_operator_info_active(bContext *C) { return ed_spacetype_test(C, SPACE_INFO); diff --git a/source/blender/editors/sculpt_paint/paint_image_proj.c b/source/blender/editors/sculpt_paint/paint_image_proj.c index ef125da46a7..4eea4fed9b6 100644 --- a/source/blender/editors/sculpt_paint/paint_image_proj.c +++ b/source/blender/editors/sculpt_paint/paint_image_proj.c @@ -5693,7 +5693,7 @@ static bool proj_paint_add_slot(bContext *C, wmOperator *op) Object *ob = CTX_data_active_object(C); Scene *scene = CTX_data_scene(C); Material *ma; - bool is_bi = BKE_scene_uses_blender_internal(scene) || BKE_scene_uses_blender_game(scene); + bool is_bi = BKE_scene_uses_blender_internal(scene); Image *ima = NULL; if (!ob) @@ -5846,7 +5846,7 @@ static int texture_paint_delete_texture_paint_slot_exec(bContext *C, wmOperator Object *ob = CTX_data_active_object(C); Scene *scene = CTX_data_scene(C); Material *ma; - bool is_bi = BKE_scene_uses_blender_internal(scene) || BKE_scene_uses_blender_game(scene); + bool is_bi = BKE_scene_uses_blender_internal(scene); TexPaintSlot *slot; /* not supported for node-based engines */ diff --git a/source/blender/editors/sculpt_paint/paint_utils.c b/source/blender/editors/sculpt_paint/paint_utils.c index 82589857ba5..f8888ad9809 100644 --- a/source/blender/editors/sculpt_paint/paint_utils.c +++ b/source/blender/editors/sculpt_paint/paint_utils.c @@ -497,10 +497,7 @@ void paint_sample_color(bContext *C, ARegion *ar, int x, int y, bool texpaint_pr if (ibuf->rect_float) { float rgba_f[4]; - if (U.gameflags & USER_DISABLE_MIPMAP) - nearest_interpolation_color_wrap(ibuf, NULL, rgba_f, u, v); - else - bilinear_interpolation_color_wrap(ibuf, NULL, rgba_f, u, v); + bilinear_interpolation_color_wrap(ibuf, NULL, rgba_f, u, v); straight_to_premul_v4(rgba_f); if (use_palette) { linearrgb_to_srgb_v3_v3(color->rgb, rgba_f); @@ -512,10 +509,7 @@ void paint_sample_color(bContext *C, ARegion *ar, int x, int y, bool texpaint_pr } else { unsigned char rgba[4]; - if (U.gameflags & USER_DISABLE_MIPMAP) - nearest_interpolation_color_wrap(ibuf, rgba, NULL, u, v); - else - bilinear_interpolation_color_wrap(ibuf, rgba, NULL, u, v); + bilinear_interpolation_color_wrap(ibuf, rgba, NULL, u, v); if (use_palette) { rgb_uchar_to_float(color->rgb, rgba); } diff --git a/source/blender/editors/space_api/spacetypes.c b/source/blender/editors/space_api/spacetypes.c index 4455b117370..3f3cb8bce4b 100644 --- a/source/blender/editors/space_api/spacetypes.c +++ b/source/blender/editors/space_api/spacetypes.c @@ -95,7 +95,6 @@ void ED_spacetypes_init(void) ED_spacetype_script(); ED_spacetype_text(); ED_spacetype_sequencer(); - ED_spacetype_logic(); ED_spacetype_console(); ED_spacetype_userpref(); ED_spacetype_clip(); @@ -121,7 +120,6 @@ void ED_spacetypes_init(void) ED_operatortypes_metaball(); ED_operatortypes_sound(); ED_operatortypes_render(); - ED_operatortypes_logic(); ED_operatortypes_mask(); ED_operatortypes_io(); diff --git a/source/blender/editors/space_logic/CMakeLists.txt b/source/blender/editors/space_logic/CMakeLists.txt deleted file mode 100644 index 349c003cf56..00000000000 --- a/source/blender/editors/space_logic/CMakeLists.txt +++ /dev/null @@ -1,58 +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): Jacques Beaurain. -# -# ***** END GPL LICENSE BLOCK ***** - -set(INC - ../include - ../interface - ../../blenkernel - ../../blenlib - ../../blentranslation - ../../gpu - ../../makesdna - ../../makesrna - ../../windowmanager - ../../../../intern/guardedalloc - ../../../../intern/glew-mx -) - -set(INC_SYS - ${GLEW_INCLUDE_PATH} -) - -set(SRC - logic_buttons.c - logic_ops.c - logic_window.c - space_logic.c - - logic_intern.h -) - -if(WITH_GAMEENGINE) - add_definitions(-DWITH_GAMEENGINE) -endif() - -add_definitions(${GL_DEFINITIONS}) - -if(WITH_INTERNATIONAL) - add_definitions(-DWITH_INTERNATIONAL) -endif() - -blender_add_lib(bf_editor_space_logic "${SRC}" "${INC}" "${INC_SYS}") diff --git a/source/blender/editors/space_logic/logic_buttons.c b/source/blender/editors/space_logic/logic_buttons.c deleted file mode 100644 index 54e6e217b77..00000000000 --- a/source/blender/editors/space_logic/logic_buttons.c +++ /dev/null @@ -1,166 +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) 2009 by Blender Foundation - * All rights reserved. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file blender/editors/space_logic/logic_buttons.c - * \ingroup splogic - */ - - -#include -#include - -#include "BLI_blenlib.h" -#include "BLI_math.h" -#include "BLI_utildefines.h" - -#include "BKE_context.h" - -#include "ED_screen.h" - -#include "RNA_access.h" -#include "RNA_define.h" - -#include "WM_api.h" -#include "WM_types.h" - -#include "UI_interface.h" -#include "UI_view2d.h" - -#include "interface_intern.h" -#include "logic_intern.h" - -static int logic_properties_toggle_exec(bContext *C, wmOperator *UNUSED(op)) -{ - ScrArea *sa = CTX_wm_area(C); - ARegion *ar = logic_has_buttons_region(sa); - - if (ar) - ED_region_toggle_hidden(C, ar); - - return OPERATOR_FINISHED; -} - -void LOGIC_OT_properties(wmOperatorType *ot) -{ - ot->name = "Properties"; - ot->description = "Toggle the properties region visibility"; - ot->idname = "LOGIC_OT_properties"; - - ot->exec = logic_properties_toggle_exec; - ot->poll = ED_operator_logic_active; - - /* flags */ - ot->flag = 0; -} - -/* Remove Logic Bricks Connections */ -/* ********************** Cut Link operator ***************** */ - -#define LINK_RESOL 12 -static int cut_links_intersect(uiLinkLine *line, float mcoords[][2], int tot) -{ - float coord_array[LINK_RESOL+1][2]; - int i, b; - rcti rectlink; - - rectlink.xmin = (int)BLI_rctf_cent_x(&line->from->rect); - rectlink.ymin = (int)BLI_rctf_cent_y(&line->from->rect); - rectlink.xmax = (int)BLI_rctf_cent_x(&line->to->rect); - rectlink.ymax = (int)BLI_rctf_cent_y(&line->to->rect); - - if (ui_link_bezier_points(&rectlink, coord_array, LINK_RESOL)) { - for (i=0; i 0) - return 1; - } - return 0; -} - -static int cut_links_exec(bContext *C, wmOperator *op) -{ - ARegion *ar = CTX_wm_region(C); - float mcoords[256][2]; - int i = 0; - - RNA_BEGIN (op->ptr, itemptr, "path") - { - float loc[2]; - - RNA_float_get_array(&itemptr, "loc", loc); - UI_view2d_region_to_view(&ar->v2d, - (int)loc[0], (int)loc[1], - &mcoords[i][0], &mcoords[i][1]); - i++; - if (i >= 256) break; - } - RNA_END; - - if (i>1) { - uiBlock *block; - uiLinkLine *line, *nline; - uiBut *but; - for (block = ar->uiblocks.first; block; block = block->next) { - but = block->buttons.first; - while (but) { - if (but->type==UI_BTYPE_LINK && but->link) { - for (line = but->link->lines.first; line; line = nline) { - nline = line->next; - - if (cut_links_intersect(line, mcoords, i)) { - ui_linkline_remove(line, but); - } - } - } - but = but->next; - } - } - return OPERATOR_FINISHED; - } - return OPERATOR_CANCELLED|OPERATOR_PASS_THROUGH; -} - -void LOGIC_OT_links_cut(wmOperatorType *ot) -{ - ot->name = "Cut Links"; - ot->idname = "LOGIC_OT_links_cut"; - ot->description = "Remove logic brick connections"; - - ot->invoke = WM_gesture_lines_invoke; - ot->modal = WM_gesture_lines_modal; - ot->exec = cut_links_exec; - ot->cancel = WM_gesture_lines_cancel; - - ot->poll = ED_operator_logic_active; - - /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; - - /* properties */ - PropertyRNA *prop; - prop = RNA_def_collection_runtime(ot->srna, "path", &RNA_OperatorMousePath, "Path", ""); - RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE); - /* internal */ - RNA_def_int(ot->srna, "cursor", BC_KNIFECURSOR, 0, INT_MAX, "Cursor", "", 0, INT_MAX); -} - diff --git a/source/blender/editors/space_logic/logic_intern.h b/source/blender/editors/space_logic/logic_intern.h deleted file mode 100644 index 13146621d1b..00000000000 --- a/source/blender/editors/space_logic/logic_intern.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) 2009 Blender Foundation. - * All rights reserved. - * - * - * Contributor(s): Blender Foundation - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file blender/editors/space_logic/logic_intern.h - * \ingroup splogic - */ - - -#ifndef __LOGIC_INTERN_H__ -#define __LOGIC_INTERN_H__ - -/* internal exports only */ -struct bContext; -struct ARegion; -struct ScrArea; -struct wmOperatorType; - -/* space_logic.c */ -struct ARegion *logic_has_buttons_region(struct ScrArea *sa); - -/* logic_ops.c */ - -/* logic_buttons.c */ -void LOGIC_OT_properties(struct wmOperatorType *ot); -void LOGIC_OT_links_cut(struct wmOperatorType *ot); - -/* logic_window.c */ -void logic_buttons(struct bContext *C, struct ARegion *ar); -void make_unique_prop_names(struct bContext *C, char *str); - -#endif /* __LOGIC_INTERN_H__ */ - diff --git a/source/blender/editors/space_logic/logic_ops.c b/source/blender/editors/space_logic/logic_ops.c deleted file mode 100644 index 7b9a8634490..00000000000 --- a/source/blender/editors/space_logic/logic_ops.c +++ /dev/null @@ -1,753 +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) 2009 Blender Foundation. - * All rights reserved. - * - * - * Contributor(s): Blender Foundation - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file blender/editors/space_logic/logic_ops.c - * \ingroup splogic - */ - -#include - -#include "DNA_object_types.h" -#include "DNA_sensor_types.h" -#include "DNA_controller_types.h" -#include "DNA_actuator_types.h" -#include "DNA_scene_types.h" - -#include "BLI_blenlib.h" -#include "BLI_string_utils.h" -#include "BLI_utildefines.h" - -#include "BLT_translation.h" - -#include "BKE_context.h" -#include "BKE_main.h" -#include "BKE_sca.h" - -#include "ED_logic.h" -#include "ED_object.h" -#include "ED_screen.h" - -#include "RNA_access.h" -#include "RNA_define.h" -#include "RNA_enum_types.h" - -#include "WM_api.h" -#include "WM_types.h" - -#include "UI_view2d.h" - -#include "logic_intern.h" - -/* ************* Generic Operator Helpers ************* */ -static int edit_sensor_poll(bContext *C) -{ - PointerRNA ptr = CTX_data_pointer_get_type(C, "sensor", &RNA_Sensor); - - if (ptr.data && ID_IS_LINKED(ptr.id.data)) return 0; - return 1; -} - -static int edit_controller_poll(bContext *C) -{ - PointerRNA ptr = CTX_data_pointer_get_type(C, "controller", &RNA_Controller); - - if (ptr.data && ID_IS_LINKED(ptr.id.data)) return 0; - return 1; -} - -static int edit_actuator_poll(bContext *C) -{ - PointerRNA ptr = CTX_data_pointer_get_type(C, "actuator", &RNA_Actuator); - - if (ptr.data && ID_IS_LINKED(ptr.id.data)) return 0; - return 1; -} - -static void edit_sensor_properties(wmOperatorType *ot) -{ - RNA_def_string(ot->srna, "sensor", NULL, MAX_NAME, "Sensor", "Name of the sensor to edit"); - RNA_def_string(ot->srna, "object", NULL, MAX_NAME, "Object", "Name of the object the sensor belongs to"); -} - -static int edit_sensor_invoke_properties(bContext *C, wmOperator *op) -{ - PointerRNA ptr = CTX_data_pointer_get_type(C, "sensor", &RNA_Sensor); - - if (RNA_struct_property_is_set(op->ptr, "sensor") && RNA_struct_property_is_set(op->ptr, "object") ) - return 1; - - if (ptr.data) { - bSensor *sens = ptr.data; - Object *ob = ptr.id.data; - - RNA_string_set(op->ptr, "sensor", sens->name); - RNA_string_set(op->ptr, "object", ob->id.name + 2); - return 1; - } - - return 0; -} - -static Object *edit_object_property_get(bContext *C, wmOperator *op) -{ - char ob_name[MAX_NAME]; - Object *ob; - - RNA_string_get(op->ptr, "object", ob_name); - - /* if ob_name is valid try to find the object with this name - * otherwise gets the active object */ - if (*ob_name) - ob = BLI_findstring(&(CTX_data_main(C)->object), ob_name, offsetof(ID, name) + 2); - else - ob = ED_object_active_context(C); - - return ob; -} - -static bSensor *edit_sensor_property_get(bContext *C, wmOperator *op, Object **ob) -{ - char sensor_name[MAX_NAME]; - bSensor *sens; - - RNA_string_get(op->ptr, "sensor", sensor_name); - - *ob = edit_object_property_get(C, op); - if (!*ob) return NULL; - - sens = BLI_findstring(&((*ob)->sensors), sensor_name, offsetof(bSensor, name)); - return sens; -} - -static void edit_controller_properties(wmOperatorType *ot) -{ - RNA_def_string(ot->srna, "controller", NULL, MAX_NAME, "Controller", "Name of the controller to edit"); - RNA_def_string(ot->srna, "object", NULL, MAX_NAME, "Object", "Name of the object the controller belongs to"); -} - -static int edit_controller_invoke_properties(bContext *C, wmOperator *op) -{ - PointerRNA ptr = CTX_data_pointer_get_type(C, "controller", &RNA_Controller); - - if (RNA_struct_property_is_set(op->ptr, "controller") && RNA_struct_property_is_set(op->ptr, "object") ) - return 1; - - if (ptr.data) { - bController *cont = ptr.data; - Object *ob = ptr.id.data; - - RNA_string_set(op->ptr, "controller", cont->name); - RNA_string_set(op->ptr, "object", ob->id.name + 2); - return 1; - } - - return 0; -} - -static bController *edit_controller_property_get(bContext *C, wmOperator *op, Object **ob) -{ - char controller_name[MAX_NAME]; - bController *cont; - - RNA_string_get(op->ptr, "controller", controller_name); - - *ob = edit_object_property_get(C, op); - if (!*ob) return NULL; - - cont = BLI_findstring(&((*ob)->controllers), controller_name, offsetof(bController, name)); - return cont; -} - -static void edit_actuator_properties(wmOperatorType *ot) -{ - RNA_def_string(ot->srna, "actuator", NULL, MAX_NAME, "Actuator", "Name of the actuator to edit"); - RNA_def_string(ot->srna, "object", NULL, MAX_NAME, "Object", "Name of the object the actuator belongs to"); -} - -static int edit_actuator_invoke_properties(bContext *C, wmOperator *op) -{ - PointerRNA ptr = CTX_data_pointer_get_type(C, "actuator", &RNA_Actuator); - - if (RNA_struct_property_is_set(op->ptr, "actuator") && RNA_struct_property_is_set(op->ptr, "object") ) - return 1; - - if (ptr.data) { - bActuator *act = ptr.data; - Object *ob = ptr.id.data; - - RNA_string_set(op->ptr, "actuator", act->name); - RNA_string_set(op->ptr, "object", ob->id.name + 2); - return 1; - } - - return 0; -} - -static bActuator *edit_actuator_property_get(bContext *C, wmOperator *op, Object **ob) -{ - char actuator_name[MAX_NAME]; - bActuator *act; - - RNA_string_get(op->ptr, "actuator", actuator_name); - - *ob = edit_object_property_get(C, op); - if (!*ob) return NULL; - - act = BLI_findstring(&((*ob)->actuators), actuator_name, offsetof(bActuator, name)); - return act; -} - -static int logicbricks_move_property_get(wmOperator *op) -{ - int type = RNA_enum_get(op->ptr, "direction"); - - if (type == 1) - return true; - else - return false; -} - -/* ************* Add/Remove Sensor Operator ************* */ - -static int sensor_remove_exec(bContext *C, wmOperator *op) -{ - Object *ob = NULL; - bSensor *sens = edit_sensor_property_get(C, op, &ob); - - if (!sens) - return OPERATOR_CANCELLED; - - BLI_remlink(&(ob->sensors), sens); - free_sensor(sens); - - WM_event_add_notifier(C, NC_LOGIC, NULL); - - return OPERATOR_FINISHED; -} - -static int sensor_remove_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event)) -{ - if (edit_sensor_invoke_properties(C, op)) - return sensor_remove_exec(C, op); - else - return OPERATOR_CANCELLED; -} - -static void LOGIC_OT_sensor_remove(wmOperatorType *ot) -{ - ot->name = "Remove Sensor"; - ot->description = "Remove a sensor from the active object"; - ot->idname = "LOGIC_OT_sensor_remove"; - - ot->invoke = sensor_remove_invoke; - ot->exec = sensor_remove_exec; - ot->poll = edit_sensor_poll; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_INTERNAL; - edit_sensor_properties(ot); -} - -static int sensor_add_exec(bContext *C, wmOperator *op) -{ - Object *ob; - bSensor *sens; - PointerRNA sens_ptr; - PropertyRNA *prop; - const char *sens_name; - char name[MAX_NAME]; - int type = RNA_enum_get(op->ptr, "type"); - - ob = edit_object_property_get(C, op); - if (!ob) - return OPERATOR_CANCELLED; - - sens = new_sensor(type); - BLI_addtail(&(ob->sensors), sens); - - /* set the sensor name based on rna type enum */ - RNA_pointer_create((ID *)ob, &RNA_Sensor, sens, &sens_ptr); - prop = RNA_struct_find_property(&sens_ptr, "type"); - - RNA_string_get(op->ptr, "name", name); - if (*name) { - BLI_strncpy(sens->name, name, sizeof(sens->name)); - } - else { - RNA_property_enum_name(C, &sens_ptr, prop, RNA_property_enum_get(&sens_ptr, prop), &sens_name); - BLI_strncpy(sens->name, sens_name, sizeof(sens->name)); - } - - BLI_uniquename(&ob->sensors, sens, DATA_("Sensor"), '.', offsetof(bSensor, name), sizeof(sens->name)); - ob->scaflag |= OB_SHOWSENS; - - WM_event_add_notifier(C, NC_LOGIC, NULL); - - return OPERATOR_FINISHED; -} - -static void LOGIC_OT_sensor_add(wmOperatorType *ot) -{ - PropertyRNA *prop; - - /* identifiers */ - ot->name = "Add Sensor"; - ot->description = "Add a sensor to the active object"; - ot->idname = "LOGIC_OT_sensor_add"; - - /* api callbacks */ - ot->invoke = WM_menu_invoke; - ot->exec = sensor_add_exec; - ot->poll = ED_operator_object_active_editable; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_INTERNAL; - - /* properties */ - ot->prop = prop = RNA_def_enum(ot->srna, "type", DummyRNA_NULL_items, SENS_ALWAYS, "Type", "Type of sensor to add"); - RNA_def_enum_funcs(prop, rna_Sensor_type_itemf); - prop = RNA_def_string(ot->srna, "name", NULL, MAX_NAME, "Name", "Name of the Sensor to add"); - RNA_def_property_flag(prop, PROP_SKIP_SAVE); - prop = RNA_def_string(ot->srna, "object", NULL, MAX_NAME, "Object", "Name of the Object to add the Sensor to"); - RNA_def_property_flag(prop, PROP_SKIP_SAVE); -} - -/* ************* Add/Remove Controller Operator ************* */ - -static int controller_remove_exec(bContext *C, wmOperator *op) -{ - Object *ob = NULL; - bController *cont = edit_controller_property_get(C, op, &ob); - - if (!cont) - return OPERATOR_CANCELLED; - - BLI_remlink(&(ob->controllers), cont); - unlink_controller(cont); - free_controller(cont); - - WM_event_add_notifier(C, NC_LOGIC, NULL); - - return OPERATOR_FINISHED; -} - -static int controller_remove_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event)) -{ - if (edit_controller_invoke_properties(C, op)) - return controller_remove_exec(C, op); - else - return OPERATOR_CANCELLED; -} - -static void LOGIC_OT_controller_remove(wmOperatorType *ot) -{ - ot->name = "Remove Controller"; - ot->description = "Remove a controller from the active object"; - ot->idname = "LOGIC_OT_controller_remove"; - - ot->invoke = controller_remove_invoke; - ot->exec = controller_remove_exec; - ot->poll = edit_controller_poll; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_INTERNAL; - edit_controller_properties(ot); -} - -static int controller_add_exec(bContext *C, wmOperator *op) -{ - Object *ob; - bController *cont; - PointerRNA cont_ptr; - PropertyRNA *prop; - const char *cont_name; - int bit; - char name[MAX_NAME]; - int type = RNA_enum_get(op->ptr, "type"); - - ob = edit_object_property_get(C, op); - if (!ob) - return OPERATOR_CANCELLED; - - cont = new_controller(type); - BLI_addtail(&(ob->controllers), cont); - - /* set the controller name based on rna type enum */ - RNA_pointer_create((ID *)ob, &RNA_Controller, cont, &cont_ptr); - prop = RNA_struct_find_property(&cont_ptr, "type"); - - RNA_string_get(op->ptr, "name", name); - if (*name) { - BLI_strncpy(cont->name, name, sizeof(cont->name)); - } - else { - RNA_property_enum_name(C, &cont_ptr, prop, RNA_property_enum_get(&cont_ptr, prop), &cont_name); - BLI_strncpy(cont->name, cont_name, sizeof(cont->name)); - } - - BLI_uniquename(&ob->controllers, cont, DATA_("Controller"), '.', offsetof(bController, name), sizeof(cont->name)); - - /* set the controller state mask from the current object state. - * A controller is always in a single state, so select the lowest bit set - * from the object state */ - for (bit = 0; bit < OB_MAX_STATES; bit++) { - if (ob->state & (1 << bit)) - break; - } - cont->state_mask = (1 << bit); - if (cont->state_mask == 0) { - /* shouldn't happen, object state is never 0 */ - cont->state_mask = 1; - } - - ob->scaflag |= OB_SHOWCONT; - - WM_event_add_notifier(C, NC_LOGIC, NULL); - - return OPERATOR_FINISHED; -} - -static void LOGIC_OT_controller_add(wmOperatorType *ot) -{ - PropertyRNA *prop; - - /* identifiers */ - ot->name = "Add Controller"; - ot->description = "Add a controller to the active object"; - ot->idname = "LOGIC_OT_controller_add"; - - /* api callbacks */ - ot->invoke = WM_menu_invoke; - ot->exec = controller_add_exec; - ot->poll = ED_operator_object_active_editable; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_INTERNAL; - - /* properties */ - ot->prop = RNA_def_enum(ot->srna, "type", rna_enum_controller_type_items, CONT_LOGIC_AND, "Type", "Type of controller to add"); - prop = RNA_def_string(ot->srna, "name", NULL, MAX_NAME, "Name", "Name of the Controller to add"); - RNA_def_property_flag(prop, PROP_SKIP_SAVE); - prop = RNA_def_string(ot->srna, "object", NULL, MAX_NAME, "Object", "Name of the Object to add the Controller to"); - RNA_def_property_flag(prop, PROP_SKIP_SAVE); -} - -/* ************* Add/Remove Actuator Operator ************* */ - -static int actuator_remove_exec(bContext *C, wmOperator *op) -{ - Object *ob = NULL; - bActuator *act = edit_actuator_property_get(C, op, &ob); - - if (!act) - return OPERATOR_CANCELLED; - - BLI_remlink(&(ob->actuators), act); - unlink_actuator(act); - free_actuator(act); - - WM_event_add_notifier(C, NC_LOGIC, NULL); - - return OPERATOR_FINISHED; -} - -static int actuator_remove_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event)) -{ - if (edit_actuator_invoke_properties(C, op)) - return actuator_remove_exec(C, op); - else - return OPERATOR_CANCELLED; -} - -static void LOGIC_OT_actuator_remove(wmOperatorType *ot) -{ - ot->name = "Remove Actuator"; - ot->description = "Remove an actuator from the active object"; - ot->idname = "LOGIC_OT_actuator_remove"; - - ot->invoke = actuator_remove_invoke; - ot->exec = actuator_remove_exec; - ot->poll = edit_actuator_poll; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_INTERNAL; - edit_actuator_properties(ot); -} - -static int actuator_add_exec(bContext *C, wmOperator *op) -{ - Object *ob; - bActuator *act; - PointerRNA act_ptr; - PropertyRNA *prop; - const char *act_name; - char name[MAX_NAME]; - int type = RNA_enum_get(op->ptr, "type"); - - ob = edit_object_property_get(C, op); - if (!ob) - return OPERATOR_CANCELLED; - - act = new_actuator(type); - BLI_addtail(&(ob->actuators), act); - - /* set the actuator name based on rna type enum */ - RNA_pointer_create((ID *)ob, &RNA_Actuator, act, &act_ptr); - prop = RNA_struct_find_property(&act_ptr, "type"); - - RNA_string_get(op->ptr, "name", name); - if (*name) { - BLI_strncpy(act->name, name, sizeof(act->name)); - } - else { - RNA_property_enum_name(C, &act_ptr, prop, RNA_property_enum_get(&act_ptr, prop), &act_name); - BLI_strncpy(act->name, act_name, sizeof(act->name)); - } - - BLI_uniquename(&ob->actuators, act, DATA_("Actuator"), '.', offsetof(bActuator, name), sizeof(act->name)); - ob->scaflag |= OB_SHOWACT; - - WM_event_add_notifier(C, NC_LOGIC, NULL); - - return OPERATOR_FINISHED; -} - -static void LOGIC_OT_actuator_add(wmOperatorType *ot) -{ - PropertyRNA *prop; - - /* identifiers */ - ot->name = "Add Actuator"; - ot->description = "Add an actuator to the active object"; - ot->idname = "LOGIC_OT_actuator_add"; - - /* api callbacks */ - ot->invoke = WM_menu_invoke; - ot->exec = actuator_add_exec; - ot->poll = ED_operator_object_active_editable; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_INTERNAL; - - /* properties */ - ot->prop = prop = RNA_def_enum(ot->srna, "type", DummyRNA_NULL_items, CONT_LOGIC_AND, "Type", "Type of actuator to add"); - RNA_def_enum_funcs(prop, rna_Actuator_type_itemf); - prop = RNA_def_string(ot->srna, "name", NULL, MAX_NAME, "Name", "Name of the Actuator to add"); - RNA_def_property_flag(prop, PROP_SKIP_SAVE); - prop = RNA_def_string(ot->srna, "object", NULL, MAX_NAME, "Object", "Name of the Object to add the Actuator to"); - RNA_def_property_flag(prop, PROP_SKIP_SAVE); -} - -/* ************* Move Logic Bricks Operator ************* */ -static const EnumPropertyItem logicbricks_move_direction[] = { - {1, "UP", 0, "Move Up", ""}, - {2, "DOWN", 0, "Move Down", ""}, - {0, NULL, 0, NULL, NULL} -}; - - -static int sensor_move_exec(bContext *C, wmOperator *op) -{ - Object *ob = NULL; - bSensor *sens = edit_sensor_property_get(C, op, &ob); - int move_up = logicbricks_move_property_get(op); - - if (!sens) - return OPERATOR_CANCELLED; - - sca_move_sensor(sens, ob, move_up); - - WM_event_add_notifier(C, NC_LOGIC, NULL); - - return OPERATOR_FINISHED; -} - -static int sensor_move_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event)) -{ - if (edit_sensor_invoke_properties(C, op)) { - return sensor_move_exec(C, op); - } - else - return OPERATOR_CANCELLED; -} - -static void LOGIC_OT_sensor_move(wmOperatorType *ot) -{ - /* identifiers */ - ot->name = "Move Sensor"; - ot->description = "Move Sensor"; - ot->idname = "LOGIC_OT_sensor_move"; - - /* api callbacks */ - ot->invoke = sensor_move_invoke; - ot->exec = sensor_move_exec; - ot->poll = edit_sensor_poll; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_INTERNAL; - - /* properties */ - edit_sensor_properties(ot); - RNA_def_enum(ot->srna, "direction", logicbricks_move_direction, 1, "Direction", "Move Up or Down"); -} - -static int controller_move_exec(bContext *C, wmOperator *op) -{ - Object *ob = NULL; - bController *cont = edit_controller_property_get(C, op, &ob); - int move_up = logicbricks_move_property_get(op); - - if (!cont) - return OPERATOR_CANCELLED; - - sca_move_controller(cont, ob, move_up); - - WM_event_add_notifier(C, NC_LOGIC, NULL); - - return OPERATOR_FINISHED; -} - -static int controller_move_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event)) -{ - if (edit_controller_invoke_properties(C, op)) { - return controller_move_exec(C, op); - } - else - return OPERATOR_CANCELLED; -} - -static void LOGIC_OT_controller_move(wmOperatorType *ot) -{ - /* identifiers */ - ot->name = "Move Controller"; - ot->description = "Move Controller"; - ot->idname = "LOGIC_OT_controller_move"; - - /* api callbacks */ - ot->invoke = controller_move_invoke; - ot->exec = controller_move_exec; - ot->poll = edit_controller_poll; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_INTERNAL; - - /* properties */ - edit_controller_properties(ot); - RNA_def_enum(ot->srna, "direction", logicbricks_move_direction, 1, "Direction", "Move Up or Down"); -} - -static int actuator_move_exec(bContext *C, wmOperator *op) -{ - Object *ob = NULL; - bActuator *act = edit_actuator_property_get(C, op, &ob); - int move_up = logicbricks_move_property_get(op); - - if (!act) - return OPERATOR_CANCELLED; - - sca_move_actuator(act, ob, move_up); - - WM_event_add_notifier(C, NC_LOGIC, NULL); - - return OPERATOR_FINISHED; -} - -static int actuator_move_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event)) -{ - if (edit_actuator_invoke_properties(C, op)) { - return actuator_move_exec(C, op); - } - else - return OPERATOR_CANCELLED; -} - -static void LOGIC_OT_actuator_move(wmOperatorType *ot) -{ - /* identifiers */ - ot->name = "Move Actuator"; - ot->description = "Move Actuator"; - ot->idname = "LOGIC_OT_actuator_move"; - - /* api callbacks */ - ot->invoke = actuator_move_invoke; - ot->exec = actuator_move_exec; - ot->poll = edit_actuator_poll; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_INTERNAL; - - /* properties */ - edit_actuator_properties(ot); - RNA_def_enum(ot->srna, "direction", logicbricks_move_direction, 1, "Direction", "Move Up or Down"); -} - -/* ************************ view ********************* */ - -static int logic_view_all_exec(bContext *C, wmOperator *op) -{ - ARegion *ar = CTX_wm_region(C); - rctf cur_new = ar->v2d.tot; - float aspect = BLI_rctf_size_y(&ar->v2d.cur) / BLI_rctf_size_x(&ar->v2d.cur); - const int smooth_viewtx = WM_operator_smooth_viewtx_get(op); - - /* force the view2d code to zoom to width, not height */ - cur_new.ymin = cur_new.ymax - BLI_rctf_size_x(&cur_new) * aspect; - - UI_view2d_smooth_view(C, ar, &cur_new, smooth_viewtx); - - return OPERATOR_FINISHED; -} - -static void LOGIC_OT_view_all(wmOperatorType *ot) -{ - /* identifiers */ - ot->name = "View All"; - ot->idname = "LOGIC_OT_view_all"; - ot->description = "Resize view so you can see all logic bricks"; - - /* api callbacks */ - ot->exec = logic_view_all_exec; - ot->poll = ED_operator_logic_active; - - /* flags */ - ot->flag = 0; -} - -/* ************************* */ - -void ED_operatortypes_logic(void) -{ - WM_operatortype_append(LOGIC_OT_sensor_remove); - WM_operatortype_append(LOGIC_OT_sensor_add); - WM_operatortype_append(LOGIC_OT_sensor_move); - WM_operatortype_append(LOGIC_OT_controller_remove); - WM_operatortype_append(LOGIC_OT_controller_add); - WM_operatortype_append(LOGIC_OT_controller_move); - WM_operatortype_append(LOGIC_OT_actuator_remove); - WM_operatortype_append(LOGIC_OT_actuator_add); - WM_operatortype_append(LOGIC_OT_actuator_move); - WM_operatortype_append(LOGIC_OT_view_all); -} diff --git a/source/blender/editors/space_logic/logic_window.c b/source/blender/editors/space_logic/logic_window.c deleted file mode 100644 index 9bdc92f98ab..00000000000 --- a/source/blender/editors/space_logic/logic_window.c +++ /dev/null @@ -1,2594 +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) 2009 Blender Foundation. - * All rights reserved. - * - * - * Contributor(s): Blender Foundation - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file blender/editors/space_logic/logic_window.c - * \ingroup splogic - */ - - -#include -#include -#include -#include - -#include "DNA_actuator_types.h" -#include "DNA_controller_types.h" -#include "DNA_property_types.h" -#include "DNA_space_types.h" -#include "DNA_scene_types.h" -#include "DNA_screen_types.h" -#include "DNA_sensor_types.h" -#include "DNA_constraint_types.h" -#include "DNA_object_types.h" - -#include "MEM_guardedalloc.h" - -#include "BLI_blenlib.h" -#include "BLI_string_utils.h" -#include "BLI_utildefines.h" - -#include "BKE_action.h" -#include "BKE_context.h" -#include "BKE_library.h" -#include "BKE_main.h" -#include "BKE_sca.h" - -#include "ED_undo.h" - -#include "BLT_translation.h" - -#include "UI_interface.h" -#include "UI_view2d.h" - -#include "RNA_access.h" - -/* XXX BAD BAD */ -#include "../interface/interface_intern.h" - -#include "logic_intern.h" - -#define B_REDR 1 - -#define B_ADD_SENS 2703 -#define B_CHANGE_SENS 2704 -#define B_DEL_SENS 2705 - -#define B_ADD_CONT 2706 -#define B_CHANGE_CONT 2707 -#define B_DEL_CONT 2708 - -#define B_ADD_ACT 2709 -#define B_CHANGE_ACT 2710 -#define B_DEL_ACT 2711 - -#define B_SOUNDACT_BROWSE 2712 - -#define B_SETPROP 2714 -#define B_SETACTOR 2715 -#define B_SETMAINACTOR 2716 -#define B_SETDYNA 2717 -#define B_SET_STATE_BIT 2718 -#define B_INIT_STATE_BIT 2719 - -/* proto */ -static ID **get_selected_and_linked_obs(bContext *C, short *count, short scavisflag); - -static void do_logic_buts(bContext *C, void *UNUSED(arg), int event) -{ - Main *bmain= CTX_data_main(C); - bSensor *sens; - bController *cont; - bActuator *act; - Object *ob; - int didit, bit; - - ob= CTX_data_active_object(C); - if (ob==NULL) return; - - switch (event) { - - case B_SETPROP: - /* check for inconsistent types */ - ob->gameflag &= ~(OB_SECTOR|OB_MAINACTOR|OB_DYNAMIC|OB_ACTOR); - break; - - case B_SETACTOR: - case B_SETDYNA: - case B_SETMAINACTOR: - ob->gameflag &= ~(OB_SECTOR|OB_PROP); - break; - - case B_ADD_SENS: - for (ob=bmain->object.first; ob; ob=ob->id.next) { - if (ob->scaflag & OB_ADDSENS) { - ob->scaflag &= ~OB_ADDSENS; - sens= new_sensor(SENS_ALWAYS); - BLI_addtail(&(ob->sensors), sens); - BLI_uniquename(&ob->sensors, sens, DATA_("Sensor"), '.', offsetof(bSensor, name), sizeof(sens->name)); - ob->scaflag |= OB_SHOWSENS; - } - } - - ED_undo_push(C, "Add sensor"); - break; - - case B_CHANGE_SENS: - for (ob=bmain->object.first; ob; ob=ob->id.next) { - sens= ob->sensors.first; - while (sens) { - if (sens->type != sens->otype) { - init_sensor(sens); - sens->otype= sens->type; - break; - } - sens= sens->next; - } - } - break; - - case B_DEL_SENS: - for (ob=bmain->object.first; ob; ob=ob->id.next) { - sens= ob->sensors.first; - while (sens) { - if (sens->flag & SENS_DEL) { - BLI_remlink(&(ob->sensors), sens); - free_sensor(sens); - break; - } - sens= sens->next; - } - } - ED_undo_push(C, "Delete sensor"); - break; - - case B_ADD_CONT: - for (ob=bmain->object.first; ob; ob=ob->id.next) { - if (ob->scaflag & OB_ADDCONT) { - ob->scaflag &= ~OB_ADDCONT; - cont= new_controller(CONT_LOGIC_AND); - BLI_uniquename(&ob->controllers, cont, DATA_("Controller"), '.', offsetof(bController, name), sizeof(cont->name)); - ob->scaflag |= OB_SHOWCONT; - BLI_addtail(&(ob->controllers), cont); - /* set the controller state mask from the current object state. - * A controller is always in a single state, so select the lowest bit set - * from the object state */ - for (bit=0; bit<32; bit++) { - if (ob->state & (1<state_mask = (1<state_mask == 0) { - /* shouldn't happen, object state is never 0 */ - cont->state_mask = 1; - } - } - } - ED_undo_push(C, "Add controller"); - break; - - case B_SET_STATE_BIT: - for (ob=bmain->object.first; ob; ob=ob->id.next) { - if (ob->scaflag & OB_ALLSTATE) { - ob->scaflag &= ~OB_ALLSTATE; - ob->state = 0x3FFFFFFF; - } - } - break; - - case B_INIT_STATE_BIT: - for (ob=bmain->object.first; ob; ob=ob->id.next) { - if (ob->scaflag & OB_INITSTBIT) { - ob->scaflag &= ~OB_INITSTBIT; - ob->state = ob->init_state; - if (!ob->state) - ob->state = 1; - } - } - break; - - case B_CHANGE_CONT: - for (ob=bmain->object.first; ob; ob=ob->id.next) { - cont= ob->controllers.first; - while (cont) { - if (cont->type != cont->otype) { - init_controller(cont); - cont->otype= cont->type; - break; - } - cont= cont->next; - } - } - break; - - - case B_DEL_CONT: - for (ob=bmain->object.first; ob; ob=ob->id.next) { - cont= ob->controllers.first; - while (cont) { - if (cont->flag & CONT_DEL) { - BLI_remlink(&(ob->controllers), cont); - unlink_controller(cont); - free_controller(cont); - break; - } - cont= cont->next; - } - } - ED_undo_push(C, "Delete controller"); - break; - - case B_ADD_ACT: - for (ob=bmain->object.first; ob; ob=ob->id.next) { - if (ob->scaflag & OB_ADDACT) { - ob->scaflag &= ~OB_ADDACT; - act= new_actuator(ACT_OBJECT); - BLI_uniquename(&ob->actuators, act, DATA_("Actuator"), '.', offsetof(bActuator, name), sizeof(act->name)); - BLI_addtail(&(ob->actuators), act); - ob->scaflag |= OB_SHOWACT; - } - } - ED_undo_push(C, "Add actuator"); - break; - - case B_CHANGE_ACT: - for (ob=bmain->object.first; ob; ob=ob->id.next) { - act= ob->actuators.first; - while (act) { - if (act->type != act->otype) { - init_actuator(act); - act->otype= act->type; - break; - } - act= act->next; - } - } - break; - - case B_DEL_ACT: - for (ob=bmain->object.first; ob; ob=ob->id.next) { - act= ob->actuators.first; - while (act) { - if (act->flag & ACT_DEL) { - BLI_remlink(&(ob->actuators), act); - unlink_actuator(act); - free_actuator(act); - break; - } - act= act->next; - } - } - ED_undo_push(C, "Delete actuator"); - break; - - case B_SOUNDACT_BROWSE: - /* since we don't know which... */ - didit= 0; - for (ob=bmain->object.first; ob; ob=ob->id.next) { - act= ob->actuators.first; - while (act) { - if (act->type==ACT_SOUND) { - bSoundActuator *sa= act->data; - if (sa->sndnr) { - ID *sound= bmain->sound.first; - int nr= 1; - - if (sa->sndnr == -2) { -// XXX activate_databrowse((ID *)bmain->sound.first, ID_SO, 0, B_SOUNDACT_BROWSE, -// &sa->sndnr, do_logic_buts); - break; - } - - while (sound) { - if (nr==sa->sndnr) - break; - nr++; - sound= sound->next; - } - - if (sa->sound) - id_us_min(((ID *)sa->sound)); - - sa->sound= (struct bSound *)sound; - - if (sound) { - id_us_plus(sound); - } - - sa->sndnr= 0; - didit= 1; - } - } - act= act->next; - } - if (didit) - break; - } - - break; - } -} - - -static const char *sensor_name(int type) -{ - switch (type) { - case SENS_ALWAYS: - return N_("Always"); - case SENS_NEAR: - return N_("Near"); - case SENS_KEYBOARD: - return N_("Keyboard"); - case SENS_PROPERTY: - return N_("Property"); - case SENS_ARMATURE: - return N_("Armature"); - case SENS_ACTUATOR: - return N_("Actuator"); - case SENS_DELAY: - return N_("Delay"); - case SENS_MOUSE: - return N_("Mouse"); - case SENS_COLLISION: - return N_("Collision"); - case SENS_RADAR: - return N_("Radar"); - case SENS_RANDOM: - return N_("Random"); - case SENS_RAY: - return N_("Ray"); - case SENS_MESSAGE: - return N_("Message"); - case SENS_JOYSTICK: - return N_("Joystick"); - } - return N_("Unknown"); -} - -static const char *controller_name(int type) -{ - switch (type) { - case CONT_LOGIC_AND: - return N_("And"); - case CONT_LOGIC_OR: - return N_("Or"); - case CONT_LOGIC_NAND: - return N_("Nand"); - case CONT_LOGIC_NOR: - return N_("Nor"); - case CONT_LOGIC_XOR: - return N_("Xor"); - case CONT_LOGIC_XNOR: - return N_("Xnor"); - case CONT_EXPRESSION: - return N_("Expression"); - case CONT_PYTHON: - return N_("Python"); - } - return N_("Unknown"); -} - -static const char *actuator_name(int type) -{ - switch (type) { - case ACT_SHAPEACTION: - return N_("Shape Action"); - case ACT_ACTION: - return N_("Action"); - case ACT_OBJECT: - return N_("Motion"); - case ACT_LAMP: - return N_("Lamp"); - case ACT_CAMERA: - return N_("Camera"); - case ACT_MATERIAL: - return N_("Material"); - case ACT_SOUND: - return N_("Sound"); - case ACT_PROPERTY: - return N_("Property"); - case ACT_EDIT_OBJECT: - return N_("Edit Object"); - case ACT_CONSTRAINT: - return N_("Constraint"); - case ACT_SCENE: - return N_("Scene"); - case ACT_GROUP: - return N_("Group"); - case ACT_RANDOM: - return N_("Random"); - case ACT_MESSAGE: - return N_("Message"); - case ACT_GAME: - return N_("Game"); - case ACT_VISIBILITY: - return N_("Visibility"); - case ACT_2DFILTER: - return N_("Filter 2D"); - case ACT_PARENT: - return N_("Parent"); - case ACT_STATE: - return N_("State"); - case ACT_ARMATURE: - return N_("Armature"); - case ACT_STEERING: - return N_("Steering"); - case ACT_MOUSE: - return N_("Mouse"); - } - return N_("Unknown"); -} - -static void set_sca_ob(Object *ob) -{ - bController *cont; - bActuator *act; - - cont= ob->controllers.first; - while (cont) { - cont->mynew= (bController *)ob; - cont= cont->next; - } - act= ob->actuators.first; - while (act) { - act->mynew= (bActuator *)ob; - act= act->next; - } -} - -static ID **get_selected_and_linked_obs(bContext *C, short *count, short scavisflag) -{ - Base *base; - Main *bmain = CTX_data_main(C); - Scene *scene = CTX_data_scene(C); - ViewLayer *view_layer = CTX_data_view_layer(C); - Object *ob, *obt, *obact = CTX_data_active_object(C); - ID **idar; - bSensor *sens; - bController *cont; - int a, nr, do_it; - - /* we need a sorted object list */ - /* set scavisflags flags in Objects to indicate these should be evaluated */ - /* also hide ob pointers in ->new entries of controllerss/actuators */ - - *count= 0; - - if (scene==NULL) return NULL; - - ob= bmain->object.first; - while (ob) { - ob->scavisflag= 0; - set_sca_ob(ob); - ob= ob->id.next; - } - - for (base = FIRSTBASE(view_layer); base; base = base->next) { - if ((base->flag & BASE_VISIBLED) && (base->flag & SELECT)) { - if (scavisflag & BUTS_SENS_SEL) base->object->scavisflag |= OB_VIS_SENS; - if (scavisflag & BUTS_CONT_SEL) base->object->scavisflag |= OB_VIS_CONT; - if (scavisflag & BUTS_ACT_SEL) base->object->scavisflag |= OB_VIS_ACT; - } - } - - if (obact) { - if (scavisflag & BUTS_SENS_ACT) obact->scavisflag |= OB_VIS_SENS; - if (scavisflag & BUTS_CONT_ACT) obact->scavisflag |= OB_VIS_CONT; - if (scavisflag & BUTS_ACT_ACT) obact->scavisflag |= OB_VIS_ACT; - } - - /* BUTS_XXX_STATE are similar to BUTS_XXX_LINK for selecting the object */ - if (scavisflag & (BUTS_SENS_LINK|BUTS_CONT_LINK|BUTS_ACT_LINK|BUTS_SENS_STATE|BUTS_ACT_STATE)) { - do_it = true; - while (do_it) { - do_it = false; - - ob= bmain->object.first; - while (ob) { - - /* 1st case: select sensor when controller selected */ - if ((scavisflag & (BUTS_SENS_LINK|BUTS_SENS_STATE)) && (ob->scavisflag & OB_VIS_SENS)==0) { - sens= ob->sensors.first; - while (sens) { - for (a=0; atotlinks; a++) { - if (sens->links[a]) { - obt= (Object *)sens->links[a]->mynew; - if (obt && (obt->scavisflag & OB_VIS_CONT)) { - do_it = true; - ob->scavisflag |= OB_VIS_SENS; - break; - } - } - } - if (do_it) break; - sens= sens->next; - } - } - - /* 2nd case: select cont when act selected */ - if ((scavisflag & BUTS_CONT_LINK) && (ob->scavisflag & OB_VIS_CONT)==0) { - cont= ob->controllers.first; - while (cont) { - for (a=0; atotlinks; a++) { - if (cont->links[a]) { - obt= (Object *)cont->links[a]->mynew; - if (obt && (obt->scavisflag & OB_VIS_ACT)) { - do_it = true; - ob->scavisflag |= OB_VIS_CONT; - break; - } - } - } - if (do_it) break; - cont= cont->next; - } - } - - /* 3rd case: select controller when sensor selected */ - if ((scavisflag & BUTS_CONT_LINK) && (ob->scavisflag & OB_VIS_SENS)) { - sens= ob->sensors.first; - while (sens) { - for (a=0; atotlinks; a++) { - if (sens->links[a]) { - obt= (Object *)sens->links[a]->mynew; - if (obt && (obt->scavisflag & OB_VIS_CONT)==0) { - do_it = true; - obt->scavisflag |= OB_VIS_CONT; - } - } - } - sens= sens->next; - } - } - - /* 4th case: select actuator when controller selected */ - if ((scavisflag & (BUTS_ACT_LINK|BUTS_ACT_STATE)) && (ob->scavisflag & OB_VIS_CONT)) { - cont= ob->controllers.first; - while (cont) { - for (a=0; atotlinks; a++) { - if (cont->links[a]) { - obt= (Object *)cont->links[a]->mynew; - if (obt && (obt->scavisflag & OB_VIS_ACT)==0) { - do_it = true; - obt->scavisflag |= OB_VIS_ACT; - } - } - } - cont= cont->next; - } - - } - ob= ob->id.next; - } - } - } - - /* now we count */ - ob= bmain->object.first; - while (ob) { - if ( ob->scavisflag ) (*count)++; - ob= ob->id.next; - } - - if (*count == 0) return NULL; - if (*count > 24) *count = 24; /* temporal */ - - idar= MEM_callocN((*count)*sizeof(void *), "idar"); - - ob= bmain->object.first; - nr= 0; - - /* make the active object always the first one of the list */ - if (obact) { - idar[0] = (ID *)obact; - nr++; - } - - while (ob) { - if ((ob->scavisflag) && (ob != obact)) { - idar[nr] = (ID *)ob; - nr++; - } - if (nr >= 24) break; - ob= ob->id.next; - } - - /* just to be sure... these were set in set_sca_done_ob() */ - clear_sca_new_poins(); - - return idar; -} - -static void get_armature_bone_constraint(Object *ob, const char *posechannel, const char *constraint_name, bConstraint **constraint) -{ - /* check that bone exist in the active object */ - if (ob->type == OB_ARMATURE && ob->pose) { - bPoseChannel *pchan= BKE_pose_channel_find_name(ob->pose, posechannel); - if (pchan) { - bConstraint *con= BLI_findstring(&pchan->constraints, constraint_name, offsetof(bConstraint, name)); - if (con) { - *constraint= con; - } - } - } - /* didn't find any */ -} - -static void do_sensor_menu(bContext *C, void *UNUSED(arg), int event) -{ - SpaceLogic *slogic= CTX_wm_space_logic(C); - ID **idar; - Object *ob; - bSensor *sens; - short count, a; - - idar= get_selected_and_linked_obs(C, &count, slogic->scaflag); - - for (a=0; ascaflag |= OB_SHOWSENS; - else if (event==1) ob->scaflag &= ~OB_SHOWSENS; - } - - for (a=0; asensors.first; - while (sens) { - if (event==2) sens->flag |= SENS_SHOW; - else if (event==3) sens->flag &= ~SENS_SHOW; - sens= sens->next; - } - } - - if (idar) MEM_freeN(idar); -} - -static uiBlock *sensor_menu(bContext *C, ARegion *ar, void *UNUSED(arg)) -{ - uiBlock *block; - int yco=0; - - block= UI_block_begin(C, ar, __func__, UI_EMBOSS_PULLDOWN); - UI_block_func_butmenu_set(block, do_sensor_menu, NULL); - - uiDefBut(block, UI_BTYPE_BUT_MENU, 1, IFACE_("Show Objects"), 0, (short)(yco-=20), 160, 19, NULL, 0.0, 0.0, 1, 0, ""); - uiDefBut(block, UI_BTYPE_BUT_MENU, 1, IFACE_("Hide Objects"), 0, (short)(yco-=20), 160, 19, NULL, 0.0, 0.0, 1, 1, ""); - uiDefBut(block, UI_BTYPE_SEPR_LINE, 0, "", 0, (short)(yco-=6), 160, 6, NULL, 0.0, 0.0, 0, 0, ""); - uiDefBut(block, UI_BTYPE_BUT_MENU, 1, IFACE_("Show Sensors"), 0, (short)(yco-=20), 160, 19, NULL, 0.0, 0.0, 1, 2, ""); - uiDefBut(block, UI_BTYPE_BUT_MENU, 1, IFACE_("Hide Sensors"), 0, (short)(yco-=20), 160, 19, NULL, 0.0, 0.0, 1, 3, ""); - - UI_block_direction_set(block, UI_DIR_UP); - UI_block_end(C, block); - - return block; -} - -static void do_controller_menu(bContext *C, void *UNUSED(arg), int event) -{ - SpaceLogic *slogic= CTX_wm_space_logic(C); - ID **idar; - Object *ob; - bController *cont; - short count, a; - - idar= get_selected_and_linked_obs(C, &count, slogic->scaflag); - - for (a=0; ascaflag |= OB_SHOWCONT; - else if (event==1) ob->scaflag &= ~OB_SHOWCONT; - } - - for (a=0; acontrollers.first; - while (cont) { - if (event==2) cont->flag |= CONT_SHOW; - else if (event==3) cont->flag &= ~CONT_SHOW; - cont= cont->next; - } - } - - if (idar) MEM_freeN(idar); -} - -static uiBlock *controller_menu(bContext *C, ARegion *ar, void *UNUSED(arg)) -{ - uiBlock *block; - int yco=0; - - block= UI_block_begin(C, ar, __func__, UI_EMBOSS_PULLDOWN); - UI_block_func_butmenu_set(block, do_controller_menu, NULL); - - uiDefBut(block, UI_BTYPE_BUT_MENU, 1, IFACE_("Show Objects"), 0, (short)(yco-=20), 160, 19, NULL, 0.0, 0.0, 1, 0, ""); - uiDefBut(block, UI_BTYPE_BUT_MENU, 1, IFACE_("Hide Objects"), 0, (short)(yco-=20), 160, 19, NULL, 0.0, 0.0, 1, 1, ""); - uiDefBut(block, UI_BTYPE_SEPR_LINE, 0, "", 0, (short)(yco-=6), 160, 6, NULL, 0.0, 0.0, 0, 0, ""); - uiDefBut(block, UI_BTYPE_BUT_MENU, 1, IFACE_("Show Controllers"), 0, (short)(yco-=20), 160, 19, NULL, 0.0, 0.0, 2, 2, ""); - uiDefBut(block, UI_BTYPE_BUT_MENU, 1, IFACE_("Hide Controllers"), 0, (short)(yco-=20), 160, 19, NULL, 0.0, 0.0, 3, 3, ""); - - UI_block_direction_set(block, UI_DIR_UP); - UI_block_end(C, block); - - return block; -} - -static void do_actuator_menu(bContext *C, void *UNUSED(arg), int event) -{ - SpaceLogic *slogic= CTX_wm_space_logic(C); - ID **idar; - Object *ob; - bActuator *act; - short count, a; - - idar= get_selected_and_linked_obs(C, &count, slogic->scaflag); - - for (a=0; ascaflag |= OB_SHOWACT; - else if (event==1) ob->scaflag &= ~OB_SHOWACT; - } - - for (a=0; aactuators.first; - while (act) { - if (event==2) act->flag |= ACT_SHOW; - else if (event==3) act->flag &= ~ACT_SHOW; - act= act->next; - } - } - - if (idar) MEM_freeN(idar); -} - -static uiBlock *actuator_menu(bContext *C, ARegion *ar, void *UNUSED(arg)) -{ - uiBlock *block; - int xco=0; - - block= UI_block_begin(C, ar, __func__, UI_EMBOSS_PULLDOWN); - UI_block_func_butmenu_set(block, do_actuator_menu, NULL); - - uiDefBut(block, UI_BTYPE_BUT_MENU, 1, IFACE_("Show Objects"), 0, (short)(xco-=20), 160, 19, NULL, 0.0, 0.0, 1, 0, ""); - uiDefBut(block, UI_BTYPE_BUT_MENU, 1, IFACE_("Hide Objects"), 0, (short)(xco-=20), 160, 19, NULL, 0.0, 0.0, 1, 1, ""); - uiDefBut(block, UI_BTYPE_SEPR_LINE, 0, "", 0, (short)(xco-=6), 160, 6, NULL, 0.0, 0.0, 0, 0, ""); - uiDefBut(block, UI_BTYPE_BUT_MENU, 1, IFACE_("Show Actuators"), 0, (short)(xco-=20), 160, 19, NULL, 0.0, 0.0, 1, 2, ""); - uiDefBut(block, UI_BTYPE_BUT_MENU, 1, IFACE_("Hide Actuators"), 0, (short)(xco-=20), 160, 19, NULL, 0.0, 0.0, 1, 3, ""); - - UI_block_direction_set(block, UI_DIR_UP); - UI_block_end(C, block); - - return block; -} - -static void check_controller_state_mask(bContext *UNUSED(C), void *arg1_but, void *arg2_mask) -{ - unsigned int *cont_mask = arg2_mask; - uiBut *but = arg1_but; - - /* a controller is always in a single state */ - *cont_mask = (1<retval); - but->retval = B_REDR; -} - -static uiBlock *controller_state_mask_menu(bContext *C, ARegion *ar, void *arg_cont) -{ - uiBlock *block; - uiBut *but; - bController *cont = arg_cont; - - short yco = 12, xco = 0, stbit, offset; - - block= UI_block_begin(C, ar, __func__, UI_EMBOSS); - - /* use this for a fake extra empy space around the buttons */ - uiDefBut(block, UI_BTYPE_LABEL, 0, "", -5, -5, 200, 34, NULL, 0, 0, 0, 0, ""); - - for (offset=0; offset<15; offset += 5) { - UI_block_align_begin(block); - for (stbit=0; stbit<5; stbit++) { - but = uiDefButBitI(block, UI_BTYPE_TOGGLE, (1<<(stbit+offset)), (stbit+offset), "", (short)(xco+12*stbit+13*offset), yco, 12, 12, (int *)&(cont->state_mask), 0, 0, 0, 0, ""); - UI_but_func_set(but, check_controller_state_mask, but, &(cont->state_mask)); - } - for (stbit=0; stbit<5; stbit++) { - but = uiDefButBitI(block, UI_BTYPE_TOGGLE, (1<<(stbit+offset+15)), (stbit+offset+15), "", (short)(xco+12*stbit+13*offset), yco-12, 12, 12, (int *)&(cont->state_mask), 0, 0, 0, 0, ""); - UI_but_func_set(but, check_controller_state_mask, but, &(cont->state_mask)); - } - } - UI_block_align_end(block); - - UI_block_direction_set(block, UI_DIR_UP); - UI_block_end(C, block); - - return block; -} - -static bool is_sensor_linked(uiBlock *block, bSensor *sens) -{ - bController *cont; - int i; - - for (i=0; itotlinks; i++) { - cont = sens->links[i]; - if (UI_block_links_find_inlink(block, cont) != NULL) - return 1; - } - return 0; -} - -/* Sensors code */ - -static void draw_sensor_header(uiLayout *layout, PointerRNA *ptr, PointerRNA *logic_ptr) -{ - uiLayout *box, *row, *sub; - bSensor *sens= (bSensor *)ptr->data; - - box = uiLayoutBox(layout); - row = uiLayoutRow(box, false); - - sub = uiLayoutRow(row, false); - uiLayoutSetActive(sub, RNA_boolean_get(ptr, "active")); - uiItemR(sub, ptr, "show_expanded", UI_ITEM_R_NO_BG, "", ICON_NONE); - if (RNA_boolean_get(ptr, "show_expanded")) { - uiItemR(sub, ptr, "type", 0, "", ICON_NONE); - uiItemR(sub, ptr, "name", 0, "", ICON_NONE); - } - else { - uiItemL(sub, IFACE_(sensor_name(sens->type)), ICON_NONE); - uiItemL(sub, sens->name, ICON_NONE); - } - - sub = uiLayoutRow(row, false); - uiLayoutSetActive(sub, (((RNA_boolean_get(logic_ptr, "show_sensors_active_states") && - RNA_boolean_get(ptr, "show_expanded")) || RNA_boolean_get(ptr, "pin")) && - RNA_boolean_get(ptr, "active"))); - uiItemR(sub, ptr, "pin", UI_ITEM_R_NO_BG, "", ICON_NONE); - - if (RNA_boolean_get(ptr, "show_expanded")==0) { - sub = uiLayoutRow(row, true); - uiLayoutSetActive(sub, RNA_boolean_get(ptr, "active")); - uiItemEnumO(sub, "LOGIC_OT_sensor_move", "", ICON_TRIA_UP, "direction", 1); // up - uiItemEnumO(sub, "LOGIC_OT_sensor_move", "", ICON_TRIA_DOWN, "direction", 2); // down - } - - sub = uiLayoutRow(row, false); - uiItemR(sub, ptr, "active", 0, "", ICON_NONE); - - sub = uiLayoutRow(row, false); - uiLayoutSetActive(sub, RNA_boolean_get(ptr, "active")); - uiItemO(sub, "", ICON_X, "LOGIC_OT_sensor_remove"); -} - -static void draw_sensor_internal_header(uiLayout *layout, PointerRNA *ptr) -{ - uiLayout *box, *split, *sub, *row; - - box = uiLayoutBox(layout); - uiLayoutSetActive(box, RNA_boolean_get(ptr, "active")); - split = uiLayoutSplit(box, 0.45f, false); - - row = uiLayoutRow(split, true); - uiItemR(row, ptr, "use_pulse_true_level", 0, "", ICON_DOTSUP); - uiItemR(row, ptr, "use_pulse_false_level", 0, "", ICON_DOTSDOWN); - - sub = uiLayoutRow(row, false); - uiLayoutSetActive(sub, (RNA_boolean_get(ptr, "use_pulse_true_level") || - RNA_boolean_get(ptr, "use_pulse_false_level"))); - uiItemR(sub, ptr, "tick_skip", 0, IFACE_("Skip"), ICON_NONE); - - row = uiLayoutRow(split, true); - uiItemR(row, ptr, "use_level", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - uiItemR(row, ptr, "use_tap", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - - uiItemR(split, ptr, "invert", UI_ITEM_R_TOGGLE, IFACE_("Invert"), ICON_NONE); -} -/* sensors in alphabetical order */ - -static void draw_sensor_actuator(uiLayout *layout, PointerRNA *ptr) -{ - Object *ob = (Object *)ptr->id.data; - PointerRNA settings_ptr; - - RNA_pointer_create((ID *)ob, &RNA_GameObjectSettings, ob, &settings_ptr); - uiItemPointerR(layout, ptr, "actuator", &settings_ptr, "actuators", NULL, ICON_LOGIC); -} - -static void draw_sensor_armature(uiLayout *layout, PointerRNA *ptr) -{ - bSensor *sens = (bSensor *)ptr->data; - bArmatureSensor *as = (bArmatureSensor *) sens->data; - Object *ob = (Object *)ptr->id.data; - uiLayout *row; - - if (ob->type != OB_ARMATURE) { - uiItemL(layout, IFACE_("Sensor only available for armatures"), ICON_NONE); - return; - } - - if (ob->pose) { - PointerRNA pose_ptr, pchan_ptr; - PropertyRNA *bones_prop; - - RNA_pointer_create((ID *)ob, &RNA_Pose, ob->pose, &pose_ptr); - bones_prop = RNA_struct_find_property(&pose_ptr, "bones"); - - uiItemPointerR(layout, ptr, "bone", &pose_ptr, "bones", NULL, ICON_BONE_DATA); - - if (RNA_property_collection_lookup_string(&pose_ptr, bones_prop, as->posechannel, &pchan_ptr)) - uiItemPointerR(layout, ptr, "constraint", &pchan_ptr, "constraints", NULL, ICON_CONSTRAINT_BONE); - } - row = uiLayoutRow(layout, true); - uiItemR(row, ptr, "test_type", 0, NULL, ICON_NONE); - if (RNA_enum_get(ptr, "test_type") != SENS_ARM_STATE_CHANGED) - uiItemR(row, ptr, "value", 0, NULL, ICON_NONE); -} - -static void draw_sensor_collision(uiLayout *layout, PointerRNA *ptr, bContext *C) -{ - uiLayout *row, *split; - PointerRNA main_ptr; - - RNA_main_pointer_create(CTX_data_main(C), &main_ptr); - - split = uiLayoutSplit(layout, 0.3f, false); - row = uiLayoutRow(split, true); - uiItemR(row, ptr, "use_pulse", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - uiItemR(row, ptr, "use_material", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - - switch (RNA_boolean_get(ptr, "use_material")) { - case SENS_COLLISION_PROPERTY: - uiItemR(split, ptr, "property", 0, NULL, ICON_NONE); - break; - case SENS_COLLISION_MATERIAL: - uiItemPointerR(split, ptr, "material", &main_ptr, "materials", NULL, ICON_MATERIAL_DATA); - break; - } -} - -static void draw_sensor_delay(uiLayout *layout, PointerRNA *ptr) -{ - uiLayout *row; - - row = uiLayoutRow(layout, false); - - uiItemR(row, ptr, "delay", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "duration", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "use_repeat", 0, NULL, ICON_NONE); -} - -static void draw_sensor_joystick(uiLayout *layout, PointerRNA *ptr) -{ - uiLayout *col, *row; - - uiItemR(layout, ptr, "joystick_index", 0, NULL, ICON_NONE); - uiItemR(layout, ptr, "event_type", 0, NULL, ICON_NONE); - - switch (RNA_enum_get(ptr, "event_type")) { - case SENS_JOY_BUTTON: - uiItemR(layout, ptr, "use_all_events", 0, NULL, ICON_NONE); - - col = uiLayoutColumn(layout, false); - uiLayoutSetActive(col, RNA_boolean_get(ptr, "use_all_events") == false); - uiItemR(col, ptr, "button_number", 0, NULL, ICON_NONE); - break; - case SENS_JOY_AXIS: - row = uiLayoutRow(layout, false); - uiItemR(row, ptr, "axis_number", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "axis_threshold", 0, NULL, ICON_NONE); - - uiItemR(layout, ptr, "use_all_events", 0, NULL, ICON_NONE); - col = uiLayoutColumn(layout, false); - uiLayoutSetActive(col, RNA_boolean_get(ptr, "use_all_events") == false); - uiItemR(col, ptr, "axis_direction", 0, NULL, ICON_NONE); - break; - case SENS_JOY_HAT: - uiItemR(layout, ptr, "hat_number", 0, NULL, ICON_NONE); - uiItemR(layout, ptr, "use_all_events", 0, NULL, ICON_NONE); - - col = uiLayoutColumn(layout, false); - uiLayoutSetActive(col, RNA_boolean_get(ptr, "use_all_events") == false); - uiItemR(col, ptr, "hat_direction", 0, NULL, ICON_NONE); - break; - case SENS_JOY_AXIS_SINGLE: - row = uiLayoutRow(layout, false); - uiItemR(row, ptr, "single_axis_number", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "axis_threshold", 0, NULL, ICON_NONE); - break; - } -} - -static void draw_sensor_keyboard(uiLayout *layout, PointerRNA *ptr) -{ - Object *ob = (Object *)ptr->id.data; - PointerRNA settings_ptr; - uiLayout *row, *col; - - row = uiLayoutRow(layout, false); - uiItemL(row, CTX_IFACE_(BLT_I18NCONTEXT_ID_WINDOWMANAGER, "Key:"), ICON_NONE); - col = uiLayoutColumn(row, false); - uiLayoutSetActive(col, RNA_boolean_get(ptr, "use_all_keys") == false); - uiItemR(col, ptr, "key", UI_ITEM_R_EVENT, "", ICON_NONE); - col = uiLayoutColumn(row, false); - uiItemR(col, ptr, "use_all_keys", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - - col = uiLayoutColumn(layout, false); - uiLayoutSetActive(col, RNA_boolean_get(ptr, "use_all_keys") == false); - row = uiLayoutRow(col, false); - uiItemL(row, IFACE_("First Modifier:"), ICON_NONE); - uiItemR(row, ptr, "modifier_key_1", UI_ITEM_R_EVENT, "", ICON_NONE); - - row = uiLayoutRow(col, false); - uiItemL(row, IFACE_("Second Modifier:"), ICON_NONE); - uiItemR(row, ptr, "modifier_key_2", UI_ITEM_R_EVENT, "", ICON_NONE); - - RNA_pointer_create((ID *)ob, &RNA_GameObjectSettings, ob, &settings_ptr); - uiItemPointerR(layout, ptr, "log", &settings_ptr, "properties", NULL, ICON_NONE); - uiItemPointerR(layout, ptr, "target", &settings_ptr, "properties", NULL, ICON_NONE); -} - -static void draw_sensor_message(uiLayout *layout, PointerRNA *ptr) -{ - uiItemR(layout, ptr, "subject", 0, NULL, ICON_NONE); -} - -static void draw_sensor_mouse(uiLayout *layout, PointerRNA *ptr, bContext *C) -{ - uiLayout *split, *split2; - PointerRNA main_ptr; - - split = uiLayoutSplit(layout, 0.8f, false); - uiItemR(split, ptr, "mouse_event", 0, NULL, ICON_NONE); - - if (RNA_enum_get(ptr, "mouse_event") == BL_SENS_MOUSE_MOUSEOVER_ANY) { - uiItemR(split, ptr, "use_pulse", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - - split = uiLayoutSplit(layout, 0.3f, false); - uiItemR(split, ptr, "use_material", 0, "", ICON_NONE); - - split2 = uiLayoutSplit(split, 0.7f, false); - if (RNA_enum_get(ptr, "use_material") == SENS_RAY_PROPERTY) { - uiItemR(split2, ptr, "property", 0, "", ICON_NONE); - } - else { - RNA_main_pointer_create(CTX_data_main(C), &main_ptr); - uiItemPointerR(split2, ptr, "material", &main_ptr, "materials", "", ICON_MATERIAL_DATA); - } - uiItemR(split2, ptr, "use_x_ray", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - } -} - -static void draw_sensor_near(uiLayout *layout, PointerRNA *ptr) -{ - uiLayout *row; - - uiItemR(layout, ptr, "property", 0, NULL, ICON_NONE); - - row = uiLayoutRow(layout, true); - uiItemR(row, ptr, "distance", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "reset_distance", 0, NULL, ICON_NONE); -} - -static void draw_sensor_property(uiLayout *layout, PointerRNA *ptr) -{ - Object *ob = (Object *)ptr->id.data; - PointerRNA settings_ptr; - - uiLayout *row; - uiItemR(layout, ptr, "evaluation_type", 0, NULL, ICON_NONE); - - RNA_pointer_create((ID *)ob, &RNA_GameObjectSettings, ob, &settings_ptr); - uiItemPointerR(layout, ptr, "property", &settings_ptr, "properties", NULL, ICON_NONE); - - switch (RNA_enum_get(ptr, "evaluation_type")) { - case SENS_PROP_INTERVAL: - row = uiLayoutRow(layout, false); - uiItemR(row, ptr, "value_min", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "value_max", 0, NULL, ICON_NONE); - break; - case SENS_PROP_EQUAL: - case SENS_PROP_NEQUAL: - case SENS_PROP_LESSTHAN: - case SENS_PROP_GREATERTHAN: - uiItemR(layout, ptr, "value", 0, NULL, ICON_NONE); - break; - case SENS_PROP_CHANGED: - break; - } -} - -static void draw_sensor_radar(uiLayout *layout, PointerRNA *ptr) -{ - uiLayout *row; - - uiItemR(layout, ptr, "property", 0, NULL, ICON_NONE); - uiItemR(layout, ptr, "axis", 0, NULL, ICON_NONE); - - row = uiLayoutRow(layout, false); - uiItemR(row, ptr, "angle", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "distance", 0, NULL, ICON_NONE); -} - -static void draw_sensor_random(uiLayout *layout, PointerRNA *ptr) -{ - uiItemR(layout, ptr, "seed", 0, NULL, ICON_NONE); -} - -static void draw_sensor_ray(uiLayout *layout, PointerRNA *ptr, bContext *C) -{ - uiLayout *split, *row; - PointerRNA main_ptr; - - RNA_main_pointer_create(CTX_data_main(C), &main_ptr); - split = uiLayoutSplit(layout, 0.3f, false); - uiItemR(split, ptr, "ray_type", 0, "", ICON_NONE); - switch (RNA_enum_get(ptr, "ray_type")) { - case SENS_RAY_PROPERTY: - uiItemR(split, ptr, "property", 0, "", ICON_NONE); - break; - case SENS_RAY_MATERIAL: - uiItemPointerR(split, ptr, "material", &main_ptr, "materials", "", ICON_MATERIAL_DATA); - break; - } - - split = uiLayoutSplit(layout, 0.3, false); - uiItemR(split, ptr, "axis", 0, "", ICON_NONE); - row = uiLayoutRow(split, false); - uiItemR(row, ptr, "range", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "use_x_ray", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); -} - -static void draw_brick_sensor(uiLayout *layout, PointerRNA *ptr, bContext *C) -{ - uiLayout *box; - - if (!RNA_boolean_get(ptr, "show_expanded")) - return; - - draw_sensor_internal_header(layout, ptr); - - box = uiLayoutBox(layout); - uiLayoutSetActive(box, RNA_boolean_get(ptr, "active")); - - switch (RNA_enum_get(ptr, "type")) { - - case SENS_ACTUATOR: - draw_sensor_actuator(box, ptr); - break; - case SENS_ALWAYS: - break; - case SENS_ARMATURE: - draw_sensor_armature(box, ptr); - break; - case SENS_COLLISION: - draw_sensor_collision(box, ptr, C); - break; - case SENS_DELAY: - draw_sensor_delay(box, ptr); - break; - case SENS_JOYSTICK: - draw_sensor_joystick(box, ptr); - break; - case SENS_KEYBOARD: - draw_sensor_keyboard(box, ptr); - break; - case SENS_MESSAGE: - draw_sensor_message(box, ptr); - break; - case SENS_MOUSE: - draw_sensor_mouse(box, ptr, C); - break; - case SENS_NEAR: - draw_sensor_near(box, ptr); - break; - case SENS_PROPERTY: - draw_sensor_property(box, ptr); - break; - case SENS_RADAR: - draw_sensor_radar(box, ptr); - break; - case SENS_RANDOM: - draw_sensor_random(box, ptr); - break; - case SENS_RAY: - draw_sensor_ray(box, ptr, C); - break; - } -} - -/* Controller code */ -static void draw_controller_header(uiLayout *layout, PointerRNA *ptr, int xco, int width, int yco) -{ - uiLayout *box, *row, *sub; - bController *cont= (bController *)ptr->data; - - char state[3]; - BLI_snprintf(state, sizeof(state), "%d", RNA_int_get(ptr, "states")); - - box = uiLayoutBox(layout); - row = uiLayoutRow(box, false); - - sub = uiLayoutRow(row, false); - uiLayoutSetActive(sub, RNA_boolean_get(ptr, "active")); - uiItemR(sub, ptr, "show_expanded", UI_ITEM_R_NO_BG, "", ICON_NONE); - if (RNA_boolean_get(ptr, "show_expanded")) { - uiItemR(sub, ptr, "type", 0, "", ICON_NONE); - uiItemR(sub, ptr, "name", 0, "", ICON_NONE); - /* XXX provisory for Blender 2.50Beta */ - uiDefBlockBut(uiLayoutGetBlock(layout), controller_state_mask_menu, cont, state, (short)(xco+width-44), yco, 22+22, UI_UNIT_Y, IFACE_("Set controller state index (from 1 to 30)")); - } - else { - uiItemL(sub, IFACE_(controller_name(cont->type)), ICON_NONE); - uiItemL(sub, cont->name, ICON_NONE); - uiItemL(sub, state, ICON_NONE); - } - - sub = uiLayoutRow(row, false); - uiLayoutSetActive(sub, RNA_boolean_get(ptr, "active")); - uiItemR(sub, ptr, "use_priority", 0, "", ICON_NONE); - - if (RNA_boolean_get(ptr, "show_expanded")==0) { - sub = uiLayoutRow(row, true); - uiLayoutSetActive(sub, RNA_boolean_get(ptr, "active")); - uiItemEnumO(sub, "LOGIC_OT_controller_move", "", ICON_TRIA_UP, "direction", 1); // up - uiItemEnumO(sub, "LOGIC_OT_controller_move", "", ICON_TRIA_DOWN, "direction", 2); // down - } - - sub = uiLayoutRow(row, false); - uiItemR(sub, ptr, "active", 0, "", ICON_NONE); - - sub = uiLayoutRow(row, false); - uiLayoutSetActive(sub, RNA_boolean_get(ptr, "active")); - uiItemO(sub, "", ICON_X, "LOGIC_OT_controller_remove"); -} - -static void draw_controller_expression(uiLayout *layout, PointerRNA *ptr) -{ - uiItemR(layout, ptr, "expression", 0, "", ICON_NONE); -} - -static void draw_controller_python(uiLayout *layout, PointerRNA *ptr) -{ - uiLayout *split, *sub; - - split = uiLayoutSplit(layout, 0.3, true); - uiItemR(split, ptr, "mode", 0, "", ICON_NONE); - if (RNA_enum_get(ptr, "mode") == CONT_PY_SCRIPT) { - uiItemR(split, ptr, "text", 0, "", ICON_NONE); - } - else { - sub = uiLayoutSplit(split, 0.8f, false); - uiItemR(sub, ptr, "module", 0, "", ICON_NONE); - uiItemR(sub, ptr, "use_debug", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - } -} - -static void draw_controller_state(uiLayout *UNUSED(layout), PointerRNA *UNUSED(ptr)) -{ - -} - -static void draw_brick_controller(uiLayout *layout, PointerRNA *ptr) -{ - uiLayout *box; - - if (!RNA_boolean_get(ptr, "show_expanded")) - return; - - box = uiLayoutBox(layout); - uiLayoutSetActive(box, RNA_boolean_get(ptr, "active")); - - draw_controller_state(box, ptr); - - switch (RNA_enum_get(ptr, "type")) { - case CONT_LOGIC_AND: - break; - case CONT_LOGIC_OR: - break; - case CONT_EXPRESSION: - draw_controller_expression(box, ptr); - break; - case CONT_PYTHON: - draw_controller_python(box, ptr); - break; - case CONT_LOGIC_NAND: - break; - case CONT_LOGIC_NOR: - break; - case CONT_LOGIC_XOR: - break; - case CONT_LOGIC_XNOR: - break; - } -} - -/* Actuator code */ -static void draw_actuator_header(uiLayout *layout, PointerRNA *ptr, PointerRNA *logic_ptr) -{ - uiLayout *box, *row, *sub; - bActuator *act= (bActuator *)ptr->data; - - box = uiLayoutBox(layout); - row = uiLayoutRow(box, false); - - sub = uiLayoutRow(row, false); - uiLayoutSetActive(sub, RNA_boolean_get(ptr, "active")); - uiItemR(sub, ptr, "show_expanded", UI_ITEM_R_NO_BG, "", ICON_NONE); - if (RNA_boolean_get(ptr, "show_expanded")) { - uiItemR(sub, ptr, "type", 0, "", ICON_NONE); - uiItemR(sub, ptr, "name", 0, "", ICON_NONE); - } - else { - uiItemL(sub, IFACE_(actuator_name(act->type)), ICON_NONE); - uiItemL(sub, act->name, ICON_NONE); - } - - sub = uiLayoutRow(row, false); - uiLayoutSetActive(sub, (((RNA_boolean_get(logic_ptr, "show_actuators_active_states") && - RNA_boolean_get(ptr, "show_expanded")) || RNA_boolean_get(ptr, "pin")) && - RNA_boolean_get(ptr, "active"))); - uiItemR(sub, ptr, "pin", UI_ITEM_R_NO_BG, "", ICON_NONE); - - if (RNA_boolean_get(ptr, "show_expanded")==0) { - sub = uiLayoutRow(row, true); - uiLayoutSetActive(sub, RNA_boolean_get(ptr, "active")); - uiItemEnumO(sub, "LOGIC_OT_actuator_move", "", ICON_TRIA_UP, "direction", 1); // up - uiItemEnumO(sub, "LOGIC_OT_actuator_move", "", ICON_TRIA_DOWN, "direction", 2); // down - } - - sub = uiLayoutRow(row, false); - uiItemR(sub, ptr, "active", 0, "", ICON_NONE); - - sub = uiLayoutRow(row, false); - uiLayoutSetActive(sub, RNA_boolean_get(ptr, "active")); - uiItemO(sub, "", ICON_X, "LOGIC_OT_actuator_remove"); -} - -static void draw_actuator_action(uiLayout *layout, PointerRNA *ptr) -{ - Object *ob = (Object *)ptr->id.data; - PointerRNA settings_ptr; - uiLayout *row, *sub; - - RNA_pointer_create((ID *)ob, &RNA_GameObjectSettings, ob, &settings_ptr); - - row = uiLayoutRow(layout, false); - uiItemR(row, ptr, "play_mode", 0, "", ICON_NONE); - - sub = uiLayoutRow(row, true); - uiItemR(sub, ptr, "use_force", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - uiItemR(sub, ptr, "use_additive", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - - row = uiLayoutColumn(sub, false); - uiLayoutSetActive(row, (RNA_boolean_get(ptr, "use_additive") || RNA_boolean_get(ptr, "use_force"))); - uiItemR(row, ptr, "use_local", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - - row = uiLayoutRow(layout, false); - uiItemR(row, ptr, "action", 0, "", ICON_NONE); - uiItemR(row, ptr, "use_continue_last_frame", 0, NULL, ICON_NONE); - - row = uiLayoutRow(layout, false); - if ((RNA_enum_get(ptr, "play_mode") == ACT_ACTION_FROM_PROP)) - uiItemPointerR(row, ptr, "property", &settings_ptr, "properties", NULL, ICON_NONE); - - else { - uiItemR(row, ptr, "frame_start", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "frame_end", 0, NULL, ICON_NONE); - } - - uiItemR(row, ptr, "apply_to_children", 0, NULL, ICON_NONE); - - row = uiLayoutRow(layout, false); - uiItemR(row, ptr, "frame_blend_in", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "priority", 0, NULL, ICON_NONE); - - row = uiLayoutRow(layout, false); - uiItemR(row, ptr, "layer", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "layer_weight", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "blend_mode", 0, "", ICON_NONE); - - uiItemPointerR(layout, ptr, "frame_property", &settings_ptr, "properties", NULL, ICON_NONE); - -#ifdef __NLA_ACTION_BY_MOTION_ACTUATOR - uiItemR(layout, "stride_length", 0, NULL, ICON_NONE); -#endif -} - -static void draw_actuator_armature(uiLayout *layout, PointerRNA *ptr) -{ - bActuator *act = (bActuator *)ptr->data; - bArmatureActuator *aa = (bArmatureActuator *) act->data; - Object *ob = (Object *)ptr->id.data; - bConstraint *constraint = NULL; - PointerRNA pose_ptr, pchan_ptr; - PropertyRNA *bones_prop = NULL; - - if (ob->type != OB_ARMATURE) { - uiItemL(layout, IFACE_("Actuator only available for armatures"), ICON_NONE); - return; - } - - if (ob->pose) { - RNA_pointer_create((ID *)ob, &RNA_Pose, ob->pose, &pose_ptr); - bones_prop = RNA_struct_find_property(&pose_ptr, "bones"); - } - - uiItemR(layout, ptr, "mode", 0, NULL, ICON_NONE); - - switch (RNA_enum_get(ptr, "mode")) { - case ACT_ARM_RUN: - break; - case ACT_ARM_ENABLE: - case ACT_ARM_DISABLE: - if (ob->pose) { - uiItemPointerR(layout, ptr, "bone", &pose_ptr, "bones", NULL, ICON_BONE_DATA); - - if (RNA_property_collection_lookup_string(&pose_ptr, bones_prop, aa->posechannel, &pchan_ptr)) - uiItemPointerR(layout, ptr, "constraint", &pchan_ptr, "constraints", NULL, ICON_CONSTRAINT_BONE); - } - break; - case ACT_ARM_SETTARGET: - if (ob->pose) { - uiItemPointerR(layout, ptr, "bone", &pose_ptr, "bones", NULL, ICON_BONE_DATA); - - if (RNA_property_collection_lookup_string(&pose_ptr, bones_prop, aa->posechannel, &pchan_ptr)) - uiItemPointerR(layout, ptr, "constraint", &pchan_ptr, "constraints", NULL, ICON_CONSTRAINT_BONE); - } - - uiItemR(layout, ptr, "target", 0, NULL, ICON_NONE); - - /* show second target only if the constraint supports it */ - get_armature_bone_constraint(ob, aa->posechannel, aa->constraint, &constraint); - if (constraint && constraint->type == CONSTRAINT_TYPE_KINEMATIC) { - uiItemR(layout, ptr, "secondary_target", 0, NULL, ICON_NONE); - } - break; - case ACT_ARM_SETWEIGHT: - if (ob->pose) { - uiItemPointerR(layout, ptr, "bone", &pose_ptr, "bones", NULL, ICON_BONE_DATA); - - if (RNA_property_collection_lookup_string(&pose_ptr, bones_prop, aa->posechannel, &pchan_ptr)) - uiItemPointerR(layout, ptr, "constraint", &pchan_ptr, "constraints", NULL, ICON_CONSTRAINT_BONE); - } - - uiItemR(layout, ptr, "weight", 0, NULL, ICON_NONE); - break; - case ACT_ARM_SETINFLUENCE: - if (ob->pose) { - uiItemPointerR(layout, ptr, "bone", &pose_ptr, "bones", NULL, ICON_BONE_DATA); - - if (RNA_property_collection_lookup_string(&pose_ptr, bones_prop, aa->posechannel, &pchan_ptr)) - uiItemPointerR(layout, ptr, "constraint", &pchan_ptr, "constraints", NULL, ICON_CONSTRAINT_BONE); - } - - uiItemR(layout, ptr, "influence", 0, NULL, ICON_NONE); - break; - } -} - -static void draw_actuator_camera(uiLayout *layout, PointerRNA *ptr) -{ - uiLayout *row; - uiItemR(layout, ptr, "object", 0, NULL, ICON_NONE); - - row = uiLayoutRow(layout, false); - uiItemR(row, ptr, "height", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "axis", 0, NULL, ICON_NONE); - - row = uiLayoutRow(layout, true); - uiItemR(row, ptr, "min", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "max", 0, NULL, ICON_NONE); - - uiItemR(layout, ptr, "damping", 0, NULL, ICON_NONE); -} - -static void draw_actuator_constraint(uiLayout *layout, PointerRNA *ptr, bContext *C) -{ - uiLayout *row, *col, *sub, *split; - PointerRNA main_ptr; - - RNA_main_pointer_create(CTX_data_main(C), &main_ptr); - - uiItemR(layout, ptr, "mode", 0, NULL, ICON_NONE); - switch (RNA_enum_get(ptr, "mode")) { - case ACT_CONST_TYPE_LOC: - uiItemR(layout, ptr, "limit", 0, NULL, ICON_NONE); - - row = uiLayoutRow(layout, true); - uiItemR(row, ptr, "limit_min", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "limit_max", 0, NULL, ICON_NONE); - - uiItemR(layout, ptr, "damping", UI_ITEM_R_SLIDER, NULL, ICON_NONE); - break; - - case ACT_CONST_TYPE_DIST: - split = uiLayoutSplit(layout, 0.8, false); - uiItemR(split, ptr, "direction", 0, NULL, ICON_NONE); - row = uiLayoutRow(split, true); - uiItemR(row, ptr, "use_local", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - uiItemR(row, ptr, "use_normal", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - - row = uiLayoutRow(layout, false); - col = uiLayoutColumn(row, true); - uiItemL(col, IFACE_("Range:"), ICON_NONE); - uiItemR(col, ptr, "range", 0, "", ICON_NONE); - - col = uiLayoutColumn(row, true); - uiItemR(col, ptr, "use_force_distance", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - sub = uiLayoutColumn(col, false); - uiLayoutSetActive(sub, RNA_boolean_get(ptr, "use_force_distance") == true); - uiItemR(sub, ptr, "distance", 0, "", ICON_NONE); - - uiItemR(layout, ptr, "damping", UI_ITEM_R_SLIDER, NULL, ICON_NONE); - - split = uiLayoutSplit(layout, 0.15f, false); - uiItemR(split, ptr, "use_material_detect", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - if (RNA_boolean_get(ptr, "use_material_detect")) - uiItemPointerR(split, ptr, "material", &main_ptr, "materials", NULL, ICON_MATERIAL_DATA); - else - uiItemR(split, ptr, "property", 0, NULL, ICON_NONE); - - split = uiLayoutSplit(layout, 0.15, false); - uiItemR(split, ptr, "use_persistent", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - - row = uiLayoutRow(split, true); - uiItemR(row, ptr, "time", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "damping_rotation", UI_ITEM_R_SLIDER, NULL, ICON_NONE); - break; - - case ACT_CONST_TYPE_ORI: - uiItemR(layout, ptr, "direction_axis_pos", 0, NULL, ICON_NONE); - - row=uiLayoutRow(layout, true); - uiItemR(row, ptr, "damping", UI_ITEM_R_SLIDER, NULL, ICON_NONE); - uiItemR(row, ptr, "time", 0, NULL, ICON_NONE); - - row=uiLayoutRow(layout, false); - uiItemR(row, ptr, "rotation_max", 0, NULL, ICON_NONE); - - row=uiLayoutRow(layout, true); - uiItemR(row, ptr, "angle_min", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "angle_max", 0, NULL, ICON_NONE); - break; - - case ACT_CONST_TYPE_FH: - split = uiLayoutSplit(layout, 0.75, false); - row = uiLayoutRow(split, false); - uiItemR(row, ptr, "fh_damping", UI_ITEM_R_SLIDER, NULL, ICON_NONE); - - uiItemR(row, ptr, "fh_height", 0, NULL, ICON_NONE); - uiItemR(split, ptr, "use_fh_paralel_axis", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - - row = uiLayoutRow(layout, false); - uiItemR(row, ptr, "direction_axis", 0, NULL, ICON_NONE); - split = uiLayoutSplit(row, 0.9f, false); - uiItemR(split, ptr, "fh_force", 0, NULL, ICON_NONE); - uiItemR(split, ptr, "use_fh_normal", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - - split = uiLayoutSplit(layout, 0.15, false); - uiItemR(split, ptr, "use_material_detect", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - if (RNA_boolean_get(ptr, "use_material_detect")) - uiItemPointerR(split, ptr, "material", &main_ptr, "materials", NULL, ICON_MATERIAL_DATA); - else - uiItemR(split, ptr, "property", 0, NULL, ICON_NONE); - - split = uiLayoutSplit(layout, 0.15, false); - uiItemR(split, ptr, "use_persistent", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - - row = uiLayoutRow(split, false); - uiItemR(row, ptr, "time", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "damping_rotation", UI_ITEM_R_SLIDER, NULL, ICON_NONE); - break; - } -} - -static void draw_actuator_edit_object(uiLayout *layout, PointerRNA *ptr) -{ - Object *ob = (Object *)ptr->id.data; - uiLayout *row, *split, *sub; - uiItemR(layout, ptr, "mode", 0, NULL, ICON_NONE); - - switch (RNA_enum_get(ptr, "mode")) { - case ACT_EDOB_ADD_OBJECT: - row = uiLayoutRow(layout, false); - uiItemR(row, ptr, "object", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "time", 0, NULL, ICON_NONE); - - split = uiLayoutSplit(layout, 0.9, false); - row = uiLayoutRow(split, false); - uiItemR(row, ptr, "linear_velocity", 0, NULL, ICON_NONE); - uiItemR(split, ptr, "use_local_linear_velocity", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - - split = uiLayoutSplit(layout, 0.9, false); - row = uiLayoutRow(split, false); - uiItemR(row, ptr, "angular_velocity", 0, NULL, ICON_NONE); - uiItemR(split, ptr, "use_local_angular_velocity", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - break; - case ACT_EDOB_END_OBJECT: - break; - case ACT_EDOB_REPLACE_MESH: - if (ob->type != OB_MESH) { - uiItemL(layout, IFACE_("Mode only available for mesh objects"), ICON_NONE); - break; - } - split = uiLayoutSplit(layout, 0.6, false); - uiItemR(split, ptr, "mesh", 0, NULL, ICON_NONE); - row = uiLayoutRow(split, false); - uiItemR(row, ptr, "use_replace_display_mesh", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - uiItemR(row, ptr, "use_replace_physics_mesh", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - break; - case ACT_EDOB_TRACK_TO: - split = uiLayoutSplit(layout, 0.5, false); - uiItemR(split, ptr, "track_object", 0, NULL, ICON_NONE); - sub = uiLayoutSplit(split, 0.7f, false); - uiItemR(sub, ptr, "time", 0, NULL, ICON_NONE); - uiItemR(sub, ptr, "use_3d_tracking", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - - row = uiLayoutRow(layout, false); - uiItemR(row, ptr, "up_axis", 0, NULL, ICON_NONE); - - row = uiLayoutRow(layout, false); - uiItemR(row, ptr, "track_axis", 0, NULL, ICON_NONE); - break; - case ACT_EDOB_DYNAMICS: - if (ob->type != OB_MESH) { - uiItemL(layout, IFACE_("Mode only available for mesh objects"), ICON_NONE); - break; - } - uiItemR(layout, ptr, "dynamic_operation", 0, NULL, ICON_NONE); - if (RNA_enum_get(ptr, "dynamic_operation") == ACT_EDOB_SET_MASS) - uiItemR(layout, ptr, "mass", 0, NULL, ICON_NONE); - break; - } -} - -static void draw_actuator_filter_2d(uiLayout *layout, PointerRNA *ptr) -{ - uiLayout *row, *split; - - uiItemR(layout, ptr, "mode", 0, NULL, ICON_NONE); - switch (RNA_enum_get(ptr, "mode")) { - case ACT_2DFILTER_CUSTOMFILTER: - uiItemR(layout, ptr, "filter_pass", 0, NULL, ICON_NONE); - uiItemR(layout, ptr, "glsl_shader", 0, NULL, ICON_NONE); - break; - case ACT_2DFILTER_MOTIONBLUR: - split=uiLayoutSplit(layout, 0.75f, true); - row = uiLayoutRow(split, false); - uiLayoutSetActive(row, RNA_boolean_get(ptr, "use_motion_blur") == true); - uiItemR(row, ptr, "motion_blur_factor", 0, NULL, ICON_NONE); - uiItemR(split, ptr, "use_motion_blur", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - break; - default: // all other 2D Filters - uiItemR(layout, ptr, "filter_pass", 0, NULL, ICON_NONE); - break; - } -} - -static void draw_actuator_game(uiLayout *layout, PointerRNA *ptr) -{ - uiItemR(layout, ptr, "mode", 0, NULL, ICON_NONE); - if (ELEM(RNA_enum_get(ptr, "mode"), ACT_GAME_LOAD, ACT_GAME_SCREENSHOT)) - uiItemR(layout, ptr, "filename", 0, NULL, ICON_NONE); -} - -static void draw_actuator_message(uiLayout *layout, PointerRNA *ptr, bContext *C) -{ - Object *ob; - PointerRNA main_ptr, settings_ptr; - uiLayout *row; - - RNA_main_pointer_create(CTX_data_main(C), &main_ptr); - - ob = (Object *)ptr->id.data; - RNA_pointer_create((ID *)ob, &RNA_GameObjectSettings, ob, &settings_ptr); - - uiItemPointerR(layout, ptr, "to_property", &main_ptr, "objects", NULL, ICON_OBJECT_DATA); - uiItemR(layout, ptr, "subject", 0, NULL, ICON_NONE); - - row = uiLayoutRow(layout, true); - uiItemR(row, ptr, "body_type", 0, NULL, ICON_NONE); - - if (RNA_enum_get(ptr, "body_type") == ACT_MESG_MESG) - uiItemR(row, ptr, "body_message", 0, "", ICON_NONE); - else // mode == ACT_MESG_PROP - uiItemPointerR(row, ptr, "body_property", &settings_ptr, "properties", "", ICON_NONE); -} - -static void draw_actuator_motion(uiLayout *layout, PointerRNA *ptr) -{ - Object *ob; - PointerRNA settings_ptr; - uiLayout *split, *row, *col, *sub; - int physics_type; - - ob = (Object *)ptr->id.data; - RNA_pointer_create((ID *)ob, &RNA_GameObjectSettings, ob, &settings_ptr); - physics_type = RNA_enum_get(&settings_ptr, "physics_type"); - - uiItemR(layout, ptr, "mode", 0, NULL, ICON_NONE); - - switch (RNA_enum_get(ptr, "mode")) { - case ACT_OBJECT_NORMAL: - split = uiLayoutSplit(layout, 0.9, false); - row = uiLayoutRow(split, false); - uiItemR(row, ptr, "offset_location", 0, NULL, ICON_NONE); - uiItemR(split, ptr, "use_local_location", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - - split = uiLayoutSplit(layout, 0.9, false); - row = uiLayoutRow(split, false); - uiItemR(row, ptr, "offset_rotation", 0, NULL, ICON_NONE); - uiItemR(split, ptr, "use_local_rotation", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - - if (ELEM(physics_type, OB_BODY_TYPE_DYNAMIC, OB_BODY_TYPE_RIGID, OB_BODY_TYPE_SOFT)) { - uiItemL(layout, IFACE_("Dynamic Object Settings:"), ICON_NONE); - split = uiLayoutSplit(layout, 0.9, false); - row = uiLayoutRow(split, false); - uiItemR(row, ptr, "force", 0, NULL, ICON_NONE); - uiItemR(split, ptr, "use_local_force", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - - split = uiLayoutSplit(layout, 0.9, false); - row = uiLayoutRow(split, false); - uiItemR(row, ptr, "torque", 0, NULL, ICON_NONE); - uiItemR(split, ptr, "use_local_torque", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - - split = uiLayoutSplit(layout, 0.9, false); - row = uiLayoutRow(split, false); - uiItemR(row, ptr, "linear_velocity", 0, NULL, ICON_NONE); - row = uiLayoutRow(split, true); - uiItemR(row, ptr, "use_local_linear_velocity", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - uiItemR(row, ptr, "use_add_linear_velocity", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - - split = uiLayoutSplit(layout, 0.9, false); - row = uiLayoutRow(split, false); - uiItemR(row, ptr, "angular_velocity", 0, NULL, ICON_NONE); - uiItemR(split, ptr, "use_local_angular_velocity", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - - uiItemR(layout, ptr, "damping", 0, NULL, ICON_NONE); - } - break; - case ACT_OBJECT_SERVO: - uiItemR(layout, ptr, "reference_object", 0, NULL, ICON_NONE); - - split = uiLayoutSplit(layout, 0.9, false); - row = uiLayoutRow(split, false); - uiItemR(row, ptr, "linear_velocity", 0, NULL, ICON_NONE); - uiItemR(split, ptr, "use_local_linear_velocity", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - - row = uiLayoutRow(layout, false); - col = uiLayoutColumn(row, false); - uiItemR(col, ptr, "use_servo_limit_x", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - sub = uiLayoutColumn(col, true); - uiLayoutSetActive(sub, RNA_boolean_get(ptr, "use_servo_limit_x") == true); - uiItemR(sub, ptr, "force_max_x", 0, NULL, ICON_NONE); - uiItemR(sub, ptr, "force_min_x", 0, NULL, ICON_NONE); - - col = uiLayoutColumn(row, false); - uiItemR(col, ptr, "use_servo_limit_y", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - sub = uiLayoutColumn(col, true); - uiLayoutSetActive(sub, RNA_boolean_get(ptr, "use_servo_limit_y") == true); - uiItemR(sub, ptr, "force_max_y", 0, NULL, ICON_NONE); - uiItemR(sub, ptr, "force_min_y", 0, NULL, ICON_NONE); - - col = uiLayoutColumn(row, false); - uiItemR(col, ptr, "use_servo_limit_z", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - sub = uiLayoutColumn(col, true); - uiLayoutSetActive(sub, RNA_boolean_get(ptr, "use_servo_limit_z") == true); - uiItemR(sub, ptr, "force_max_z", 0, NULL, ICON_NONE); - uiItemR(sub, ptr, "force_min_z", 0, NULL, ICON_NONE); - - //XXXACTUATOR missing labels from original 2.49 ui (e.g. Servo, Min, Max, Fast) - //Layout designers willing to help on that, please compare with 2.49 ui - // (since the old code is going to be deleted ... soon) - - col = uiLayoutColumn(layout, true); - uiItemR(col, ptr, "proportional_coefficient", UI_ITEM_R_SLIDER, NULL, ICON_NONE); - uiItemR(col, ptr, "integral_coefficient", UI_ITEM_R_SLIDER, NULL, ICON_NONE); - uiItemR(col, ptr, "derivate_coefficient", UI_ITEM_R_SLIDER, NULL, ICON_NONE); - break; - case ACT_OBJECT_CHARACTER: - split = uiLayoutSplit(layout, 0.9, false); - row = uiLayoutRow(split, false); - uiItemR(row, ptr, "offset_location", 0, NULL, ICON_NONE); - row = uiLayoutRow(split, true); - uiItemR(row, ptr, "use_local_location", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - uiItemR(row, ptr, "use_add_character_location", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - - split = uiLayoutSplit(layout, 0.9, false); - row = uiLayoutRow(split, false); - uiItemR(row, ptr, "offset_rotation", 0, NULL, ICON_NONE); - uiItemR(split, ptr, "use_local_rotation", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - - split = uiLayoutSplit(layout, 0.9, false); - row = uiLayoutRow(split, false); - split = uiLayoutSplit(row, 0.7, false); - uiItemL(split, "", ICON_NONE); /*Just use this for some spacing */ - uiItemR(split, ptr, "use_character_jump", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - break; - } -} - -static void draw_actuator_parent(uiLayout *layout, PointerRNA *ptr) -{ - uiLayout *row, *sub; - - uiItemR(layout, ptr, "mode", 0, NULL, ICON_NONE); - - if (RNA_enum_get(ptr, "mode") == ACT_PARENT_SET) { - uiItemR(layout, ptr, "object", 0, NULL, ICON_NONE); - - row = uiLayoutRow(layout, false); - uiItemR(row, ptr, "use_compound", 0, NULL, ICON_NONE); - sub = uiLayoutRow(row, false); - uiLayoutSetActive(sub, RNA_boolean_get(ptr, "use_compound") == true); - uiItemR(sub, ptr, "use_ghost", 0, NULL, ICON_NONE); - } -} - -static void draw_actuator_property(uiLayout *layout, PointerRNA *ptr) -{ - Object *ob = (Object *)ptr->id.data; - bActuator *act = (bActuator *)ptr->data; - bPropertyActuator *pa = (bPropertyActuator *) act->data; - Object *ob_from= pa->ob; - PointerRNA settings_ptr, obj_settings_ptr; - - uiLayout *row, *sub; - - RNA_pointer_create((ID *)ob, &RNA_GameObjectSettings, ob, &settings_ptr); - - uiItemR(layout, ptr, "mode", 0, NULL, ICON_NONE); - uiItemPointerR(layout, ptr, "property", &settings_ptr, "properties", NULL, ICON_NONE); - - switch (RNA_enum_get(ptr, "mode")) { - case ACT_PROP_TOGGLE: - case ACT_PROP_LEVEL: - break; - case ACT_PROP_ADD: - uiItemR(layout, ptr, "value", 0, NULL, ICON_NONE); - break; - case ACT_PROP_ASSIGN: - uiItemR(layout, ptr, "value", 0, NULL, ICON_NONE); - break; - case ACT_PROP_COPY: - row = uiLayoutRow(layout, false); - uiItemR(row, ptr, "object", 0, NULL, ICON_NONE); - if (ob_from) { - RNA_pointer_create((ID *)ob_from, &RNA_GameObjectSettings, ob_from, &obj_settings_ptr); - uiItemPointerR(row, ptr, "object_property", &obj_settings_ptr, "properties", NULL, ICON_NONE); - } - else { - sub = uiLayoutRow(row, false); - uiLayoutSetActive(sub, false); - uiItemR(sub, ptr, "object_property", 0, NULL, ICON_NONE); - } - break; - } -} - -static void draw_actuator_random(uiLayout *layout, PointerRNA *ptr) -{ - Object *ob; - PointerRNA settings_ptr; - uiLayout *row; - - ob = (Object *)ptr->id.data; - RNA_pointer_create((ID *)ob, &RNA_GameObjectSettings, ob, &settings_ptr); - - row = uiLayoutRow(layout, false); - - uiItemR(row, ptr, "seed", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "distribution", 0, NULL, ICON_NONE); - - row = uiLayoutRow(layout, false); - uiItemPointerR(row, ptr, "property", &settings_ptr, "properties", NULL, ICON_NONE); - - row = uiLayoutRow(layout, false); - - switch (RNA_enum_get(ptr, "distribution")) { - case ACT_RANDOM_BOOL_CONST: - uiItemR(row, ptr, "use_always_true", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - break; - - case ACT_RANDOM_BOOL_UNIFORM: - uiItemL(row, IFACE_("Choose between true and false, 50% chance each"), ICON_NONE); - break; - - case ACT_RANDOM_BOOL_BERNOUILLI: - uiItemR(row, ptr, "chance", 0, NULL, ICON_NONE); - break; - - case ACT_RANDOM_INT_CONST: - uiItemR(row, ptr, "int_value", 0, NULL, ICON_NONE); - break; - - case ACT_RANDOM_INT_UNIFORM: - uiItemR(row, ptr, "int_min", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "int_max", 0, NULL, ICON_NONE); - break; - - case ACT_RANDOM_INT_POISSON: - uiItemR(row, ptr, "int_mean", 0, NULL, ICON_NONE); - break; - - case ACT_RANDOM_FLOAT_CONST: - uiItemR(row, ptr, "float_value", 0, NULL, ICON_NONE); - break; - - case ACT_RANDOM_FLOAT_UNIFORM: - uiItemR(row, ptr, "float_min", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "float_max", 0, NULL, ICON_NONE); - break; - - case ACT_RANDOM_FLOAT_NORMAL: - uiItemR(row, ptr, "float_mean", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "standard_derivation", 0, NULL, ICON_NONE); - break; - - case ACT_RANDOM_FLOAT_NEGATIVE_EXPONENTIAL: - uiItemR(row, ptr, "half_life_time", 0, NULL, ICON_NONE); - break; - } -} - -static void draw_actuator_scene(uiLayout *layout, PointerRNA *ptr) -{ - uiItemR(layout, ptr, "mode", 0, NULL, ICON_NONE); - - switch (RNA_enum_get(ptr, "mode")) { - case ACT_SCENE_CAMERA: - uiItemR(layout, ptr, "camera", 0, NULL, ICON_NONE); - break; - case ACT_SCENE_RESTART: - break; - default: // ACT_SCENE_SET|ACT_SCENE_ADD_FRONT|ACT_SCENE_ADD_BACK|ACT_SCENE_REMOVE|ACT_SCENE_SUSPEND|ACT_SCENE_RESUME - uiItemR(layout, ptr, "scene", 0, NULL, ICON_NONE); - break; - } -} - -static void draw_actuator_shape_action(uiLayout *layout, PointerRNA *ptr) -{ - Object *ob = (Object *)ptr->id.data; - PointerRNA settings_ptr; - uiLayout *row; - - if (ob->type != OB_MESH) { - uiItemL(layout, IFACE_("Actuator only available for mesh objects"), ICON_NONE); - return; - } - - RNA_pointer_create((ID *)ob, &RNA_GameObjectSettings, ob, &settings_ptr); - - row = uiLayoutRow(layout, false); - uiItemR(row, ptr, "mode", 0, "", ICON_NONE); - uiItemR(row, ptr, "action", 0, "", ICON_NONE); - uiItemR(row, ptr, "use_continue_last_frame", 0, NULL, ICON_NONE); - - row = uiLayoutRow(layout, false); - if ((RNA_enum_get(ptr, "mode") == ACT_ACTION_FROM_PROP)) - uiItemPointerR(row, ptr, "property", &settings_ptr, "properties", NULL, ICON_NONE); - - else { - uiItemR(row, ptr, "frame_start", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "frame_end", 0, NULL, ICON_NONE); - } - - row = uiLayoutRow(layout, false); - uiItemR(row, ptr, "frame_blend_in", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "priority", 0, NULL, ICON_NONE); - - row = uiLayoutRow(layout, false); - uiItemPointerR(row, ptr, "frame_property", &settings_ptr, "properties", NULL, ICON_NONE); - -#ifdef __NLA_ACTION_BY_MOTION_ACTUATOR - uiItemR(row, "stride_length", 0, NULL, ICON_NONE); -#endif -} - -static void draw_actuator_sound(uiLayout *layout, PointerRNA *ptr, bContext *C) -{ - uiLayout *row, *col; - - uiTemplateID(layout, C, ptr, "sound", NULL, "SOUND_OT_open", NULL, UI_TEMPLATE_ID_FILTER_ALL); - if (!RNA_pointer_get(ptr, "sound").data) { - uiItemL(layout, IFACE_("Select a sound from the list or load a new one"), ICON_NONE); - return; - } - uiItemR(layout, ptr, "mode", 0, NULL, ICON_NONE); - - row = uiLayoutRow(layout, false); - uiItemR(row, ptr, "volume", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "pitch", 0, NULL, ICON_NONE); - - uiItemR(layout, ptr, "use_sound_3d", 0, NULL, ICON_NONE); - - col = uiLayoutColumn(layout, false); - uiLayoutSetActive(col, RNA_boolean_get(ptr, "use_sound_3d") == true); - - row = uiLayoutRow(col, false); - uiItemR(row, ptr, "gain_3d_min", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "gain_3d_max", 0, NULL, ICON_NONE); - - row = uiLayoutRow(col, false); - uiItemR(row, ptr, "distance_3d_reference", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "distance_3d_max", 0, NULL, ICON_NONE); - - row = uiLayoutRow(col, false); - uiItemR(row, ptr, "rolloff_factor_3d", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "cone_outer_gain_3d", 0, NULL, ICON_NONE); - - row = uiLayoutRow(col, false); - uiItemR(row, ptr, "cone_outer_angle_3d", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "cone_inner_angle_3d", 0, NULL, ICON_NONE); -} - -static void draw_actuator_state(uiLayout *layout, PointerRNA *ptr) -{ - uiLayout *split; - Object *ob = (Object *)ptr->id.data; - PointerRNA settings_ptr; - RNA_pointer_create((ID *)ob, &RNA_GameObjectSettings, ob, &settings_ptr); - - split = uiLayoutSplit(layout, 0.35, false); - uiItemR(split, ptr, "operation", 0, NULL, ICON_NONE); - - uiTemplateLayers(split, ptr, "states", &settings_ptr, "used_states", 0); -} - -static void draw_actuator_visibility(uiLayout *layout, PointerRNA *ptr) -{ - uiLayout *row; - row = uiLayoutRow(layout, false); - - uiItemR(row, ptr, "use_visible", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "use_occlusion", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "apply_to_children", 0, NULL, ICON_NONE); -} - -static void draw_actuator_steering(uiLayout *layout, PointerRNA *ptr) -{ - uiLayout *row; - uiLayout *col; - - uiItemR(layout, ptr, "mode", 0, NULL, ICON_NONE); - uiItemR(layout, ptr, "target", 0, NULL, ICON_NONE); - uiItemR(layout, ptr, "navmesh", 0, NULL, ICON_NONE); - - row = uiLayoutRow(layout, false); - uiItemR(row, ptr, "distance", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "velocity", 0, NULL, ICON_NONE); - row = uiLayoutRow(layout, false); - uiItemR(row, ptr, "acceleration", 0, NULL, ICON_NONE); - uiItemR(row, ptr, "turn_speed", 0, NULL, ICON_NONE); - - row = uiLayoutRow(layout, false); - col = uiLayoutColumn(row, false); - uiItemR(col, ptr, "facing", 0, NULL, ICON_NONE); - col = uiLayoutColumn(row, false); - uiItemR(col, ptr, "facing_axis", 0, NULL, ICON_NONE); - if (!RNA_boolean_get(ptr, "facing")) { - uiLayoutSetActive(col, false); - } - col = uiLayoutColumn(row, false); - uiItemR(col, ptr, "normal_up", 0, NULL, ICON_NONE); - if (!RNA_pointer_get(ptr, "navmesh").data) { - uiLayoutSetActive(col, false); - } - - row = uiLayoutRow(layout, false); - col = uiLayoutColumn(row, false); - uiItemR(col, ptr, "self_terminated", 0, NULL, ICON_NONE); - if (RNA_enum_get(ptr, "mode")==ACT_STEERING_PATHFOLLOWING) { - col = uiLayoutColumn(row, false); - uiItemR(col, ptr, "update_period", 0, NULL, ICON_NONE); - } - row = uiLayoutRow(layout, false); - uiItemR(row, ptr, "lock_z_velocity", 1, NULL, ICON_NONE); - row = uiLayoutRow(layout, false); - uiItemR(row, ptr, "show_visualization", 0, NULL, ICON_NONE); - if (RNA_enum_get(ptr, "mode") != ACT_STEERING_PATHFOLLOWING) { - uiLayoutSetActive(row, false); - } -} - -static void draw_actuator_mouse(uiLayout *layout, PointerRNA *ptr) -{ - uiLayout *row, *col, *subcol, *split, *subsplit; - - uiItemR(layout, ptr, "mode", 0, NULL, 0); - - switch (RNA_enum_get(ptr, "mode")) { - case ACT_MOUSE_VISIBILITY: - row = uiLayoutRow(layout, 0); - uiItemR(row, ptr, "visible", UI_ITEM_R_TOGGLE, NULL, 0); - break; - - case ACT_MOUSE_LOOK: - /* X axis */ - row = uiLayoutRow(layout, 0); - col = uiLayoutColumn(row, 1); - - uiItemR(col, ptr, "use_axis_x", UI_ITEM_R_TOGGLE, NULL, 0); - - subcol = uiLayoutColumn(col, 1); - uiLayoutSetActive(subcol, RNA_boolean_get(ptr, "use_axis_x")==1); - uiItemR(subcol, ptr, "sensitivity_x", 0, NULL, 0); - uiItemR(subcol, ptr, "threshold_x", 0, NULL, 0); - - uiItemR(subcol, ptr, "min_x", 0, NULL, 0); - uiItemR(subcol, ptr, "max_x", 0, NULL, 0); - - uiItemR(subcol, ptr, "object_axis_x", 0, NULL, 0); - - /* Y Axis */ - col = uiLayoutColumn(row, 1); - - uiItemR(col, ptr, "use_axis_y", UI_ITEM_R_TOGGLE, NULL, 0); - - subcol = uiLayoutColumn(col, 1); - uiLayoutSetActive(subcol, RNA_boolean_get(ptr, "use_axis_y")==1); - uiItemR(subcol, ptr, "sensitivity_y", 0, NULL, 0); - uiItemR(subcol, ptr, "threshold_y", 0, NULL, 0); - - uiItemR(subcol, ptr, "min_y", 0, NULL, 0); - uiItemR(subcol, ptr, "max_y", 0, NULL, 0); - - uiItemR(subcol, ptr, "object_axis_y", 0, NULL, 0); - - /* Lower options */ - row = uiLayoutRow(layout, 0); - split = uiLayoutSplit(row, 0.5, 0); - - subsplit = uiLayoutSplit(split, 0.5, 1); - uiLayoutSetActive(subsplit, RNA_boolean_get(ptr, "use_axis_x")==1); - uiItemR(subsplit, ptr, "local_x", UI_ITEM_R_TOGGLE, NULL, 0); - uiItemR(subsplit, ptr, "reset_x", UI_ITEM_R_TOGGLE, NULL, 0); - - subsplit = uiLayoutSplit(split, 0.5, 1); - uiLayoutSetActive(subsplit, RNA_boolean_get(ptr, "use_axis_y")==1); - uiItemR(subsplit, ptr, "local_y", UI_ITEM_R_TOGGLE, NULL, 0); - uiItemR(subsplit, ptr, "reset_y", UI_ITEM_R_TOGGLE, NULL, 0); - - break; - } -} - -static void draw_brick_actuator(uiLayout *layout, PointerRNA *ptr, bContext *C) -{ - uiLayout *box; - - if (!RNA_boolean_get(ptr, "show_expanded")) - return; - - box = uiLayoutBox(layout); - uiLayoutSetActive(box, RNA_boolean_get(ptr, "active")); - - switch (RNA_enum_get(ptr, "type")) { - case ACT_ACTION: - draw_actuator_action(box, ptr); - break; - case ACT_ARMATURE: - draw_actuator_armature(box, ptr); - break; - case ACT_CAMERA: - draw_actuator_camera(box, ptr); - break; - case ACT_CONSTRAINT: - draw_actuator_constraint(box, ptr, C); - break; - case ACT_EDIT_OBJECT: - draw_actuator_edit_object(box, ptr); - break; - case ACT_2DFILTER: - draw_actuator_filter_2d(box, ptr); - break; - case ACT_GAME: - draw_actuator_game(box, ptr); - break; - case ACT_MESSAGE: - draw_actuator_message(box, ptr, C); - break; - case ACT_OBJECT: - draw_actuator_motion(box, ptr); - break; - case ACT_PARENT: - draw_actuator_parent(box, ptr); - break; - case ACT_PROPERTY: - draw_actuator_property(box, ptr); - break; - case ACT_RANDOM: - draw_actuator_random(box, ptr); - break; - case ACT_SCENE: - draw_actuator_scene(box, ptr); - break; - case ACT_SHAPEACTION: - draw_actuator_shape_action(box, ptr); - break; - case ACT_SOUND: - draw_actuator_sound(box, ptr, C); - break; - case ACT_STATE: - draw_actuator_state(box, ptr); - break; - case ACT_VISIBILITY: - draw_actuator_visibility(box, ptr); - break; - case ACT_STEERING: - draw_actuator_steering(box, ptr); - break; - case ACT_MOUSE: - draw_actuator_mouse(box, ptr); - break; - } -} - -void logic_buttons(bContext *C, ARegion *ar) -{ - SpaceLogic *slogic= CTX_wm_space_logic(C); - Object *ob= CTX_data_active_object(C); - ID **idar; - PointerRNA logic_ptr, settings_ptr, object_ptr; - uiLayout *layout, *row, *box; - uiBlock *block; - uiBut *but; - char uiblockstr[32]; - short a, count; - int xco, yco, width, height; - - if (ob==NULL) return; - - RNA_pointer_create(NULL, &RNA_SpaceLogicEditor, slogic, &logic_ptr); - idar= get_selected_and_linked_obs(C, &count, slogic->scaflag); - - BLI_snprintf(uiblockstr, sizeof(uiblockstr), "buttonswin %p", (void *)ar); - block= UI_block_begin(C, ar, uiblockstr, UI_EMBOSS); - UI_block_func_handle_set(block, do_logic_buts, NULL); - UI_block_bounds_set_normal(block, U.widget_unit/2); - - /* loop over all objects and set visible/linked flags for the logic bricks */ - for (a=0; aactuators.first; - while (act) { - act->flag &= ~(ACT_LINKED|ACT_VISIBLE); - act = act->next; - } - /* same for sensors */ - sens= ob->sensors.first; - while (sens) { - sens->flag &= ~(SENS_VISIBLE); - sens = sens->next; - } - - /* mark the linked and visible actuators */ - cont= ob->controllers.first; - while (cont) { - flag = ACT_LINKED; - - /* this controller is visible, mark all its actuator */ - if ((ob->scaflag & OB_ALLSTATE) || (ob->state & cont->state_mask)) - flag |= ACT_VISIBLE; - - for (iact=0; iacttotlinks; iact++) { - act = cont->links[iact]; - if (act) - act->flag |= flag; - } - cont = cont->next; - } - } - - /* ****************** Controllers ****************** */ - - xco= 21 * U.widget_unit; yco= - U.widget_unit / 2; width= 15 * U.widget_unit; - layout= UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, xco, yco, width, 20, 0, UI_style_get()); - row = uiLayoutRow(layout, true); - - uiDefBlockBut(block, controller_menu, NULL, IFACE_("Controllers"), xco - U.widget_unit / 2, yco, width, UI_UNIT_Y, ""); /* replace this with uiLayout stuff later */ - - uiItemR(row, &logic_ptr, "show_controllers_selected_objects", 0, IFACE_("Sel"), ICON_NONE); - uiItemR(row, &logic_ptr, "show_controllers_active_object", 0, IFACE_("Act"), ICON_NONE); - uiItemR(row, &logic_ptr, "show_controllers_linked_controller", 0, IFACE_("Link"), ICON_NONE); - - for (a=0; ascavisflag & OB_VIS_CONT) == 0) { - continue; - } - - /* Drawing the Controller Header common to all Selected Objects */ - - RNA_pointer_create((ID *)ob, &RNA_GameObjectSettings, ob, &settings_ptr); - - split = uiLayoutSplit(layout, 0.05f, false); - uiItemR(split, &settings_ptr, "show_state_panel", UI_ITEM_R_NO_BG, "", ICON_DISCLOSURE_TRI_RIGHT); - - row = uiLayoutRow(split, true); - uiDefButBitS(block, UI_BTYPE_TOGGLE, OB_SHOWCONT, B_REDR, ob->id.name + 2, (short)(xco - U.widget_unit / 2), yco, (short)(width - 1.5f * U.widget_unit), UI_UNIT_Y, &ob->scaflag, 0, 31, 0, 0, TIP_("Object name, click to show/hide controllers")); - - RNA_pointer_create((ID *)ob, &RNA_Object, ob, &object_ptr); - uiLayoutSetContextPointer(row, "object", &object_ptr); - uiItemMenuEnumO(row, C, "LOGIC_OT_controller_add", "type", IFACE_("Add Controller"), ICON_NONE); - - if (RNA_boolean_get(&settings_ptr, "show_state_panel")) { - - box = uiLayoutBox(layout); - split = uiLayoutSplit(box, 0.2f, false); - - col = uiLayoutColumn(split, false); - uiItemL(col, IFACE_("Visible"), ICON_NONE); - uiItemL(col, IFACE_("Initial"), ICON_NONE); - - subsplit = uiLayoutSplit(split, 0.85f, false); - col = uiLayoutColumn(subsplit, false); - row = uiLayoutRow(col, false); - uiLayoutSetActive(row, RNA_boolean_get(&settings_ptr, "use_all_states") == false); - uiTemplateGameStates(row, &settings_ptr, "states_visible", &settings_ptr, "used_states", 0); - row = uiLayoutRow(col, false); - uiTemplateGameStates(row, &settings_ptr, "states_initial", &settings_ptr, "used_states", 0); - - col = uiLayoutColumn(subsplit, false); - uiItemR(col, &settings_ptr, "use_all_states", UI_ITEM_R_TOGGLE, NULL, ICON_NONE); - uiItemR(col, &settings_ptr, "show_debug_state", 0, "", ICON_NONE); - } - - /* End of Drawing the Controller Header common to all Selected Objects */ - - if ((ob->scaflag & OB_SHOWCONT) == 0) continue; - - - uiItemS(layout); - - for (cont= ob->controllers.first; cont; cont=cont->next) { - RNA_pointer_create((ID *)ob, &RNA_Controller, cont, &ptr); - - if (!(ob->scaflag & OB_ALLSTATE) && !(ob->state & cont->state_mask)) - continue; - - /* use two nested splits to align inlinks/links properly */ - split = uiLayoutSplit(layout, 0.05f, false); - - /* put inlink button to the left */ - col = uiLayoutColumn(split, false); - uiLayoutSetActive(col, RNA_boolean_get(&ptr, "active")); - uiLayoutSetAlignment(col, UI_LAYOUT_ALIGN_LEFT); - but = uiDefIconBut(block, UI_BTYPE_INLINK, 0, ICON_INLINK, 0, 0, UI_UNIT_X, UI_UNIT_Y, cont, LINK_CONTROLLER, 0, 0, 0, ""); - if (!RNA_boolean_get(&ptr, "active")) { - UI_but_flag_enable(but, UI_BUT_SCA_LINK_GREY); - } - - //col = uiLayoutColumn(split, true); - /* nested split for middle and right columns */ - subsplit = uiLayoutSplit(split, 0.95f, false); - - col = uiLayoutColumn(subsplit, true); - uiLayoutSetContextPointer(col, "controller", &ptr); - - /* should make UI template for controller header.. function will do for now */ -// draw_controller_header(col, &ptr); - draw_controller_header(col, &ptr, xco, width, yco); //provisory for 2.50 beta - - /* draw the brick contents */ - draw_brick_controller(col, &ptr); - - /* put link button to the right */ - col = uiLayoutColumn(subsplit, false); - uiLayoutSetActive(col, RNA_boolean_get(&ptr, "active")); - uiLayoutSetAlignment(col, UI_LAYOUT_ALIGN_LEFT); - but = uiDefIconBut(block, UI_BTYPE_LINK, 0, ICON_LINK, 0, 0, UI_UNIT_X, UI_UNIT_Y, NULL, 0, 0, 0, 0, ""); - if (!RNA_boolean_get(&ptr, "active")) { - UI_but_flag_enable(but, UI_BUT_SCA_LINK_GREY); - } - - UI_but_link_set(but, NULL, (void ***)&(cont->links), &cont->totlinks, LINK_CONTROLLER, LINK_ACTUATOR); - - } - } - UI_block_layout_resolve(block, NULL, &yco); /* stores final height in yco */ - height = yco; - - /* ****************** Sensors ****************** */ - - xco= U.widget_unit / 2; yco= -U.widget_unit / 2; width= 17 * U.widget_unit; - layout= UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, xco, yco, width, 20, 0, UI_style_get()); - row = uiLayoutRow(layout, true); - - uiDefBlockBut(block, sensor_menu, NULL, IFACE_("Sensors"), xco - U.widget_unit / 2, yco, 15 * U.widget_unit, UI_UNIT_Y, ""); /* replace this with uiLayout stuff later */ - - uiItemR(row, &logic_ptr, "show_sensors_selected_objects", 0, IFACE_("Sel"), ICON_NONE); - uiItemR(row, &logic_ptr, "show_sensors_active_object", 0, IFACE_("Act"), ICON_NONE); - uiItemR(row, &logic_ptr, "show_sensors_linked_controller", 0, IFACE_("Link"), ICON_NONE); - uiItemR(row, &logic_ptr, "show_sensors_active_states", 0, IFACE_("State"), ICON_NONE); - - for (a=0; ascavisflag & OB_VIS_SENS) == 0) continue; - - row = uiLayoutRow(layout, true); - uiDefButBitS(block, UI_BTYPE_TOGGLE, OB_SHOWSENS, B_REDR, ob->id.name + 2, (short)(xco - U.widget_unit / 2), yco, (short)(width - 1.5f * U.widget_unit), UI_UNIT_Y, &ob->scaflag, 0, 31, 0, 0, TIP_("Object name, click to show/hide sensors")); - - RNA_pointer_create((ID *)ob, &RNA_Object, ob, &object_ptr); - uiLayoutSetContextPointer(row, "object", &object_ptr); - uiItemMenuEnumO(row, C, "LOGIC_OT_sensor_add", "type", IFACE_("Add Sensor"), ICON_NONE); - - if ((ob->scaflag & OB_SHOWSENS) == 0) continue; - - uiItemS(layout); - - for (sens= ob->sensors.first; sens; sens=sens->next) { - RNA_pointer_create((ID *)ob, &RNA_Sensor, sens, &ptr); - - if ((ob->scaflag & OB_ALLSTATE) || - !(slogic->scaflag & BUTS_SENS_STATE) || - (sens->totlinks == 0) || /* always display sensor without links so that is can be edited */ - (sens->flag & SENS_PIN && slogic->scaflag & BUTS_SENS_STATE) || /* states can hide some sensors, pinned sensors ignore the visible state */ - (is_sensor_linked(block, sens)) - ) - { // gotta check if the current state is visible or not - uiLayout *split, *col; - - /* make as visible, for move operator */ - sens->flag |= SENS_VISIBLE; - - split = uiLayoutSplit(layout, 0.95f, false); - col = uiLayoutColumn(split, true); - uiLayoutSetContextPointer(col, "sensor", &ptr); - - /* should make UI template for sensor header.. function will do for now */ - draw_sensor_header(col, &ptr, &logic_ptr); - - /* draw the brick contents */ - draw_brick_sensor(col, &ptr, C); - - /* put link button to the right */ - col = uiLayoutColumn(split, false); - uiLayoutSetActive(col, RNA_boolean_get(&ptr, "active")); - but = uiDefIconBut(block, UI_BTYPE_LINK, 0, ICON_LINK, 0, 0, UI_UNIT_X, UI_UNIT_Y, NULL, 0, 0, 0, 0, ""); - if (!RNA_boolean_get(&ptr, "active")) { - UI_but_flag_enable(but, UI_BUT_SCA_LINK_GREY); - } - - /* use old-school uiButtons for links for now */ - UI_but_link_set(but, NULL, (void ***)&sens->links, &sens->totlinks, LINK_SENSOR, LINK_CONTROLLER); - } - } - } - UI_block_layout_resolve(block, NULL, &yco); /* stores final height in yco */ - height = MIN2(height, yco); - - /* ****************** Actuators ****************** */ - - xco= 40 * U.widget_unit; yco= -U.widget_unit / 2; width= 17 * U.widget_unit; - layout= UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, xco, yco, width, 20, 0, UI_style_get()); - row = uiLayoutRow(layout, true); - - uiDefBlockBut(block, actuator_menu, NULL, IFACE_("Actuators"), xco - U.widget_unit / 2, yco, 15 * U.widget_unit, UI_UNIT_Y, ""); /* replace this with uiLayout stuff later */ - - uiItemR(row, &logic_ptr, "show_actuators_selected_objects", 0, IFACE_("Sel"), ICON_NONE); - uiItemR(row, &logic_ptr, "show_actuators_active_object", 0, IFACE_("Act"), ICON_NONE); - uiItemR(row, &logic_ptr, "show_actuators_linked_controller", 0, IFACE_("Link"), ICON_NONE); - uiItemR(row, &logic_ptr, "show_actuators_active_states", 0, IFACE_("State"), ICON_NONE); - - for (a=0; ascavisflag & OB_VIS_ACT) == 0) { - continue; - } - - row = uiLayoutRow(layout, true); - uiDefButBitS(block, UI_BTYPE_TOGGLE, OB_SHOWACT, B_REDR, ob->id.name + 2, (short)(xco - U.widget_unit / 2), yco, (short)(width - 1.5f * U.widget_unit), UI_UNIT_Y, &ob->scaflag, 0, 31, 0, 0, TIP_("Object name, click to show/hide actuators")); - - RNA_pointer_create((ID *)ob, &RNA_Object, ob, &object_ptr); - uiLayoutSetContextPointer(row, "object", &object_ptr); - uiItemMenuEnumO(row, C, "LOGIC_OT_actuator_add", "type", IFACE_("Add Actuator"), ICON_NONE); - - if ((ob->scaflag & OB_SHOWACT) == 0) continue; - - uiItemS(layout); - - for (act= ob->actuators.first; act; act=act->next) { - - RNA_pointer_create((ID *)ob, &RNA_Actuator, act, &ptr); - - if ((ob->scaflag & OB_ALLSTATE) || - !(slogic->scaflag & BUTS_ACT_STATE) || - !(act->flag & ACT_LINKED) || /* always display actuators without links so that is can be edited */ - (act->flag & ACT_VISIBLE) || /* this actuator has visible connection, display it */ - (act->flag & ACT_PIN && slogic->scaflag & BUTS_ACT_STATE) /* states can hide some sensors, pinned sensors ignore the visible state */ - ) - { // gotta check if the current state is visible or not - uiLayout *split, *col; - - /* make as visible, for move operator */ - act->flag |= ACT_VISIBLE; - - split = uiLayoutSplit(layout, 0.05f, false); - - /* put inlink button to the left */ - col = uiLayoutColumn(split, false); - uiLayoutSetActive(col, RNA_boolean_get(&ptr, "active")); - but = uiDefIconBut(block, UI_BTYPE_INLINK, 0, ICON_INLINK, 0, 0, UI_UNIT_X, UI_UNIT_Y, act, LINK_ACTUATOR, 0, 0, 0, ""); - if (!RNA_boolean_get(&ptr, "active")) { - UI_but_flag_enable(but, UI_BUT_SCA_LINK_GREY); - } - - col = uiLayoutColumn(split, true); - uiLayoutSetContextPointer(col, "actuator", &ptr); - - /* should make UI template for actuator header.. function will do for now */ - draw_actuator_header(col, &ptr, &logic_ptr); - - /* draw the brick contents */ - draw_brick_actuator(col, &ptr, C); - - } - } - } - UI_block_layout_resolve(block, NULL, &yco); /* stores final height in yco */ - height = MIN2(height, yco); - - UI_view2d_totRect_set(&ar->v2d, 57.5f * U.widget_unit, height - U.widget_unit); - - /* set the view */ - UI_view2d_view_ortho(&ar->v2d); - - UI_block_links_compose(block); - - UI_block_end(C, block); - UI_block_draw(C, block); - - /* restore view matrix */ - UI_view2d_view_restore(C); - - if (idar) MEM_freeN(idar); -} - diff --git a/source/blender/editors/space_logic/space_logic.c b/source/blender/editors/space_logic/space_logic.c deleted file mode 100644 index af90ef487e0..00000000000 --- a/source/blender/editors/space_logic/space_logic.c +++ /dev/null @@ -1,377 +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) 2009 Blender Foundation. - * All rights reserved. - * - * - * Contributor(s): Blender Foundation - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file blender/editors/space_logic/space_logic.c - * \ingroup splogic - */ - - -#include -#include - - -#include "MEM_guardedalloc.h" - -#include "BLI_blenlib.h" -#include "BLI_utildefines.h" - -#include "DNA_gpencil_types.h" - -#include "BKE_context.h" -#include "BKE_library.h" -#include "BKE_screen.h" - -#include "ED_space_api.h" -#include "ED_screen.h" - -#include "BIF_gl.h" - - -#include "WM_api.h" -#include "WM_types.h" - -#include "UI_resources.h" -#include "UI_view2d.h" - -#include "logic_intern.h" - -/* ******************** manage regions ********************* */ - -ARegion *logic_has_buttons_region(ScrArea *sa) -{ - ARegion *ar, *arnew; - - ar = BKE_area_find_region_type(sa, RGN_TYPE_UI); - if (ar) return ar; - - /* add subdiv level; after header */ - ar = BKE_area_find_region_type(sa, RGN_TYPE_HEADER); - - /* is error! */ - if (ar == NULL) return NULL; - - arnew= MEM_callocN(sizeof(ARegion), "buttons for image"); - - BLI_insertlinkafter(&sa->regionbase, ar, arnew); - arnew->regiontype = RGN_TYPE_UI; - arnew->alignment = RGN_ALIGN_RIGHT; - - arnew->flag = RGN_FLAG_HIDDEN; - - return arnew; -} - -/* ******************** default callbacks for image space ***************** */ - -static SpaceLink *logic_new(const bContext *C) -{ - ScrArea *sa= CTX_wm_area(C); - ARegion *ar; - SpaceLogic *slogic; - - slogic= MEM_callocN(sizeof(SpaceLogic), "initlogic"); - slogic->spacetype= SPACE_LOGIC; - - /* default options */ - slogic->scaflag = ((BUTS_SENS_SEL|BUTS_SENS_ACT|BUTS_SENS_LINK) | - (BUTS_CONT_SEL|BUTS_CONT_ACT|BUTS_CONT_LINK) | - (BUTS_ACT_SEL|BUTS_ACT_ACT|BUTS_ACT_LINK) | - (BUTS_SENS_STATE|BUTS_ACT_STATE)); - - - /* header */ - ar= MEM_callocN(sizeof(ARegion), "header for logic"); - - BLI_addtail(&slogic->regionbase, ar); - ar->regiontype= RGN_TYPE_HEADER; - ar->alignment= RGN_ALIGN_BOTTOM; - - /* buttons/list view */ - ar= MEM_callocN(sizeof(ARegion), "buttons for logic"); - - BLI_addtail(&slogic->regionbase, ar); - ar->regiontype= RGN_TYPE_UI; - ar->alignment= RGN_ALIGN_RIGHT; - - /* main region */ - ar= MEM_callocN(sizeof(ARegion), "main region for logic"); - - BLI_addtail(&slogic->regionbase, ar); - ar->regiontype= RGN_TYPE_WINDOW; - - ar->v2d.tot.xmin = 0.0f; - ar->v2d.tot.ymax = 0.0f; - ar->v2d.tot.xmax = 1150.0f; - ar->v2d.tot.ymin = ( 1150.0f/(float)sa->winx ) * (float)-sa->winy; - - ar->v2d.cur = ar->v2d.tot; - - ar->v2d.min[0] = 1.0f; - ar->v2d.min[1] = 1.0f; - - ar->v2d.max[0] = 32000.0f; - ar->v2d.max[1] = 32000.0f; - - ar->v2d.minzoom = 0.5f; - ar->v2d.maxzoom = 1.5f; - - ar->v2d.scroll = (V2D_SCROLL_RIGHT | V2D_SCROLL_BOTTOM); - ar->v2d.keepzoom = V2D_KEEPZOOM | V2D_LIMITZOOM | V2D_KEEPASPECT; - ar->v2d.keeptot = V2D_KEEPTOT_BOUNDS; - ar->v2d.align = V2D_ALIGN_NO_POS_Y | V2D_ALIGN_NO_NEG_X; - ar->v2d.keepofs = V2D_KEEPOFS_Y; - - return (SpaceLink *)slogic; -} - -/* not spacelink itself */ -static void logic_free(SpaceLink *UNUSED(sl)) -{ -// Spacelogic *slogic= (SpaceLogic *) sl; - -// if (slogic->gpd) -// XXX BKE_gpencil_free(slogic->gpd); - -} - - -/* spacetype; init callback */ -static void logic_init(struct wmWindowManager *UNUSED(wm), ScrArea *UNUSED(sa)) -{ - -} - -static SpaceLink *logic_duplicate(SpaceLink *sl) -{ - SpaceLogic *slogicn= MEM_dupallocN(sl); - - return (SpaceLink *)slogicn; -} - -static void logic_operatortypes(void) -{ - WM_operatortype_append(LOGIC_OT_properties); - WM_operatortype_append(LOGIC_OT_links_cut); -} - -static void logic_keymap(struct wmKeyConfig *keyconf) -{ - wmKeyMap *keymap = WM_keymap_find(keyconf, "Logic Editor", SPACE_LOGIC, 0); - - WM_keymap_add_item(keymap, "LOGIC_OT_properties", NKEY, KM_PRESS, 0, 0); - WM_keymap_add_item(keymap, "LOGIC_OT_links_cut", LEFTMOUSE, KM_PRESS, KM_CTRL, 0); - WM_keymap_add_menu(keymap, "LOGIC_MT_logicbricks_add", AKEY, KM_PRESS, KM_SHIFT, 0); - - WM_keymap_add_item(keymap, "LOGIC_OT_view_all", HOMEKEY, KM_PRESS, 0, 0); -#ifdef WITH_INPUT_NDOF - WM_keymap_add_item(keymap, "LOGIC_OT_view_all", NDOF_BUTTON_FIT, KM_PRESS, 0, 0); -#endif -} - -static void logic_refresh(const bContext *UNUSED(C), ScrArea *UNUSED(sa)) -{ -// SpaceLogic *slogic= CTX_wm_space_logic(C); -// Object *obedit= CTX_data_edit_object(C); - -} - -static void logic_listener( - bScreen *UNUSED(sc), ScrArea *UNUSED(sa), ARegion *ar, - wmNotifier *wmn, const Scene *UNUSED(scene)) -{ - /* context changes */ - switch (wmn->category) { - case NC_LOGIC: - ED_region_tag_redraw(ar); - break; - case NC_SCENE: - switch (wmn->data) { - case ND_FRAME: - ED_region_tag_redraw(ar); - break; - - case ND_OB_ACTIVE: - ED_region_tag_redraw(ar); - break; - } - break; - case NC_OBJECT: - break; - case NC_ID: - if (wmn->action == NA_RENAME) - ED_region_tag_redraw(ar); - break; - } -} - -static int logic_context(const bContext *UNUSED(C), const char *UNUSED(member), bContextDataResult *UNUSED(result)) -{ -// SpaceLogic *slogic= CTX_wm_space_logic(C); - return 0; -} - -/************************** main region ***************************/ - - -/* add handlers, stuff you only do once or on area/region changes */ -static void logic_main_region_init(wmWindowManager *wm, ARegion *ar) -{ - wmKeyMap *keymap; - - UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_CUSTOM, ar->winx, ar->winy); - - /* own keymaps */ - keymap = WM_keymap_find(wm->defaultconf, "Logic Editor", SPACE_LOGIC, 0); - WM_event_add_keymap_handler(&ar->handlers, keymap); -} - -static void logic_main_region_draw(const bContext *C, ARegion *ar) -{ - /* draw entirely, view changes should be handled here */ -// SpaceLogic *slogic= CTX_wm_space_logic(C); - View2D *v2d= &ar->v2d; - View2DScrollers *scrollers; - - /* clear and setup matrix */ - UI_ThemeClearColor(TH_BACK); - glClear(GL_COLOR_BUFFER_BIT); - - UI_view2d_view_ortho(v2d); - - logic_buttons((bContext *)C, ar); - - /* reset view matrix */ - UI_view2d_view_restore(C); - - /* scrollers */ - scrollers= UI_view2d_scrollers_calc(C, v2d, V2D_ARG_DUMMY, V2D_ARG_DUMMY, V2D_ARG_DUMMY, V2D_ARG_DUMMY); - UI_view2d_scrollers_draw(C, v2d, scrollers); - UI_view2d_scrollers_free(scrollers); - -} - - -/* *********************** buttons region ************************ */ - -/* add handlers, stuff you only do once or on area/region changes */ -static void logic_buttons_region_init(wmWindowManager *wm, ARegion *ar) -{ - wmKeyMap *keymap; - - ED_region_panels_init(wm, ar); - - keymap = WM_keymap_find(wm->defaultconf, "Logic Editor", SPACE_LOGIC, 0); - WM_event_add_keymap_handler(&ar->handlers, keymap); -} - -static void logic_buttons_region_draw(const bContext *C, ARegion *ar) -{ - ED_region_panels(C, ar, NULL, -1, true); -} - -/************************* header region **************************/ - -/* add handlers, stuff you only do once or on area/region changes */ -static void logic_header_region_init(wmWindowManager *UNUSED(wm), ARegion *ar) -{ - ED_region_header_init(ar); -} - -static void logic_header_region_draw(const bContext *C, ARegion *ar) -{ - ED_region_header(C, ar); -} - -/**************************** spacetype *****************************/ - -static void logic_id_remap(ScrArea *UNUSED(sa), SpaceLink *slink, ID *old_id, ID *new_id) -{ - SpaceLogic *slog = (SpaceLogic *)slink; - - if (!ELEM(GS(old_id->name), ID_GD)) { - return; - } - - if ((ID *)slog->gpd == old_id) { - slog->gpd = (bGPdata *)new_id; - id_us_min(old_id); - id_us_plus(new_id); - } -} - -/* only called once, from space/spacetypes.c */ -void ED_spacetype_logic(void) -{ - SpaceType *st = MEM_callocN(sizeof(SpaceType), "spacetype logic"); - ARegionType *art; - - st->spaceid = SPACE_LOGIC; - strncpy(st->name, "Logic", BKE_ST_MAXNAME); - - st->new = logic_new; - st->free = logic_free; - st->init = logic_init; - st->duplicate = logic_duplicate; - st->operatortypes = logic_operatortypes; - st->keymap = logic_keymap; - st->refresh = logic_refresh; - st->context = logic_context; - st->id_remap = logic_id_remap; - - /* regions: main window */ - art = MEM_callocN(sizeof(ARegionType), "spacetype logic region"); - art->regionid = RGN_TYPE_WINDOW; - art->keymapflag = ED_KEYMAP_UI | ED_KEYMAP_FRAMES | ED_KEYMAP_VIEW2D; - art->init = logic_main_region_init; - art->draw = logic_main_region_draw; - art->listener = logic_listener; - - BLI_addhead(&st->regiontypes, art); - - /* regions: listview/buttons */ - art = MEM_callocN(sizeof(ARegionType), "spacetype logic region"); - art->regionid = RGN_TYPE_UI; - art->prefsizex= 220; // XXX - art->keymapflag = ED_KEYMAP_UI | ED_KEYMAP_FRAMES; - art->listener = logic_listener; - art->init = logic_buttons_region_init; - art->draw = logic_buttons_region_draw; - BLI_addhead(&st->regiontypes, art); - - /* regions: header */ - art= MEM_callocN(sizeof(ARegionType), "spacetype logic region"); - art->regionid = RGN_TYPE_HEADER; - art->prefsizey = HEADERY; - art->keymapflag = ED_KEYMAP_UI | ED_KEYMAP_VIEW2D | ED_KEYMAP_FRAMES | ED_KEYMAP_HEADER; - art->init = logic_header_region_init; - art->draw = logic_header_region_draw; - - BLI_addhead(&st->regiontypes, art); - - BKE_spacetype_register(st); -} - - diff --git a/source/blender/editors/space_view3d/CMakeLists.txt b/source/blender/editors/space_view3d/CMakeLists.txt index d148ef3c6fe..d027729c7a7 100644 --- a/source/blender/editors/space_view3d/CMakeLists.txt +++ b/source/blender/editors/space_view3d/CMakeLists.txt @@ -84,13 +84,6 @@ if(WITH_PYTHON) add_definitions(-DWITH_PYTHON) endif() -if(WITH_GAMEENGINE) - list(APPEND INC - ../../../gameengine/BlenderRoutines - ) - add_definitions(-DWITH_GAMEENGINE) -endif() - add_definitions(${GL_DEFINITIONS}) if(WITH_INTERNATIONAL) diff --git a/source/blender/editors/space_view3d/drawmesh.c b/source/blender/editors/space_view3d/drawmesh.c index 0d4ec4d42d1..2b3678c4812 100644 --- a/source/blender/editors/space_view3d/drawmesh.c +++ b/source/blender/editors/space_view3d/drawmesh.c @@ -41,7 +41,6 @@ #include "DNA_meshdata_types.h" #include "DNA_node_types.h" #include "DNA_object_types.h" -#include "DNA_property_types.h" #include "DNA_scene_types.h" #include "DNA_screen_types.h" #include "DNA_view3d_types.h" @@ -51,7 +50,6 @@ #include "BKE_image.h" #include "BKE_material.h" #include "BKE_paint.h" -#include "BKE_property.h" #include "BKE_editmesh.h" #include "BKE_scene.h" diff --git a/source/blender/editors/space_view3d/drawobject.c b/source/blender/editors/space_view3d/drawobject.c index 287613c847b..1d54a1937eb 100644 --- a/source/blender/editors/space_view3d/drawobject.c +++ b/source/blender/editors/space_view3d/drawobject.c @@ -328,7 +328,7 @@ bool draw_glsl_material(Scene *scene, ViewLayer *view_layer, Object *ob, View3D return true; if (v3d->drawtype == OB_TEXTURE) - return (scene->gm.matmode == GAME_MAT_GLSL && !BKE_scene_use_new_shading_nodes(scene)); + return !BKE_scene_use_new_shading_nodes(scene); else if (v3d->drawtype == OB_MATERIAL && dt > OB_SOLID) return true; else @@ -1189,51 +1189,6 @@ static void draw_transp_spot_volume(Lamp *la, float x, float z, unsigned pos) glDisable(GL_CULL_FACE); } -#ifdef WITH_GAMEENGINE -static void draw_transp_sun_volume(Lamp *la, unsigned pos) -{ - float box[8][3]; - - /* construct box */ - box[0][0] = box[1][0] = box[2][0] = box[3][0] = -la->shadow_frustum_size; - box[4][0] = box[5][0] = box[6][0] = box[7][0] = +la->shadow_frustum_size; - box[0][1] = box[1][1] = box[4][1] = box[5][1] = -la->shadow_frustum_size; - box[2][1] = box[3][1] = box[6][1] = box[7][1] = +la->shadow_frustum_size; - box[0][2] = box[3][2] = box[4][2] = box[7][2] = -la->clipend; - box[1][2] = box[2][2] = box[5][2] = box[6][2] = -la->clipsta; - - /* draw edges */ - imm_draw_box(box, false, pos); - - /* draw faces */ - glEnable(GL_CULL_FACE); - glEnable(GL_BLEND); - glDepthMask(GL_FALSE); - - /* draw backside darkening */ - glCullFace(GL_FRONT); - - glBlendFunc(GL_ZERO, GL_SRC_ALPHA); - immUniformColor4f(0.0f, 0.0f, 0.0f, 0.4f); - - imm_draw_box(box, true, pos); - - /* draw front side lighting */ - glCullFace(GL_BACK); - - glBlendFunc(GL_ONE, GL_ONE); - immUniformColor3f(0.2f, 0.2f, 0.2f); - - imm_draw_box(box, true, pos); - - /* restore state */ - glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); - glDisable(GL_BLEND); - glDepthMask(GL_TRUE); - glDisable(GL_CULL_FACE); -} -#endif - void drawlamp(View3D *v3d, RegionView3D *rv3d, Base *base, const char dt, const short dflag, const unsigned char ob_wire_col[4], const bool is_obact) { @@ -1253,22 +1208,7 @@ void drawlamp(View3D *v3d, RegionView3D *rv3d, Base *base, !(base->flag_legacy & OB_FROMDUPLI) && !is_view); -#ifdef WITH_GAMEENGINE - const bool drawshadowbox = ( - (rv3d->rflag & RV3D_IS_GAME_ENGINE) && - (dt > OB_WIRE) && - !(G.f & G_PICKSEL) && - (la->type == LA_SUN) && - ((la->mode & LA_SHAD_BUF) || - (la->mode & LA_SHAD_RAY)) && - (la->mode & LA_SHOW_SHADOW_BOX) && - !(base->flag_legacy & OB_FROMDUPLI) && - !is_view); -#else - const bool drawshadowbox = false; -#endif - - if ((drawcone || drawshadowbox) && !v3d->transp) { + if (drawcone && !v3d->transp) { /* in this case we need to draw delayed */ ED_view3d_after_add(&v3d->afterdraw_transp, base, dflag); return; @@ -1576,11 +1516,6 @@ void drawlamp(View3D *v3d, RegionView3D *rv3d, Base *base, } } -#ifdef WITH_GAMEENGINE - if (drawshadowbox) { - draw_transp_sun_volume(la, pos); - } -#endif } else if (la->type == LA_AREA) { setlinestyle(3); @@ -4300,11 +4235,7 @@ static void draw_mesh_fancy( Depsgraph *depsgraph, Scene *scene, ViewLayer *view_layer, ARegion *ar, View3D *v3d, RegionView3D *rv3d, Base *base, const char dt, const unsigned char ob_wire_col[4], const short dflag) { -#ifdef WITH_GAMEENGINE - Object *ob = (rv3d->rflag & RV3D_IS_GAME_ENGINE) ? BKE_object_lod_meshob_get(base->object, view_layer) : base->object; -#else Object *ob = base->object; -#endif Mesh *me = ob->data; eWireDrawMode draw_wire = OBDRAW_WIRE_OFF; bool /* no_verts,*/ no_edges, no_faces; @@ -4718,11 +4649,7 @@ static void draw_mesh_fancy_new( return; } -#ifdef WITH_GAMEENGINE - Object *ob = (rv3d->rflag & RV3D_IS_GAME_ENGINE) ? BKE_object_lod_meshob_get(base->object, view_layer) : base->object; -#else Object *ob = base->object; -#endif Mesh *me = ob->data; eWireDrawMode draw_wire = OBDRAW_WIRE_OFF; /* could be bool draw_wire_overlay */ bool no_edges, no_faces; @@ -8177,33 +8104,7 @@ void draw_bounding_volume(Object *ob, char type, const unsigned char ob_wire_col if (bb == NULL) return; - if (ob->gameflag & OB_BOUNDS) { /* bounds need to be drawn around origin for game engine */ - - if (type == OB_BOUND_BOX) { - float vec[8][3], size[3]; - - unsigned int pos = GWN_vertformat_attr_add(immVertexFormat(), "pos", GWN_COMP_F32, 3, GWN_FETCH_FLOAT); - immBindBuiltinProgram(GPU_SHADER_3D_UNIFORM_COLOR); - if (ob_wire_col) immUniformColor3ubv(ob_wire_col); - - BKE_boundbox_calc_size_aabb(bb, size); - - vec[0][0] = vec[1][0] = vec[2][0] = vec[3][0] = -size[0]; - vec[4][0] = vec[5][0] = vec[6][0] = vec[7][0] = +size[0]; - vec[0][1] = vec[1][1] = vec[4][1] = vec[5][1] = -size[1]; - vec[2][1] = vec[3][1] = vec[6][1] = vec[7][1] = +size[1]; - vec[0][2] = vec[3][2] = vec[4][2] = vec[7][2] = -size[2]; - vec[1][2] = vec[2][2] = vec[5][2] = vec[6][2] = +size[2]; - - imm_draw_box(vec, false, pos); - - immUnbindProgram(); - } - else { - imm_draw_bb(bb, type, true, ob_wire_col); - } - } - else { + { if (type == OB_BOUND_BOX) { unsigned int pos = GWN_vertformat_attr_add(immVertexFormat(), "pos", GWN_COMP_F32, 3, GWN_FETCH_FLOAT); immBindBuiltinProgram(GPU_SHADER_3D_UNIFORM_COLOR); @@ -8384,48 +8285,6 @@ static void draw_hooks(Object *ob, unsigned int pos) } } -static void draw_rigid_body_pivot(bRigidBodyJointConstraint *data, - const short dflag, const unsigned char ob_wire_col[4]) -{ - const char *axis_str[3] = {"px", "py", "pz"}; - float mat[4][4]; - - unsigned int pos = GWN_vertformat_attr_add(immVertexFormat(), "pos", GWN_COMP_F32, 3, GWN_FETCH_FLOAT); - immBindBuiltinProgram(GPU_SHADER_3D_UNIFORM_COLOR); - - if (ob_wire_col) immUniformColor3ubv(ob_wire_col); - - eul_to_mat4(mat, &data->axX); - glLineWidth(4.0f); - setlinestyle(2); - - immBegin(GWN_PRIM_LINES, 6); - for (int axis = 0; axis < 3; axis++) { - float dir[3] = {0, 0, 0}; - float v[3]; - - copy_v3_v3(v, &data->pivX); - - dir[axis] = 1.0f; - mul_m4_v3(mat, dir); - add_v3_v3(v, dir); - immVertex3fv(pos, &data->pivX); - immVertex3fv(pos, v); - - /* when const color is set wirecolor is NULL - we could get the current color but - * with selection and group instancing its not needed to draw the text */ - if ((dflag & DRAW_CONSTCOLOR) == 0) { - view3d_cached_text_draw_add(v, axis_str[axis], 2, 0, V3D_CACHE_TEXT_ASCII, ob_wire_col); - } - } - immEnd(); - - setlinestyle(0); - glLineWidth(1.0f); - - immUnbindProgram(); -} - void draw_object_wire_color(ViewLayer *view_layer, Base *base, unsigned char r_ob_wire_col[4]) { Object *ob = base->object; @@ -9059,23 +8918,6 @@ afterdraw: } if (!render_override) { - bConstraint *con; - - for (con = ob->constraints.first; con; con = con->next) { - if (con->type == CONSTRAINT_TYPE_RIGIDBODYJOINT) { - bRigidBodyJointConstraint *data = (bRigidBodyJointConstraint *)con->data; - if (data->flag & CONSTRAINT_DRAW_PIVOT) - draw_rigid_body_pivot(data, dflag, ob_wire_col); - } - } - - if ((ob->gameflag & OB_BOUNDS) && (ob->mode == OB_MODE_OBJECT)) { - if (ob->boundtype != ob->collision_boundtype || (dtx & OB_DRAWBOUNDOX) == 0) { - setlinestyle(2); - draw_bounding_volume(ob, ob->collision_boundtype, ob_wire_col); - setlinestyle(0); - } - } if (ob->rigidbody_object) { draw_rigidbody_shape(ob, ob_wire_col); } @@ -9120,33 +8962,6 @@ afterdraw: } } - if ((dt <= OB_SOLID) && !render_override) { - if (((ob->gameflag & OB_DYNAMIC) && - ((ob->gameflag & OB_BOUNDS) == 0)) || - - ((ob->gameflag & OB_BOUNDS) && - (ob->collision_boundtype == OB_BOUND_SPHERE))) - { - float imat[4][4], vec[3] = {0.0f, 0.0f, 0.0f}; - - unsigned int pos = GWN_vertformat_attr_add(immVertexFormat(), "pos", GWN_COMP_F32, 3, GWN_FETCH_FLOAT); - immBindBuiltinProgram(GPU_SHADER_3D_UNIFORM_COLOR); - - invert_m4_m4(imat, rv3d->viewmatob); - - if ((dflag & DRAW_CONSTCOLOR) == 0) { - /* prevent random colors being used */ - immUniformColor3ubv(ob_wire_col); - } - - setlinestyle(2); - imm_drawcircball(vec, ob->inertia, imat, pos); - setlinestyle(0); - - immUnbindProgram(); - } - } - /* return warning, this is cached text draw */ invert_m4_m4(ob->imat, ob->obmat); view3d_cached_text_draw_end(v3d, ar, 1); diff --git a/source/blender/editors/space_view3d/view3d_draw_legacy.c b/source/blender/editors/space_view3d/view3d_draw_legacy.c index dcdcf95bf86..807a4f212f6 100644 --- a/source/blender/editors/space_view3d/view3d_draw_legacy.c +++ b/source/blender/editors/space_view3d/view3d_draw_legacy.c @@ -990,12 +990,6 @@ static void draw_dupli_objects_color( /* Make sure lod is updated from dupli's position */ savedlod = dob->ob->currentlod; -#ifdef WITH_GAMEENGINE - if (rv3d->rflag & RV3D_IS_GAME_ENGINE) { - BKE_object_lod_update(dob->ob, rv3d->viewinv[3]); - } -#endif - /* extra service: draw the duplicator in drawtype of parent, minimum taken * to allow e.g. boundbox box objects in groups for LOD */ dt = tbase.object->dt; @@ -1467,9 +1461,7 @@ CustomDataMask ED_view3d_datamask(const Scene *scene, const View3D *v3d) mask |= CD_MASK_ORCO; } else { - if ((scene->gm.matmode == GAME_MAT_GLSL && drawtype == OB_TEXTURE) || - (drawtype == OB_MATERIAL)) - { + if (drawtype == OB_MATERIAL) { mask |= CD_MASK_ORCO; } } @@ -1925,19 +1917,6 @@ static void view3d_main_region_draw_engine_info(View3D *v3d, RegionView3D *rv3d, ED_region_info_draw(ar, rv3d->render_engine->text, fill_color, true); } -#ifdef WITH_GAMEENGINE -static void update_lods(Scene *scene, float camera_pos[3]) -{ - Scene *sce_iter; - Base *base; - - for (SETLOOPER(scene, sce_iter, base)) { - Object *ob = base->object; - BKE_object_lod_update(ob, camera_pos); - } -} -#endif - static void view3d_main_region_draw_objects(const bContext *C, Scene *scene, ViewLayer *view_layer, View3D *v3d, ARegion *ar, const char **grid_unit) { @@ -1964,16 +1943,6 @@ static void view3d_main_region_draw_objects(const bContext *C, Scene *scene, Vie VP_legacy_view3d_main_region_setup_view(depsgraph, scene, v3d, ar, NULL, NULL); } - rv3d->rflag &= ~RV3D_IS_GAME_ENGINE; -#ifdef WITH_GAMEENGINE - if (STREQ(scene->view_render.engine_id, RE_engine_id_BLENDER_GAME)) { - rv3d->rflag |= RV3D_IS_GAME_ENGINE; - - /* Make sure LoDs are up to date */ - update_lods(scene, rv3d->viewinv[3]); - } -#endif - /* main drawing call */ view3d_draw_objects(C, depsgraph, scene, v3d, ar, grid_unit, true, false); diff --git a/source/blender/editors/space_view3d/view3d_intern.h b/source/blender/editors/space_view3d/view3d_intern.h index 4b005185638..64927ff55c7 100644 --- a/source/blender/editors/space_view3d/view3d_intern.h +++ b/source/blender/editors/space_view3d/view3d_intern.h @@ -251,8 +251,6 @@ void VIEW3D_OT_smoothview(struct wmOperatorType *ot); void VIEW3D_OT_camera_to_view(struct wmOperatorType *ot); void VIEW3D_OT_camera_to_view_selected(struct wmOperatorType *ot); void VIEW3D_OT_object_as_camera(struct wmOperatorType *ot); -void VIEW3D_OT_game_start(struct wmOperatorType *ot); - bool ED_view3d_boundbox_clip_ex(const RegionView3D *rv3d, const struct BoundBox *bb, float obmat[4][4]); bool ED_view3d_boundbox_clip(RegionView3D *rv3d, const struct BoundBox *bb); diff --git a/source/blender/editors/space_view3d/view3d_ops.c b/source/blender/editors/space_view3d/view3d_ops.c index 8e6f5228b09..0274ddd82fc 100644 --- a/source/blender/editors/space_view3d/view3d_ops.c +++ b/source/blender/editors/space_view3d/view3d_ops.c @@ -203,7 +203,6 @@ void view3d_operatortypes(void) WM_operatortype_append(VIEW3D_OT_camera_to_view); WM_operatortype_append(VIEW3D_OT_camera_to_view_selected); WM_operatortype_append(VIEW3D_OT_object_as_camera); - WM_operatortype_append(VIEW3D_OT_game_start); WM_operatortype_append(VIEW3D_OT_fly); WM_operatortype_append(VIEW3D_OT_walk); WM_operatortype_append(VIEW3D_OT_navigate); diff --git a/source/blender/editors/space_view3d/view3d_view.c b/source/blender/editors/space_view3d/view3d_view.c index 1d44f3d3fd5..b6ea68c8fe4 100644 --- a/source/blender/editors/space_view3d/view3d_view.c +++ b/source/blender/editors/space_view3d/view3d_view.c @@ -64,15 +64,6 @@ #include "DEG_depsgraph_query.h" -#ifdef WITH_GAMEENGINE -# include "BLI_listbase.h" -# include "BLI_callbacks.h" - -# include "GPU_draw.h" - -# include "BL_System.h" -#endif - #include "view3d_intern.h" /* own include */ /* -------------------------------------------------------------------- */ @@ -1090,213 +1081,3 @@ int ED_view3d_view_layer_set(int lay, const int *values, int *active) } /** \} */ - -/* -------------------------------------------------------------------- */ -/** \name Game Engine Operator - * - * Start the game engine (handles context switching). - * \{ */ - -#ifdef WITH_GAMEENGINE - -static ListBase queue_back; -static void game_engine_save_state(bContext *C, wmWindow *win) -{ - Object *obact = CTX_data_active_object(C); - - glPushAttrib(GL_ALL_ATTRIB_BITS); - - if (obact && obact->mode & OB_MODE_TEXTURE_PAINT) { - GPU_paint_set_mipmap(1); - } - - queue_back = win->queue; - - BLI_listbase_clear(&win->queue); -} - -static void game_engine_restore_state(bContext *C, wmWindow *win) -{ - Object *obact = CTX_data_active_object(C); - - if (obact && obact->mode & OB_MODE_TEXTURE_PAINT) { - GPU_paint_set_mipmap(0); - } - /* check because closing win can set to NULL */ - if (win) { - win->queue = queue_back; - } - - GPU_state_init(); - - glPopAttrib(); -} - -/* was space_set_commmandline_options in 2.4x */ -static void game_set_commmandline_options(GameData *gm) -{ - SYS_SystemHandle syshandle; - int test; - - if ((syshandle = SYS_GetSystem())) { - /* User defined settings */ - test = (U.gameflags & USER_DISABLE_MIPMAP); - GPU_set_mipmap(!test); - SYS_WriteCommandLineInt(syshandle, "nomipmap", test); - - /* File specific settings: */ - /* Only test the first one. These two are switched - * simultaneously. */ - test = (gm->flag & GAME_SHOW_FRAMERATE); - SYS_WriteCommandLineInt(syshandle, "show_framerate", test); - SYS_WriteCommandLineInt(syshandle, "show_profile", test); - - test = (gm->flag & GAME_SHOW_DEBUG_PROPS); - SYS_WriteCommandLineInt(syshandle, "show_properties", test); - - test = (gm->flag & GAME_SHOW_PHYSICS); - SYS_WriteCommandLineInt(syshandle, "show_physics", test); - - test = (gm->flag & GAME_ENABLE_ALL_FRAMES); - SYS_WriteCommandLineInt(syshandle, "fixedtime", test); - - test = (gm->flag & GAME_ENABLE_ANIMATION_RECORD); - SYS_WriteCommandLineInt(syshandle, "animation_record", test); - - test = (gm->flag & GAME_IGNORE_DEPRECATION_WARNINGS); - SYS_WriteCommandLineInt(syshandle, "ignore_deprecation_warnings", test); - - test = (gm->matmode == GAME_MAT_MULTITEX); - SYS_WriteCommandLineInt(syshandle, "blender_material", test); - test = (gm->matmode == GAME_MAT_GLSL); - SYS_WriteCommandLineInt(syshandle, "blender_glsl_material", test); - } -} - -#endif /* WITH_GAMEENGINE */ - -static int game_engine_poll(bContext *C) -{ - const wmWindow *win = CTX_wm_window(C); - const Scene *scene = WM_window_get_active_scene(win); - - /* we need a context and area to launch BGE - * it's a temporary solution to avoid crash at load time - * if we try to auto run the BGE. Ideally we want the - * context to be set as soon as we load the file. */ - - if (win == NULL) return 0; - if (CTX_wm_screen(C) == NULL) return 0; - - if (CTX_data_mode_enum(C) != CTX_MODE_OBJECT) - return 0; - - if (!BKE_scene_uses_blender_game(scene)) - return 0; - - return 1; -} - -static int game_engine_exec(bContext *C, wmOperator *op) -{ -#ifdef WITH_GAMEENGINE - Scene *startscene = CTX_data_scene(C); - Main *bmain = CTX_data_main(C); - ScrArea /* *sa, */ /* UNUSED */ *prevsa = CTX_wm_area(C); - ARegion *ar, *prevar = CTX_wm_region(C); - wmWindow *prevwin = CTX_wm_window(C); - RegionView3D *rv3d; - rcti cam_frame; - - UNUSED_VARS(op); - - /* bad context switch .. */ - if (!ED_view3d_context_activate(C)) - return OPERATOR_CANCELLED; - - /* redraw to hide any menus/popups, we don't go back to - * the window manager until after this operator exits */ - WM_redraw_windows(C); - - BLI_callback_exec(bmain, &startscene->id, BLI_CB_EVT_GAME_PRE); - - rv3d = CTX_wm_region_view3d(C); - /* sa = CTX_wm_area(C); */ /* UNUSED */ - ar = CTX_wm_region(C); - - view3d_operator_needs_opengl(C); - - game_set_commmandline_options(&startscene->gm); - - if ((rv3d->persp == RV3D_CAMOB) && - (startscene->gm.framing.type == SCE_GAMEFRAMING_BARS) && - (startscene->gm.stereoflag != STEREO_DOME)) - { - Depsgraph *depsgraph = CTX_data_depsgraph(C); - /* Letterbox */ - rctf cam_framef; - ED_view3d_calc_camera_border(startscene, depsgraph, ar, CTX_wm_view3d(C), rv3d, &cam_framef, false); - cam_frame.xmin = cam_framef.xmin + ar->winrct.xmin; - cam_frame.xmax = cam_framef.xmax + ar->winrct.xmin; - cam_frame.ymin = cam_framef.ymin + ar->winrct.ymin; - cam_frame.ymax = cam_framef.ymax + ar->winrct.ymin; - BLI_rcti_isect(&ar->winrct, &cam_frame, &cam_frame); - } - else { - cam_frame.xmin = ar->winrct.xmin; - cam_frame.xmax = ar->winrct.xmax; - cam_frame.ymin = ar->winrct.ymin; - cam_frame.ymax = ar->winrct.ymax; - } - - - game_engine_save_state(C, prevwin); - - StartKetsjiShell(C, ar, &cam_frame, 1); - - /* window wasnt closed while the BGE was running */ - if (BLI_findindex(&CTX_wm_manager(C)->windows, prevwin) == -1) { - prevwin = NULL; - CTX_wm_window_set(C, NULL); - } - - ED_area_tag_redraw(CTX_wm_area(C)); - - if (prevwin) { - /* restore context, in case it changed in the meantime, for - * example by working in another window or closing it */ - CTX_wm_region_set(C, prevar); - CTX_wm_window_set(C, prevwin); - CTX_wm_area_set(C, prevsa); - } - - game_engine_restore_state(C, prevwin); - - //XXX restore_all_scene_cfra(scene_cfra_store); - BKE_scene_set_background(CTX_data_main(C), startscene); - //XXX BKE_scene_graph_update_for_newframe(depsgraph, bmain); - - BLI_callback_exec(bmain, &startscene->id, BLI_CB_EVT_GAME_POST); - - return OPERATOR_FINISHED; -#else - UNUSED_VARS(C); - BKE_report(op->reports, RPT_ERROR, "Game engine is disabled in this build"); - return OPERATOR_CANCELLED; -#endif -} - -void VIEW3D_OT_game_start(wmOperatorType *ot) -{ - /* identifiers */ - ot->name = "Start Game Engine"; - ot->description = "Start game engine"; - ot->idname = "VIEW3D_OT_game_start"; - - /* api callbacks */ - ot->exec = game_engine_exec; - - ot->poll = game_engine_poll; -} - -/** \} */ diff --git a/source/blender/gpu/CMakeLists.txt b/source/blender/gpu/CMakeLists.txt index e3fb67261bb..94b27c8f916 100644 --- a/source/blender/gpu/CMakeLists.txt +++ b/source/blender/gpu/CMakeLists.txt @@ -234,10 +234,6 @@ data_to_c_simple(shaders/gpu_shader_vertex_world.glsl SRC) data_to_c_simple(shaders/gpu_shader_vsm_store_frag.glsl SRC) data_to_c_simple(shaders/gpu_shader_vsm_store_vert.glsl SRC) -if(WITH_GAMEENGINE) - add_definitions(-DWITH_GAMEENGINE) -endif() - if(WITH_MOD_SMOKE) add_definitions(-DWITH_SMOKE) endif() diff --git a/source/blender/gpu/GPU_draw.h b/source/blender/gpu/GPU_draw.h index 9bbf46b2a1f..4598ac974c8 100644 --- a/source/blender/gpu/GPU_draw.h +++ b/source/blender/gpu/GPU_draw.h @@ -49,15 +49,12 @@ struct DupliObject; #include "DNA_object_enums.h" -/* OpenGL drawing functions related to shading. These are also - * shared with the game engine, where there were previously - * duplicates of some of these functions. */ +/* OpenGL drawing functions related to shading. */ /* Initialize * - sets the default Blender opengl state, if in doubt, check * the contents of this function - * - this is called when starting Blender, for opengl rendering, - * and for switching back from the game engine for example. */ + * - this is called when starting Blender, for opengl rendering. */ void GPU_state_init(void); @@ -103,14 +100,6 @@ int GPU_default_lights(void); int GPU_scene_object_lights( struct ViewLayer *view_layer, float viewmat[4][4], int ortho); -/* Text render - * - based on moving uv coordinates */ - -void GPU_render_text( - int mode, const char *textstr, int textlen, unsigned int *col, - const float *v_quad[4], const float *uv_quad[4], - int glattrib); - /* Mipmap settings * - these will free textures on changes */ diff --git a/source/blender/gpu/intern/gpu_draw.c b/source/blender/gpu/intern/gpu_draw.c index 8b344716a9c..e0a71f841fd 100644 --- a/source/blender/gpu/intern/gpu_draw.c +++ b/source/blender/gpu/intern/gpu_draw.c @@ -31,8 +31,8 @@ * Utility functions for dealing with OpenGL texture & material context, * mipmap generation and light objects. * - * These are some obscure rendering functions shared between the - * game engine and the blender, in this module to avoid duplication + * These are some obscure rendering functions shared between the game engine (not anymore) + * and the blender, in this module to avoid duplication * and abstract them away from the rest a bit. */ @@ -70,9 +70,6 @@ #include "BKE_node.h" #include "BKE_scene.h" #include "BKE_DerivedMesh.h" -#ifdef WITH_GAMEENGINE -# include "BKE_object.h" -#endif #include "GPU_basic_shader.h" #include "GPU_buffers.h" @@ -98,131 +95,7 @@ extern Material defmaterial; /* from material.c */ -/* Text Rendering */ - -static void gpu_mcol(unsigned int ucol) -{ - /* mcol order is swapped */ - const char *cp = (char *)&ucol; - glColor3ub(cp[3], cp[2], cp[1]); -} - -void GPU_render_text( - int mode, const char *textstr, int textlen, unsigned int *col, - const float *v_quad[4], const float *uv_quad[4], - int glattrib) -{ - /* XXX, 2.8 removes texface */ -#if 0 - Image *ima = mtexpoly->tpage; -#else - Image *ima = NULL; -#endif - if ((mode & GEMAT_TEXT) && (textlen > 0) && ima) { - const float *v1 = v_quad[0]; - const float *v2 = v_quad[1]; - const float *v3 = v_quad[2]; - const float *v4 = v_quad[3]; - const size_t textlen_st = textlen; - float centerx, centery, sizex, sizey, transx, transy, movex, movey, advance; - - /* multiline */ - float line_start = 0.0f, line_height; - - if (v4) - line_height = max_ffff(v1[1], v2[1], v3[1], v4[2]) - min_ffff(v1[1], v2[1], v3[1], v4[2]); - else - line_height = max_fff(v1[1], v2[1], v3[1]) - min_fff(v1[1], v2[1], v3[1]); - line_height *= 1.2f; /* could be an option? */ - /* end multiline */ - - - /* color has been set */ - if (!col) - glColor3f(1.0f, 1.0f, 1.0f); - - gpuPushMatrix(); - - /* get the tab width */ - ImBuf *first_ibuf = BKE_image_get_first_ibuf(ima); - matrixGlyph(first_ibuf, ' ', ¢erx, ¢ery, - &sizex, &sizey, &transx, &transy, &movex, &movey, &advance); - - float advance_tab = advance * 4; /* tab width could also be an option */ - - - for (size_t index = 0; index < textlen_st; ) { - unsigned int character; - float uv[4][2]; - - /* lets calculate offset stuff */ - character = BLI_str_utf8_as_unicode_and_size_safe(textstr + index, &index); - - if (character == '\n') { - gpuTranslate2f(line_start, -line_height); - line_start = 0.0f; - continue; - } - else if (character == '\t') { - gpuTranslate2f(advance_tab, 0.0f); - line_start -= advance_tab; /* so we can go back to the start of the line */ - continue; - - } - else if (character > USHRT_MAX) { - /* not much we can do here bmfonts take ushort */ - character = '?'; - } - - /* space starts at offset 1 */ - /* character = character - ' ' + 1; */ - matrixGlyph(first_ibuf, character, & centerx, ¢ery, - &sizex, &sizey, &transx, &transy, &movex, &movey, &advance); - - uv[0][0] = (uv_quad[0][0] - centerx) * sizex + transx; - uv[0][1] = (uv_quad[0][1] - centery) * sizey + transy; - uv[1][0] = (uv_quad[1][0] - centerx) * sizex + transx; - uv[1][1] = (uv_quad[1][1] - centery) * sizey + transy; - uv[2][0] = (uv_quad[2][0] - centerx) * sizex + transx; - uv[2][1] = (uv_quad[2][1] - centery) * sizey + transy; - - glBegin(GL_POLYGON); - if (glattrib >= 0) glVertexAttrib2fv(glattrib, uv[0]); - else glTexCoord2fv(uv[0]); - if (col) gpu_mcol(col[0]); - glVertex3f(sizex * v1[0] + movex, sizey * v1[1] + movey, v1[2]); - - if (glattrib >= 0) glVertexAttrib2fv(glattrib, uv[1]); - else glTexCoord2fv(uv[1]); - if (col) gpu_mcol(col[1]); - glVertex3f(sizex * v2[0] + movex, sizey * v2[1] + movey, v2[2]); - - if (glattrib >= 0) glVertexAttrib2fv(glattrib, uv[2]); - else glTexCoord2fv(uv[2]); - if (col) gpu_mcol(col[2]); - glVertex3f(sizex * v3[0] + movex, sizey * v3[1] + movey, v3[2]); - - if (v4) { - uv[3][0] = (uv_quad[3][0] - centerx) * sizex + transx; - uv[3][1] = (uv_quad[3][1] - centery) * sizey + transy; - - if (glattrib >= 0) glVertexAttrib2fv(glattrib, uv[3]); - else glTexCoord2fv(uv[3]); - if (col) gpu_mcol(col[3]); - glVertex3f(sizex * v4[0] + movex, sizey * v4[1] + movey, v4[2]); - } - glEnd(); - - gpuTranslate2f(advance, 0.0f); - line_start -= advance; /* so we can go back to the start of the line */ - } - gpuPopMatrix(); - - BKE_image_release_ibuf(ima, first_ibuf, NULL); - } -} - -/* Checking powers of two for images since OpenGL ES requires it */ +//* Checking powers of two for images since OpenGL ES requires it */ #ifdef WITH_DDS static bool is_power_of_2_resolution(int w, int h) { @@ -1553,7 +1426,7 @@ void GPU_end_dupli_object(void) } void GPU_begin_object_materials( - View3D *v3d, RegionView3D *rv3d, Scene *scene, ViewLayer *view_layer, Object *ob, + View3D *v3d, RegionView3D *rv3d, Scene *scene, ViewLayer *UNUSED(view_layer), Object *ob, bool glsl, bool *do_alpha_after) { Material *ma; @@ -1590,14 +1463,6 @@ void GPU_begin_object_materials( } #endif -#ifdef WITH_GAMEENGINE - if (rv3d->rflag & RV3D_IS_GAME_ENGINE) { - ob = BKE_object_lod_matob_get(ob, view_layer); - } -#else - UNUSED_VARS(view_layer); -#endif - /* initialize state */ /* DupliObject must be restored */ dob = GMS.dob; @@ -1843,18 +1708,10 @@ int GPU_object_material_bind(int nr, void *attribs) GPU_material_bind_uniforms(gpumat, GMS.gob->obmat, GMS.gviewmat, GMS.gob->col, auto_bump_scale, &partile_info, object_info); GMS.gboundmat = mat; - /* for glsl use alpha blend mode, unless it's set to solid and - * we are already drawing in an alpha pass */ - if (mat->game.alpha_blend != GPU_BLEND_SOLID) - alphablend = mat->game.alpha_blend; - if (GMS.is_alpha_pass) glDepthMask(1); if (GMS.backface_culling) { - if (mat->game.flag) - glEnable(GL_CULL_FACE); - else - glDisable(GL_CULL_FACE); + glDisable(GL_CULL_FACE); } if (GMS.use_matcaps) @@ -2120,8 +1977,8 @@ static void gpu_disable_multisample(void) /* Default OpenGL State * - * This is called on startup, for opengl offscreen render and to restore state - * for the game engine. Generally we should always return to this state when + * This is called on startup, for opengl offscreen render. + * Generally we should always return to this state when * temporarily modifying the state for drawing, though that are (undocumented) * exceptions that we should try to get rid of. */ diff --git a/source/blender/gpu/intern/gpu_lamp.c b/source/blender/gpu/intern/gpu_lamp.c index 8968521060d..f8ca11782a5 100644 --- a/source/blender/gpu/intern/gpu_lamp.c +++ b/source/blender/gpu/intern/gpu_lamp.c @@ -345,11 +345,9 @@ void GPU_lamp_free(Object *ob) BLI_freelistN(&ob->gpulamp); } -bool GPU_lamp_has_shadow_buffer(GPULamp *lamp) +bool GPU_lamp_has_shadow_buffer(GPULamp *UNUSED(lamp)) { - return (!(lamp->scene->gm.flag & GAME_GLSL_NO_SHADOWS) && - !(lamp->scene->gm.flag & GAME_GLSL_NO_LIGHTS) && - lamp->tex && lamp->fb); + return false; } void GPU_lamp_update_buffer_mats(GPULamp *lamp) diff --git a/source/blender/gpu/intern/gpu_material.c b/source/blender/gpu/intern/gpu_material.c index 98d8eea6036..53ef9835d1d 100644 --- a/source/blender/gpu/intern/gpu_material.c +++ b/source/blender/gpu/intern/gpu_material.c @@ -1049,7 +1049,7 @@ static void ramp_diffuse_result(GPUShadeInput *shi, GPUNodeLink **diff) Material *ma = shi->mat; GPUMaterial *mat = shi->gpumat; - if (!(mat->scene->gm.flag & GAME_GLSL_NO_RAMPS)) { + { if (ma->ramp_col) { if (ma->rampin_col == MA_RAMP_IN_RESULT) { GPUNodeLink *fac; @@ -1068,9 +1068,7 @@ static void add_to_diffuse( { GPUNodeLink *fac, *tmp, *addcol; - if (!(mat->scene->gm.flag & GAME_GLSL_NO_RAMPS) && - ma->ramp_col && (ma->mode & MA_RAMP_COL)) - { + if (ma->ramp_col && (ma->mode & MA_RAMP_COL)) { /* MA_RAMP_IN_RESULT is exceptional */ if (ma->rampin_col == MA_RAMP_IN_RESULT) { addcol = shi->rgb; @@ -1108,9 +1106,7 @@ static void ramp_spec_result(GPUShadeInput *shi, GPUNodeLink **spec) Material *ma = shi->mat; GPUMaterial *mat = shi->gpumat; - if (!(mat->scene->gm.flag & GAME_GLSL_NO_RAMPS) && - ma->ramp_spec && ma->rampin_spec == MA_RAMP_IN_RESULT) - { + if (ma->ramp_spec && ma->rampin_spec == MA_RAMP_IN_RESULT) { GPUNodeLink *fac; GPU_link(mat, "ramp_rgbtobw", *spec, &fac); @@ -1224,7 +1220,7 @@ static void shade_one_light(GPUShadeInput *shi, GPUShadeResult *shr, GPULamp *la is = inp; /* Lambert */ - if (!(mat->scene->gm.flag & GAME_GLSL_NO_SHADERS)) { + { if (ma->diff_shader == MA_DIFF_ORENNAYAR) GPU_link(mat, "shade_diffuse_oren_nayer", inp, vn, lv, view, GPU_uniform(&ma->roughness), &is); @@ -1240,10 +1236,9 @@ static void shade_one_light(GPUShadeInput *shi, GPUShadeResult *shr, GPULamp *la } } - if (!(mat->scene->gm.flag & GAME_GLSL_NO_SHADERS)) - if (ma->shade_flag & MA_CUBIC) - GPU_link(mat, "shade_cubic", is, &is); - + if (ma->shade_flag & MA_CUBIC) + GPU_link(mat, "shade_cubic", is, &is); + i = is; GPU_link(mat, "shade_visifac", i, visifac, shi->refl, &i); @@ -1260,8 +1255,8 @@ static void shade_one_light(GPUShadeInput *shi, GPUShadeResult *shr, GPULamp *la /* this replaces if (i > 0.0) conditional until that is supported */ /* done in shade_visifac now, GPU_link(mat, "mtex_value_clamp_positive", i, &i); */ - if ((ma->mode & MA_SHADOW) && GPU_lamp_has_shadow_buffer(lamp)) { - if (!(mat->scene->gm.flag & GAME_GLSL_NO_SHADOWS)) { + if (ma->mode & MA_SHADOW) { + { mat->dynproperty |= DYN_LAMP_PERSMAT; if (lamp->la->shadowmap_type == LA_SHADMAP_VARIANCE) { @@ -1300,7 +1295,7 @@ static void shade_one_light(GPUShadeInput *shi, GPUShadeResult *shr, GPULamp *la } } } - else if ((mat->scene->gm.flag & GAME_GLSL_NO_SHADOWS) && (lamp->mode & LA_ONLYSHADOW)) { + else if (lamp->mode & LA_ONLYSHADOW) { add_user_list(&mat->lamps, lamp); return; } @@ -1318,10 +1313,7 @@ static void shade_one_light(GPUShadeInput *shi, GPUShadeResult *shr, GPULamp *la } } - if (mat->scene->gm.flag & GAME_GLSL_NO_SHADERS) { - /* pass */ - } - else if (!(lamp->mode & LA_NO_SPEC) && !(lamp->mode & LA_ONLYSHADOW) && + if (!(lamp->mode & LA_NO_SPEC) && !(lamp->mode & LA_ONLYSHADOW) && (GPU_link_changed(shi->spec) || ma->spec != 0.0f)) { if (lamp->type == LA_HEMI) { @@ -1674,7 +1666,7 @@ static void do_material_tex(GPUShadeInput *shi) texture_rgb_blend(mat, tcol, shi->rgb, tin, colfac, mtex->blendtype, &shi->rgb); } - if (!(mat->scene->gm.flag & GAME_GLSL_NO_EXTRA_TEX) && (mtex->mapto & MAP_COLSPEC)) { + if (mtex->mapto & MAP_COLSPEC) { GPUNodeLink *colspecfac; if (mtex->colspecfac == 1.0f) colspecfac = stencil; @@ -1698,7 +1690,7 @@ static void do_material_tex(GPUShadeInput *shi) } } - if (!(mat->scene->gm.flag & GAME_GLSL_NO_EXTRA_TEX) && (mtex->mapto & MAP_NORM)) { + if (mtex->mapto & MAP_NORM) { if (tex->type == TEX_IMAGE) { found_deriv_map = tex->imaflag & TEX_DERIVATIVEMAP; @@ -1905,7 +1897,7 @@ static void do_material_tex(GPUShadeInput *shi) GPU_link(mat, "mtex_rgbtoint", trgb, &tin); } - if (!(mat->scene->gm.flag & GAME_GLSL_NO_EXTRA_TEX) && mtex->mapto & MAP_REF) { + if (mtex->mapto & MAP_REF) { GPUNodeLink *difffac; if (mtex->difffac == 1.0f) difffac = stencil; @@ -1916,7 +1908,7 @@ static void do_material_tex(GPUShadeInput *shi) mtex->blendtype, &shi->refl); GPU_link(mat, "mtex_value_clamp_positive", shi->refl, &shi->refl); } - if (!(mat->scene->gm.flag & GAME_GLSL_NO_EXTRA_TEX) && mtex->mapto & MAP_SPEC) { + if (mtex->mapto & MAP_SPEC) { GPUNodeLink *specfac; if (mtex->specfac == 1.0f) specfac = stencil; @@ -1927,7 +1919,7 @@ static void do_material_tex(GPUShadeInput *shi) mtex->blendtype, &shi->spec); GPU_link(mat, "mtex_value_clamp_positive", shi->spec, &shi->spec); } - if (!(mat->scene->gm.flag & GAME_GLSL_NO_EXTRA_TEX) && mtex->mapto & MAP_EMIT) { + if (mtex->mapto & MAP_EMIT) { GPUNodeLink *emitfac; if (mtex->emitfac == 1.0f) emitfac = stencil; @@ -1938,7 +1930,7 @@ static void do_material_tex(GPUShadeInput *shi) mtex->blendtype, &shi->emit); GPU_link(mat, "mtex_value_clamp_positive", shi->emit, &shi->emit); } - if (!(mat->scene->gm.flag & GAME_GLSL_NO_EXTRA_TEX) && mtex->mapto & MAP_HAR) { + if (mtex->mapto & MAP_HAR) { GPUNodeLink *hardfac; if (mtex->hardfac == 1.0f) hardfac = stencil; @@ -1961,7 +1953,7 @@ static void do_material_tex(GPUShadeInput *shi) mtex->blendtype, &shi->alpha); GPU_link(mat, "mtex_value_clamp", shi->alpha, &shi->alpha); } - if (!(mat->scene->gm.flag & GAME_GLSL_NO_EXTRA_TEX) && mtex->mapto & MAP_AMB) { + if (mtex->mapto & MAP_AMB) { GPUNodeLink *ambfac; if (mtex->ambfac == 1.0f) ambfac = stencil; @@ -2056,7 +2048,7 @@ void GPU_shaderesult_set(GPUShadeInput *shi, GPUShadeResult *shr) do_material_tex(shi); - if ((mat->scene->gm.flag & GAME_GLSL_NO_LIGHTS) || (ma->mode & MA_SHLESS)) { + if (ma->mode & MA_SHLESS) { GPU_link(mat, "set_rgb", shi->rgb, &shr->diff); GPU_link(mat, "set_rgb_zero", &shr->spec); GPU_link(mat, "set_value", shi->alpha, &shr->alpha); @@ -2098,8 +2090,7 @@ void GPU_shaderesult_set(GPUShadeInput *shi, GPUShadeResult *shr) } /* environment lighting */ - if (!(mat->scene->gm.flag & GAME_GLSL_NO_ENV_LIGHTING) && - (world->mode & WO_ENV_LIGHT) && + if ((world->mode & WO_ENV_LIGHT) && (mat->scene->r.mode & R_SHADOW) && !BKE_scene_use_new_shading_nodes(mat->scene)) { @@ -2608,7 +2599,7 @@ GPUMaterial *GPU_material_from_blender(Scene *scene, Material *ma, bool use_open else if (new_shading_nodes && ma->alpha < 1.0f) GPU_material_enable_alpha(mat); - if (!(scene->gm.flag & GAME_GLSL_NO_NODES) && ma->nodetree && ma->use_nodes) { + if (ma->nodetree && ma->use_nodes) { /* create nodes */ if (new_shading_nodes) ntreeGPUMaterialNodes(ma->nodetree, mat, NODE_NEW_SHADING); diff --git a/source/blender/ikplugin/intern/itasc_plugin.cpp b/source/blender/ikplugin/intern/itasc_plugin.cpp index dc2d081f835..af303556090 100644 --- a/source/blender/ikplugin/intern/itasc_plugin.cpp +++ b/source/blender/ikplugin/intern/itasc_plugin.cpp @@ -1072,12 +1072,11 @@ static IK_Scene *convert_tree(struct Depsgraph *depsgraph, Scene *blscene, Objec IK_Scene *ikscene; IK_Channel *ikchan; KDL::Frame initPose; - KDL::Rotation boneRot; Bone *bone; int a, numtarget; unsigned int t; float length; - bool ret = true, ingame; + bool ret = true; double *rot; float start[3]; @@ -1094,26 +1093,13 @@ static IK_Scene *convert_tree(struct Depsgraph *depsgraph, Scene *blscene, Objec ikscene->armature = arm; ikscene->scene = scene; ikparam = (bItasc *)ob->pose->ikparam; - ingame = (ob->pose->flag & POSE_GAME_ENGINE); + if (!ikparam) { // you must have our own copy ikparam = &DefIKParam; } - else if (ingame) { - // tweak the param when in game to have efficient stepping - // using fixed substep is not effecient since frames in the GE are often - // shorter than in animation => move to auto step automatically and set - // the target substep duration via min/max - if (!(ikparam->flag & ITASC_AUTO_STEP)) { - float timestep = blscene->r.frs_sec_base / blscene->r.frs_sec; - if (ikparam->numstep > 0) - timestep /= ikparam->numstep; - // with equal min and max, the algorythm will take this step and the indicative substep most of the time - ikparam->minstep = ikparam->maxstep = timestep; - ikparam->flag |= ITASC_AUTO_STEP; - } - } - if ((ikparam->flag & ITASC_SIMULATION) && !ingame) + + if (ikparam->flag & ITASC_SIMULATION) // no cache in animation mode ikscene->cache = new iTaSC::Cache(); @@ -1140,15 +1126,8 @@ static IK_Scene *convert_tree(struct Depsgraph *depsgraph, Scene *blscene, Objec double weight[3]; // build the array of joints corresponding to the IK chain convert_channels(depsgraph, ikscene, tree, ctime); - if (ingame) { - // in the GE, set the initial joint angle to match the current pose - // this will update the jointArray in ikscene - convert_pose(ikscene); - } - else { - // in Blender, the rest pose is always 0 for joints - BKE_pose_rest(ikscene); - } + // in Blender, the rest pose is always 0 for joints + BKE_pose_rest(ikscene); rot = ikscene->jointArray(0); for (a = 0, ikchan = ikscene->channels; a < tree->totchannel; ++a, ++ikchan) { @@ -1787,12 +1766,6 @@ void itasc_execute_tree(struct Depsgraph *depsgraph, struct Scene *scene, Object for (IK_Scene *ikscene = ikdata->first; ikscene; ikscene = ikscene->next) { if (ikscene->channels[0].pchan == pchan_root) { float timestep = scene->r.frs_sec_base / scene->r.frs_sec; - if (ob->pose->flag & POSE_GAME_ENGINE) { - timestep = ob->pose->ctime; - // limit the timestep to avoid excessive number of iteration - if (timestep > 0.2f) - timestep = 0.2f; - } execute_scene(depsgraph, scene, ikscene, ikparam, ctime, timestep); break; } diff --git a/source/blender/imbuf/intern/indexer.c b/source/blender/imbuf/intern/indexer.c index eaf4dfd84b4..2bda07bdbbe 100644 --- a/source/blender/imbuf/intern/indexer.c +++ b/source/blender/imbuf/intern/indexer.c @@ -1041,7 +1041,7 @@ static IndexBuildContext *index_fallback_create_context(struct anim *anim, IMB_T /* since timecode indices only work with ffmpeg right now, * don't know a sensible fallback here... * - * so no proxies, no game to play... + * so no proxies... */ if (proxy_sizes_in_use == IMB_PROXY_NONE) { return NULL; diff --git a/source/blender/makesdna/DNA_action_types.h b/source/blender/makesdna/DNA_action_types.h index 95cbdeadf87..e1306253df8 100644 --- a/source/blender/makesdna/DNA_action_types.h +++ b/source/blender/makesdna/DNA_action_types.h @@ -434,8 +434,7 @@ typedef enum ePose_Flags { POSE_RECALCPATHS = (1 << 4), /* set by BKE_pose_rebuild to give a chance to the IK solver to rebuild IK tree */ POSE_WAS_REBUILT = (1 << 5), - /* set by game_copy_pose to indicate that this pose is used in the game engine */ - POSE_GAME_ENGINE = (1 << 6), + POSE_FLAG_DEPRECATED = (1 << 6), /* deprecated. */ /* pose constraint flags needs to be updated */ POSE_CONSTRAINTS_NEED_UPDATE_FLAGS = (1 << 7), } ePose_Flags; diff --git a/source/blender/makesdna/DNA_actuator_types.h b/source/blender/makesdna/DNA_actuator_types.h deleted file mode 100644 index 6bdea21da1e..00000000000 --- a/source/blender/makesdna/DNA_actuator_types.h +++ /dev/null @@ -1,583 +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 DNA_actuator_types.h - * \ingroup DNA - * - * #bActuator type is specifically for use by Object logic-bricks in the game-engine. - */ - -#ifndef __DNA_ACTUATOR_TYPES_H__ -#define __DNA_ACTUATOR_TYPES_H__ - -struct Object; -struct Mesh; -struct Scene; -struct Group; -struct Text; - -/* ****************** ACTUATORS ********************* */ - -/* unused now, moved to editobjectactuator in 2.02. Still needed for dna */ -typedef struct bAddObjectActuator { - int time, pad; - struct Object *ob; -} bAddObjectActuator; - -typedef struct bActionActuator { - struct bAction *act; /* Pointer to action */ - short type, flag; /* Playback type */ // not in use - float sta, end; /* Start & End frames */ - char name[64]; /* For property-driven playback, MAX_NAME */ - char frameProp[64]; /* Set this property to the actions current frame, MAX_NAME */ - short blendin; /* Number of frames of blending */ - short priority; /* Execution priority */ - short layer; /* Animation layer */ - short end_reset; /* Ending the actuator (negative pulse) wont reset the action to its starting frame */ - short strideaxis; /* Displacement axis */ - short blend_mode; /* Layer blending mode */ - float stridelength; /* Displacement incurred by cycle */ // not in use - float layer_weight; /* How much of the previous layer to use for blending. (<0 = disable, 0 = add mode) */ -} bActionActuator; - -typedef struct Sound3D { - 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; -} Sound3D; - -typedef struct bSoundActuator { - short flag, sndnr; - int pad1, pad2; - short pad3[2]; - float volume, pitch; - struct bSound *sound; - struct Sound3D sound3D; - short type, pad4; - short pad5, pad6[1]; -} bSoundActuator; - -typedef struct bEditObjectActuator { - int time; - short type, flag; - struct Object *ob; - struct Mesh *me; - char name[64]; /* MAX_NAME */ - float linVelocity[3]; /* initial lin. velocity on creation */ - float angVelocity[3]; /* initial ang. velocity on creation */ - float mass; - short localflag; /* flag for the lin & ang. vel: apply locally */ - short dyn_operation; - short upflag, trackflag; /* flag for up axis and track axis */ - int pad; -} bEditObjectActuator; - -typedef struct bSceneActuator { - short type, pad1; - int pad; - struct Scene *scene; - struct Object *camera; -} bSceneActuator; - -typedef struct bPropertyActuator { - int pad, type; - char name[64], value[64]; /* MAX_NAME */ - struct Object *ob; -} bPropertyActuator; - -typedef struct bObjectActuator { - short flag, type, otype; - short damping; - float forceloc[3], forcerot[3]; - float pad[3], pad1[3]; - float dloc[3], drot[3]; /* angle in radians */ - float linearvelocity[3], angularvelocity[3]; - struct Object *reference; -} bObjectActuator; - -/* deprecated, handled by bActionActuator now */ -typedef struct bIpoActuator { - short flag, type; - float sta, end; - char name[64]; /* MAX_NAME */ - char frameProp[64]; /* Set this property to the actions current frame, MAX_NAME */ - - short pad1, pad2, pad3, pad4; - -} bIpoActuator; - -typedef struct bCameraActuator { - struct Object *ob; - float height, min, max; - float damping; - short pad1, axis; - float pad2; -} bCameraActuator; - -typedef struct bConstraintActuator { - short type, mode; - short flag, damp; - short time, rotdamp; - int pad; - float minloc[3], maxloc[3]; - float minrot[3], maxrot[3]; - char matprop[64]; /* MAX_NAME */ -} bConstraintActuator; - -typedef struct bGroupActuator { - short flag, type; - int sta, end; - char name[64]; /* property or groupkey, MAX_NAME */ - - short pad[3], cur, butsta, butend;/* not referenced, can remove? */ - /* struct Group *group; not used, remove */ - -} bGroupActuator; - -/* I added a few extra fields here, to facilitate conversions */ -typedef struct bRandomActuator { - int seed; - int distribution; - int int_arg_1; - int int_arg_2; - float float_arg_1; - float float_arg_2; - char propname[64]; /* MAX_NAME */ -} bRandomActuator; - -typedef struct bMessageActuator { - char toPropName[64]; /* Send to all objects with this propertyname. Empty to broadcast. MAX_NAME. */ - struct Object *toObject;/* (Possible future use) pointer to a single destination object. */ - char subject[64]; /* Message Subject to send. MAX_NAME. */ - short bodyType, pad1; /* bodyType is either 'User defined text' or PropName */ - int pad2; - char body[64]; /* Either User Defined Text or our PropName to send value of, MAX_NAME */ -} bMessageActuator; - -typedef struct bGameActuator { - short flag, type; - int sta, end; - char filename[64]; - char loadaniname[64]; -} bGameActuator; - -typedef struct bVisibilityActuator { - /** bit 0: Is this object visible? - ** bit 1: Apply recursively - ** bit 2: Is this object an occluder? */ - int flag; -} bVisibilityActuator; - -typedef struct bTwoDFilterActuator { - char pad[4]; - /* Tells what type of 2D Filter */ - short type; - /* (flag == 0) means 2D filter is activate and - * (flag != 0) means 2D filter is inactive */ - short flag; - int int_arg; - /* a float argument */ - float float_arg; - struct Text *text; -} bTwoDFilterActuator; - -typedef struct bParentActuator { - char pad[2]; - short flag; - int type; - struct Object *ob; -} bParentActuator; - -typedef struct bStateActuator { - int type; /* 0=Set, 1=Add, 2=Rem, 3=Chg */ - unsigned int mask; /* the bits to change */ -} bStateActuator; - -typedef struct bArmatureActuator { - char posechannel[64]; /* MAX_NAME */ - char constraint[64]; /* MAX_NAME */ - int type; /* 0=run, 1=enable, 2=disable, 3=set target, 4=set weight */ - float weight; - float influence; - float pad; - struct Object *target; - struct Object *subtarget; -} bArmatureActuator; - -typedef struct bSteeringActuator { - char pad[5]; - char flag; - short facingaxis; - int type; /* 0=seek, 1=flee, 2=path following */ - float dist; - float velocity; - float acceleration; - float turnspeed; - int updateTime; - struct Object *target; - struct Object *navmesh; -} bSteeringActuator; - -typedef struct bMouseActuator { - short type; /* 0=Visibility, 1=Look */ - short flag; - - int object_axis[2]; - float threshold[2]; - float sensitivity[2]; - float limit_x[2]; - float limit_y[2]; -} bMouseActuator; - - -typedef struct bActuator { - struct bActuator *next, *prev, *mynew; - short type; - /** - * Tells what type of actuator data \ref data holds. - */ - short flag; - short otype, go; - char name[64]; /* MAX_NAME */ - - /** - * data must point to an object actuator type struct. - */ - void *data; - - /** - * For ipo's and props: to find out which object the actuator - * belongs to */ - struct Object *ob; - -} bActuator; - -/* objectactuator->flag */ -#define ACT_FORCE_LOCAL 1 -#define ACT_TORQUE_LOCAL 2 -#define ACT_SERVO_LIMIT_X 2 -#define ACT_DLOC_LOCAL 4 -#define ACT_SERVO_LIMIT_Y 4 -#define ACT_DROT_LOCAL 8 -#define ACT_SERVO_LIMIT_Z 8 -#define ACT_LIN_VEL_LOCAL 16 -#define ACT_ANG_VEL_LOCAL 32 -//#define ACT_ADD_LIN_VEL_LOCAL 64 -#define ACT_ADD_LIN_VEL 64 -#define ACT_ADD_CHAR_LOC 128 -#define ACT_CHAR_JUMP 256 - -/* objectactuator->type */ -#define ACT_OBJECT_NORMAL 0 -#define ACT_OBJECT_SERVO 1 -#define ACT_OBJECT_CHARACTER 2 - -/* actuator->type */ -#define ACT_OBJECT 0 -#define ACT_IPO 1 -#define ACT_LAMP 2 -#define ACT_CAMERA 3 -#define ACT_MATERIAL 4 -#define ACT_SOUND 5 -#define ACT_PROPERTY 6 - /* these two obsolete since 2.02 */ -#define ACT_ADD_OBJECT 7 -#define ACT_END_OBJECT 8 - -#define ACT_CONSTRAINT 9 -#define ACT_EDIT_OBJECT 10 -#define ACT_SCENE 11 -#define ACT_GROUP 12 -#define ACT_RANDOM 13 -#define ACT_MESSAGE 14 -#define ACT_ACTION 15 /* __ NLA */ -#define ACT_GAME 17 -#define ACT_VISIBILITY 18 -#define ACT_2DFILTER 19 -#define ACT_PARENT 20 -#define ACT_SHAPEACTION 21 -#define ACT_STATE 22 -#define ACT_ARMATURE 23 -#define ACT_STEERING 24 -#define ACT_MOUSE 25 - -/* actuator flag */ -#define ACT_SHOW 1 -#define ACT_DEL 2 -#define ACT_NEW 4 -#define ACT_LINKED 8 -#define ACT_VISIBLE 16 -#define ACT_PIN 32 -#define ACT_DEACTIVATE 64 - -/* link codes */ -#define LINK_SENSOR 0 -#define LINK_CONTROLLER 1 -#define LINK_ACTUATOR 2 - -/* keyboardsensor->type */ -#define SENS_ALL_KEYS 1 - -/* actionactuator->type */ -#define ACT_ACTION_PLAY 0 -#define ACT_ACTION_PINGPONG 1 -#define ACT_ACTION_FLIPPER 2 -#define ACT_ACTION_LOOP_STOP 3 -#define ACT_ACTION_LOOP_END 4 -#define ACT_ACTION_KEY2KEY 5 -#define ACT_ACTION_FROM_PROP 6 -#define ACT_ACTION_MOTION 7 - -/* actionactuator->blend_mode */ -#define ACT_ACTION_BLEND 0 -#define ACT_ACTION_ADD 1 - -/* ipoactuator->type */ -/* used for conversion from 2.01 */ -#define ACT_IPO_FROM_PROP 6 - -/* groupactuator->type */ -#define ACT_GROUP_PLAY 0 -#define ACT_GROUP_PINGPONG 1 -#define ACT_GROUP_FLIPPER 2 -#define ACT_GROUP_LOOP_STOP 3 -#define ACT_GROUP_LOOP_END 4 -#define ACT_GROUP_FROM_PROP 5 -#define ACT_GROUP_SET 6 - -/* ipoactuator->flag */ -#define ACT_IPOFORCE (1 << 0) -#define ACT_IPOEND (1 << 1) -#define ACT_IPOLOCAL (1 << 2) -#define ACT_IPOCHILD (1 << 4) -#define ACT_IPOADD (1 << 5) - -/* property actuator->type */ -#define ACT_PROP_ASSIGN 0 -#define ACT_PROP_ADD 1 -#define ACT_PROP_COPY 2 -#define ACT_PROP_TOGGLE 3 -#define ACT_PROP_LEVEL 4 - -/* constraint flag */ -#define ACT_CONST_NONE 0 -#define ACT_CONST_LOCX 1 -#define ACT_CONST_LOCY 2 -#define ACT_CONST_LOCZ 4 -#define ACT_CONST_ROTX 8 -#define ACT_CONST_ROTY 16 -#define ACT_CONST_ROTZ 32 -#define ACT_CONST_NORMAL 64 -#define ACT_CONST_MATERIAL 128 -#define ACT_CONST_PERMANENT 256 -#define ACT_CONST_DISTANCE 512 -#define ACT_CONST_LOCAL 1024 -#define ACT_CONST_DOROTFH 2048 - -/* constraint mode */ -#define ACT_CONST_DIRPX 1 -#define ACT_CONST_DIRPY 2 -#define ACT_CONST_DIRPZ 4 -#define ACT_CONST_DIRNX 8 -#define ACT_CONST_DIRNY 16 -#define ACT_CONST_DIRNZ 32 - -/* constraint type */ -#define ACT_CONST_TYPE_LOC 0 -#define ACT_CONST_TYPE_DIST 1 -#define ACT_CONST_TYPE_ORI 2 -#define ACT_CONST_TYPE_FH 3 - -/* editObjectActuator->type */ -#define ACT_EDOB_ADD_OBJECT 0 -#define ACT_EDOB_END_OBJECT 1 -#define ACT_EDOB_REPLACE_MESH 2 -#define ACT_EDOB_TRACK_TO 3 -#define ACT_EDOB_DYNAMICS 4 - -/* editObjectActuator->localflag */ -#define ACT_EDOB_LOCAL_LINV 2 -#define ACT_EDOB_LOCAL_ANGV 4 - -/* editObjectActuator->flag */ -#define ACT_TRACK_3D 1 - -/* editObjectActuator->upflag */ -#define ACT_TRACK_UP_X 0 -#define ACT_TRACK_UP_Y 1 -#define ACT_TRACK_UP_Z 2 - -/* editObjectActuator->trackflag */ -#define ACT_TRACK_TRAXIS_X 0 -#define ACT_TRACK_TRAXIS_Y 1 -#define ACT_TRACK_TRAXIS_Z 2 -#define ACT_TRACK_TRAXIS_NEGX 3 -#define ACT_TRACK_TRAXIS_NEGY 4 -#define ACT_TRACK_TRAXIS_NEGZ 5 - -/* editObjectActuator->flag for replace mesh actuator */ -#define ACT_EDOB_REPLACE_MESH_NOGFX 2 /* use for replace mesh actuator */ -#define ACT_EDOB_REPLACE_MESH_PHYS 4 - -/* editObjectActuator->dyn_operation */ -#define ACT_EDOB_RESTORE_DYN 0 -#define ACT_EDOB_SUSPEND_DYN 1 -#define ACT_EDOB_ENABLE_RB 2 -#define ACT_EDOB_DISABLE_RB 3 -#define ACT_EDOB_SET_MASS 4 - - -/* SceneActuator->type */ -#define ACT_SCENE_RESTART 0 -#define ACT_SCENE_SET 1 -#define ACT_SCENE_CAMERA 2 -#define ACT_SCENE_ADD_FRONT 3 -#define ACT_SCENE_ADD_BACK 4 -#define ACT_SCENE_REMOVE 5 -#define ACT_SCENE_SUSPEND 6 -#define ACT_SCENE_RESUME 7 - - -/* randomAct->distribution */ -#define ACT_RANDOM_BOOL_CONST 0 -#define ACT_RANDOM_BOOL_UNIFORM 1 -#define ACT_RANDOM_BOOL_BERNOUILLI 2 -#define ACT_RANDOM_INT_CONST 3 -#define ACT_RANDOM_INT_UNIFORM 4 -#define ACT_RANDOM_INT_POISSON 5 -#define ACT_RANDOM_FLOAT_CONST 6 -#define ACT_RANDOM_FLOAT_UNIFORM 7 -#define ACT_RANDOM_FLOAT_NORMAL 8 -#define ACT_RANDOM_FLOAT_NEGATIVE_EXPONENTIAL 9 - -/* SoundActuator->flag */ -#define ACT_SND_3D_SOUND 1 - -/* SoundActuator->type */ -#define ACT_SND_PLAY_STOP_SOUND 0 -#define ACT_SND_PLAY_END_SOUND 1 -#define ACT_SND_LOOP_STOP_SOUND 2 -#define ACT_SND_LOOP_END_SOUND 3 -#define ACT_SND_LOOP_BIDIRECTIONAL_SOUND 4 -#define ACT_SND_LOOP_BIDIRECTIONAL_STOP_SOUND 5 - -/* messageactuator->type */ -#define ACT_MESG_MESG 0 -#define ACT_MESG_PROP 1 - -/* gameactuator->type */ -#define ACT_GAME_LOAD 0 -#define ACT_GAME_START 1 -#define ACT_GAME_RESTART 2 -#define ACT_GAME_QUIT 3 -#define ACT_GAME_SAVECFG 4 -#define ACT_GAME_LOADCFG 5 -#define ACT_GAME_SCREENSHOT 6 - -/* visibilityact->flag */ -/* Set means the object will become invisible */ -#define ACT_VISIBILITY_INVISIBLE (1 << 0) -#define ACT_VISIBILITY_RECURSIVE (1 << 1) -#define ACT_VISIBILITY_OCCLUSION (1 << 2) - -/* twodfilter->type */ -#define ACT_2DFILTER_ENABLED -2 -#define ACT_2DFILTER_DISABLED -1 -#define ACT_2DFILTER_NOFILTER 0 -#define ACT_2DFILTER_MOTIONBLUR 1 -#define ACT_2DFILTER_BLUR 2 -#define ACT_2DFILTER_SHARPEN 3 -#define ACT_2DFILTER_DILATION 4 -#define ACT_2DFILTER_EROSION 5 -#define ACT_2DFILTER_LAPLACIAN 6 -#define ACT_2DFILTER_SOBEL 7 -#define ACT_2DFILTER_PREWITT 8 -#define ACT_2DFILTER_GRAYSCALE 9 -#define ACT_2DFILTER_SEPIA 10 -#define ACT_2DFILTER_INVERT 11 -#define ACT_2DFILTER_CUSTOMFILTER 12 -#define ACT_2DFILTER_NUMBER_OF_FILTERS 13 - -/* parentactuator->type */ -#define ACT_PARENT_SET 0 -#define ACT_PARENT_REMOVE 1 - -/* parentactuator->flag */ -#define ACT_PARENT_COMPOUND 1 -#define ACT_PARENT_GHOST 2 - -/* armatureactuator->type */ -#define ACT_ARM_RUN 0 -#define ACT_ARM_ENABLE 1 -#define ACT_ARM_DISABLE 2 -#define ACT_ARM_SETTARGET 3 -#define ACT_ARM_SETWEIGHT 4 -#define ACT_ARM_SETINFLUENCE 5 -/* update this define if more types are added */ -#define ACT_ARM_MAXTYPE 5 - -/* stateactuator->type */ -#define ACT_STATE_SET 0 -#define ACT_STATE_ADD 1 -#define ACT_STATE_REMOVE 2 -#define ACT_STATE_CHANGE 3 - -/* steeringactuator->type */ -#define ACT_STEERING_SEEK 0 -#define ACT_STEERING_FLEE 1 -#define ACT_STEERING_PATHFOLLOWING 2 -/* steeringactuator->flag */ -#define ACT_STEERING_SELFTERMINATED 1 -#define ACT_STEERING_ENABLEVISUALIZATION 2 -#define ACT_STEERING_AUTOMATICFACING 4 -#define ACT_STEERING_NORMALUP 8 -#define ACT_STEERING_LOCKZVEL 16 - -/* mouseactuator->type */ -#define ACT_MOUSE_VISIBILITY 0 -#define ACT_MOUSE_LOOK 1 - -/* mouseactuator->flag */ -#define ACT_MOUSE_VISIBLE (1 << 0) -#define ACT_MOUSE_USE_AXIS_X (1 << 1) -#define ACT_MOUSE_USE_AXIS_Y (1 << 2) -#define ACT_MOUSE_RESET_X (1 << 3) -#define ACT_MOUSE_RESET_Y (1 << 4) -#define ACT_MOUSE_LOCAL_X (1 << 5) -#define ACT_MOUSE_LOCAL_Y (1 << 6) - -/* mouseactuator->object_axis */ -#define ACT_MOUSE_OBJECT_AXIS_X 0 -#define ACT_MOUSE_OBJECT_AXIS_Y 1 -#define ACT_MOUSE_OBJECT_AXIS_Z 2 - -#endif /* __DNA_ACTUATOR_TYPES_H__ */ diff --git a/source/blender/makesdna/DNA_constraint_types.h b/source/blender/makesdna/DNA_constraint_types.h index 4c4440ad573..9a87b64ac08 100644 --- a/source/blender/makesdna/DNA_constraint_types.h +++ b/source/blender/makesdna/DNA_constraint_types.h @@ -488,7 +488,7 @@ typedef enum eBConstraint_Types { CONSTRAINT_TYPE_DISTLIMIT = 14, /* limit distance */ CONSTRAINT_TYPE_STRETCHTO = 15, /* claiming this to be mine :) is in tuhopuu bjornmose */ CONSTRAINT_TYPE_MINMAX = 16, /* floor constraint */ - CONSTRAINT_TYPE_RIGIDBODYJOINT = 17, /* rigidbody constraint */ + /* CONSTRAINT_TYPE_DEPRECATED = 17 */ CONSTRAINT_TYPE_CLAMPTO = 18, /* clampto constraint */ CONSTRAINT_TYPE_TRANSFORM = 19, /* transformation (loc/rot/size -> loc/rot/size) constraint */ CONSTRAINT_TYPE_SHRINKWRAP = 20, /* shrinkwrap (loc/rot) constraint */ @@ -841,10 +841,6 @@ typedef enum eObjectSolver_Flags { OBJECTSOLVER_ACTIVECLIP = (1<<0) } eObjectSolver_Flags; -/* Rigid-Body Constraint */ -#define CONSTRAINT_DRAW_PIVOT 0x40 -#define CONSTRAINT_DISABLE_LINKED_COLLISION 0x80 - /* ObjectSolver Constraint -> flag */ typedef enum eStretchTo_Flags { STRETCHTOCON_USE_BULGE_MIN = (1 << 0), diff --git a/source/blender/makesdna/DNA_controller_types.h b/source/blender/makesdna/DNA_controller_types.h deleted file mode 100644 index 154542d60c5..00000000000 --- a/source/blender/makesdna/DNA_controller_types.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 DNA_controller_types.h - * \ingroup DNA - * - * #bController type is specifically for use by Object logic-bricks in the game-engine. - */ - -#ifndef __DNA_CONTROLLER_TYPES_H__ -#define __DNA_CONTROLLER_TYPES_H__ - -struct bActuator; -struct Text; -struct bSensor; - -/* ****************** CONTROLLERS ********************* */ - -typedef struct bExpressionCont { - char str[128]; -} bExpressionCont; - -typedef struct bPythonCont { - struct Text *text; - char module[64]; - int mode; - int flag; /* only used for debug now */ -} bPythonCont; - -typedef struct bController { - struct bController *next, *prev, *mynew; - short type, flag, inputs, totlinks; - short otype, totslinks, pad2, pad3; - - char name[64]; - void *data; - - struct bActuator **links; - - struct bSensor **slinks; - short val, valo; - unsigned int state_mask; - -} bController; - -/* controller->type */ -#define CONT_LOGIC_AND 0 -#define CONT_LOGIC_OR 1 -#define CONT_EXPRESSION 2 -#define CONT_PYTHON 3 -#define CONT_LOGIC_NAND 4 -#define CONT_LOGIC_NOR 5 -#define CONT_LOGIC_XOR 6 -#define CONT_LOGIC_XNOR 7 - -/* controller->flag */ -#define CONT_SHOW 1 -#define CONT_DEL 2 -#define CONT_NEW 4 -#define CONT_MASK 8 -#define CONT_PRIO 16 -#define CONT_DEACTIVATE 32 - -/* pyctrl->flag */ -#define CONT_PY_DEBUG 1 - -/* pyctrl->mode */ -#define CONT_PY_SCRIPT 0 -#define CONT_PY_MODULE 1 - -#endif /* __DNA_CONTROLLER_TYPES_H__ */ diff --git a/source/blender/makesdna/DNA_material_types.h b/source/blender/makesdna/DNA_material_types.h index bc33b7ba6e2..b6f74c7e6f7 100644 --- a/source/blender/makesdna/DNA_material_types.h +++ b/source/blender/makesdna/DNA_material_types.h @@ -75,14 +75,6 @@ typedef struct VolumeSettings { float ms_spread; } VolumeSettings; -/* Game Engine Options (old Texface mode, transp and flag) */ -typedef struct GameSettings { - int flag; - int alpha_blend; - int face_orientation; - int pad1; -} GameSettings; - typedef struct TexPaintSlot { struct Image *ima; /* image to be painted on */ char *uvname; /* customdata index for uv layer, MAX_NAME*/ @@ -116,7 +108,6 @@ typedef struct Material { /* end synced with render_types.h */ struct VolumeSettings vol; - struct GameSettings game; float fresnel_mir, fresnel_mir_i; float fresnel_tra, fresnel_tra_i; @@ -228,33 +219,6 @@ typedef struct Material { ListBase gpumaterial; /* runtime */ } Material; - -/* **************** GAME PROPERTIES ********************* */ -// Blend Transparency Options - alpha_blend /* match GPU_material::GPUBlendMode */ -#define GEMAT_SOLID 0 /* GPU_BLEND_SOLID */ -#define GEMAT_ADD 1 /* GPU_BLEND_ADD */ -#define GEMAT_ALPHA 2 /* GPU_BLEND_ALPHA */ -#define GEMAT_CLIP 4 /* GPU_BLEND_CLIP */ -#define GEMAT_ALPHA_SORT 8 /* GPU_BLEND_ALPHA_SORT */ -#define GEMAT_ALPHA_TO_COVERAGE 16 /* GPU_BLEND_ALPHA_TO_COVERAGE */ - -// Game Options - flag -#define GEMAT_BACKCULL 16 /* KX_BACKCULL */ -#define GEMAT_SHADED 32 /* KX_LIGHT */ -#define GEMAT_TEXT 64 /* RAS_RENDER_3DPOLYGON_TEXT */ -#define GEMAT_NOPHYSICS 128 -#define GEMAT_INVISIBLE 256 - -// Face Orientation Options - face_orientation -#define GEMAT_NORMAL 0 -#define GEMAT_HALO 512 /* BILLBOARD_SCREENALIGNED */ -#define GEMAT_BILLBOARD 1024 /* BILLBOARD_AXISALIGNED */ -#define GEMAT_SHADOW 2048 /* SHADOW */ - -// Use Textures - not defined directly in the UI -#define GEMAT_TEX 4096 /* KX_TEX */ - - /* **************** MATERIAL ********************* */ /* maximum number of materials per material array. diff --git a/source/blender/makesdna/DNA_object_force_types.h b/source/blender/makesdna/DNA_object_force_types.h index e7ebd3b72d7..16c96073469 100644 --- a/source/blender/makesdna/DNA_object_force_types.h +++ b/source/blender/makesdna/DNA_object_force_types.h @@ -218,59 +218,6 @@ typedef struct SBVertex { float vec[4]; } SBVertex; -typedef struct BulletSoftBody { - int flag; /* various boolean options */ - float linStiff; /* linear stiffness 0..1 */ - float angStiff; /* angular stiffness 0..1 */ - float volume; /* volume preservation 0..1 */ - - int viterations; /* Velocities solver iterations */ - int piterations; /* Positions solver iterations */ - int diterations; /* Drift solver iterations */ - int citerations; /* Cluster solver iterations */ - - float kSRHR_CL; /* Soft vs rigid hardness [0,1] (cluster only) */ - float kSKHR_CL; /* Soft vs kinetic hardness [0,1] (cluster only) */ - float kSSHR_CL; /* Soft vs soft hardness [0,1] (cluster only) */ - float kSR_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */ - - float kSK_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */ - float kSS_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */ - float kVCF; /* Velocities correction factor (Baumgarte) */ - float kDP; /* Damping coefficient [0,1] */ - - float kDG; /* Drag coefficient [0,+inf] */ - float kLF; /* Lift coefficient [0,+inf] */ - float kPR; /* Pressure coefficient [-inf,+inf] */ - float kVC; /* Volume conversation coefficient [0,+inf] */ - - float kDF; /* Dynamic friction coefficient [0,1] */ - float kMT; /* Pose matching coefficient [0,1] */ - float kCHR; /* Rigid contacts hardness [0,1] */ - float kKHR; /* Kinetic contacts hardness [0,1] */ - - float kSHR; /* Soft contacts hardness [0,1] */ - float kAHR; /* Anchors hardness [0,1] */ - int collisionflags; /* Vertex/Face or Signed Distance Field(SDF) or Clusters, Soft versus Soft or Rigid */ - int numclusteriterations; /* number of iterations to refine collision clusters*/ - float welding; /* welding limit to remove duplicate/nearby vertices, 0.0..0.01 */ - float margin; /* margin specific to softbody */ -} BulletSoftBody; - -/* BulletSoftBody.flag */ -#define OB_BSB_SHAPE_MATCHING 2 -// #define OB_BSB_UNUSED 4 -#define OB_BSB_BENDING_CONSTRAINTS 8 -#define OB_BSB_AERO_VPOINT 16 /* aero model, Vertex normals are oriented toward velocity*/ -// #define OB_BSB_AERO_VTWOSIDE 32 /* aero model, Vertex normals are flipped to match velocity */ - -/* BulletSoftBody.collisionflags */ -#define OB_BSB_COL_SDF_RS 2 /* SDF based rigid vs soft */ -#define OB_BSB_COL_CL_RS 4 /* Cluster based rigid vs soft */ -#define OB_BSB_COL_CL_SS 8 /* Cluster based soft vs soft */ -#define OB_BSB_COL_VF_SS 16 /* Vertex/Face based soft vs soft */ - - typedef struct SoftBody { /* dynamic data */ int totpoint, totspring; diff --git a/source/blender/makesdna/DNA_object_types.h b/source/blender/makesdna/DNA_object_types.h index 2cbc266ea0c..bb17b10b299 100644 --- a/source/blender/makesdna/DNA_object_types.h +++ b/source/blender/makesdna/DNA_object_types.h @@ -212,9 +212,7 @@ typedef struct Object { short transflag, protectflag; /* transformation settings and transform locks */ short trackflag, upflag; short nlaflag; /* used for DopeSheet filtering settings (expanded/collapsed) */ - short scaflag; /* ui state for game logic */ - char scavisflag; /* more display settings for game logic */ - char pad; + short pad[2]; /* did last modifier stack generation need mapping support? */ char lastNeedMapping; /* bool */ @@ -223,39 +221,9 @@ typedef struct Object { /* dupli-frame settings */ int dupon, dupoff, dupsta, dupend; - /* during realtime */ - - /* note that inertia is only called inertia for historical reasons - * and is not changed to avoid DNA surgery. It actually reflects the - * Size value in the GameButtons (= radius) */ - - float mass, damping, inertia; - /* The form factor k is introduced to give the user more control - * and to fix incompatibility problems. - * For rotational symmetric objects, the inertia value can be - * expressed as: Theta = k * m * r^2 - * where m = Mass, r = Radius - * For a Sphere, the form factor is by default = 0.4 - */ - - float formfactor; - float rdamping; - float margin; - float max_vel; /* clamp the maximum velocity 0.0 is disabled */ - float min_vel; /* clamp the minimum velocity 0.0 is disabled */ - float max_angvel; /* clamp the maximum angular velocity, 0.0 is disabled */ - float min_angvel; /* clamp the minimum angular velocity, 0.0 is disabled */ - float obstacleRad; - - /* "Character" physics properties */ - float step_height; - float jump_speed; - float fall_speed; - unsigned char max_jumps; - char pad2; - /* Depsgraph */ short base_flag; /* used by depsgraph, flushed from base */ + short pad8; /** Collision mask settings */ unsigned short col_group, col_mask; @@ -270,11 +238,6 @@ typedef struct Object { char empty_drawtype; float empty_drawsize; float dupfacesca; /* dupliface scale */ - - ListBase prop; /* game logic property list (not to be confused with IDProperties) */ - ListBase sensors; /* game logic sensors */ - ListBase controllers; /* game logic controllers */ - ListBase actuators; /* game logic actuators */ float sf; /* sf is time-offset */ @@ -284,25 +247,22 @@ typedef struct Object { unsigned char pad5[6]; float col[4]; /* object color */ - int gameflag; - int gameflag2; - char restrictflag; /* for restricting view, select, render etc. accessible in outliner */ char pad3; short softflag; /* softbody settings */ - float anisotropicFriction[3]; + float pad9[3]; ListBase constraints; /* object constraints */ ListBase nlastrips DNA_DEPRECATED; // XXX deprecated... old animation system ListBase hooks DNA_DEPRECATED; // XXX deprecated... old animation system ListBase particlesystem; /* particle systems */ - struct BulletSoftBody *bsoft; /* settings for game engine bullet soft body */ struct PartDeflect *pd; /* particle deflector/attractor/collision data */ struct SoftBody *soft; /* if exists, saved in file */ struct Group *dup_group; /* object duplicator for group */ + void *pad10; - char body_type; /* for now used to temporarily holds the type of collision object */ + char pad4; char shapeflag; /* flag for pinning */ short shapenr; /* current shape key for menu or pinned */ float smoothresh; /* smoothresh is phong interpolation ray_shadow correction in render */ @@ -313,8 +273,6 @@ typedef struct Object { void *pad7; uint64_t lastDataMask; /* the custom data layer mask that was last used to calculate derivedDeform and derivedFinal */ uint64_t customdata_mask; /* (extra) custom data layer mask to use for creating derivedmesh, set by depsgraph */ - unsigned int state; /* bit masks of game controllers that are active */ - unsigned int init_state; /* bit masks of initial state as recorded by the users */ /* Runtime valuated curve-specific data, not stored in the file */ struct CurveCache *curve_cache; @@ -476,8 +434,6 @@ enum { OB_NEGZ = 5, }; -/* gameflag in game.h */ - /* dt: no flags */ enum { OB_BOUNDBOX = 1, @@ -580,84 +536,6 @@ enum { /* collision masks */ #define OB_MAX_COL_MASKS 16 -/* ob->gameflag */ -enum { - OB_DYNAMIC = 1 << 0, - OB_CHILD = 1 << 1, - OB_ACTOR = 1 << 2, - OB_INERTIA_LOCK_X = 1 << 3, - OB_INERTIA_LOCK_Y = 1 << 4, - OB_INERTIA_LOCK_Z = 1 << 5, - OB_DO_FH = 1 << 6, - OB_ROT_FH = 1 << 7, - OB_ANISOTROPIC_FRICTION = 1 << 8, - OB_GHOST = 1 << 9, - OB_RIGID_BODY = 1 << 10, - OB_BOUNDS = 1 << 11, - - OB_COLLISION_RESPONSE = 1 << 12, - OB_SECTOR = 1 << 13, - OB_PROP = 1 << 14, - OB_MAINACTOR = 1 << 15, - - OB_COLLISION = 1 << 16, - OB_SOFT_BODY = 1 << 17, - OB_OCCLUDER = 1 << 18, - OB_SENSOR = 1 << 19, - OB_NAVMESH = 1 << 20, - OB_HASOBSTACLE = 1 << 21, - OB_CHARACTER = 1 << 22, - - OB_RECORD_ANIMATION = 1 << 23, -}; - -/* ob->gameflag2 */ -enum { - OB_NEVER_DO_ACTIVITY_CULLING = 1 << 0, - OB_LOCK_RIGID_BODY_X_AXIS = 1 << 2, - OB_LOCK_RIGID_BODY_Y_AXIS = 1 << 3, - OB_LOCK_RIGID_BODY_Z_AXIS = 1 << 4, - OB_LOCK_RIGID_BODY_X_ROT_AXIS = 1 << 5, - OB_LOCK_RIGID_BODY_Y_ROT_AXIS = 1 << 6, - OB_LOCK_RIGID_BODY_Z_ROT_AXIS = 1 << 7, - -/* OB_LIFE = OB_PROP | OB_DYNAMIC | OB_ACTOR | OB_MAINACTOR | OB_CHILD, */ -}; - -/* ob->body_type */ -enum { - OB_BODY_TYPE_NO_COLLISION = 0, - OB_BODY_TYPE_STATIC = 1, - OB_BODY_TYPE_DYNAMIC = 2, - OB_BODY_TYPE_RIGID = 3, - OB_BODY_TYPE_SOFT = 4, - OB_BODY_TYPE_OCCLUDER = 5, - OB_BODY_TYPE_SENSOR = 6, - OB_BODY_TYPE_NAVMESH = 7, - OB_BODY_TYPE_CHARACTER = 8, -}; - -/* ob->scavisflag */ -enum { - OB_VIS_SENS = 1 << 0, - OB_VIS_CONT = 1 << 1, - OB_VIS_ACT = 1 << 2, -}; - -/* ob->scaflag */ -enum { - OB_SHOWSENS = 1 << 6, - OB_SHOWACT = 1 << 7, - OB_ADDSENS = 1 << 8, - OB_ADDCONT = 1 << 9, - OB_ADDACT = 1 << 10, - OB_SHOWCONT = 1 << 11, - OB_ALLSTATE = 1 << 12, - OB_INITSTBIT = 1 << 13, - OB_DEBUGSTATE = 1 << 14, - OB_SHOWSTATE = 1 << 15, -}; - /* ob->restrictflag */ enum { OB_RESTRICT_VIEW = 1 << 0, diff --git a/source/blender/makesdna/DNA_property_types.h b/source/blender/makesdna/DNA_property_types.h deleted file mode 100644 index 77cd7c3e102..00000000000 --- a/source/blender/makesdna/DNA_property_types.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 DNA_property_types.h - * \ingroup DNA - * \since mar-2001 - * \author nzc - * \attention Renderrecipe and scene decription. The fact that there is a - * hierarchy here is a bit strange, and not desirable. - * - * #bProperty type is specifically for use by Objects game-logic. - */ - -#ifndef __DNA_PROPERTY_TYPES_H__ -#define __DNA_PROPERTY_TYPES_H__ - -/* ********************* PROPERTY ************************ */ - -typedef struct bProperty { - struct bProperty *next, *prev; - char name[64]; /* MAX_NAME */ - short type, flag; - int data; /* data should be 4 bytes to store int,float stuff */ - void *poin; /* references data unless its a string which is malloc'd */ - -} bProperty; - -/* property->type XXX Game Property, not RNA */ -#define GPROP_BOOL 0 -#define GPROP_INT 1 -#define GPROP_FLOAT 2 -#define GPROP_STRING 3 -// #define GPROP_VECTOR 4 // UNUSED -#define GPROP_TIME 5 - -/* property->flag */ -#define PROP_DEBUG 1 - -#define MAX_PROPSTRING 128 - -#endif /* __DNA_PROPERTY_TYPES_H__ */ diff --git a/source/blender/makesdna/DNA_scene_types.h b/source/blender/makesdna/DNA_scene_types.h index 3b7875ea5b1..db997aed1cb 100644 --- a/source/blender/makesdna/DNA_scene_types.h +++ b/source/blender/makesdna/DNA_scene_types.h @@ -745,13 +745,6 @@ typedef struct RenderData { short jp2_preset DNA_DEPRECATED, jp2_depth DNA_DEPRECATED; /*deprecated*/ int rpad3; - /* Dome variables */ // XXX deprecated since 2.5 - short domeres DNA_DEPRECATED, domemode DNA_DEPRECATED; // XXX deprecated since 2.5 - short domeangle DNA_DEPRECATED, dometilt DNA_DEPRECATED; // XXX deprecated since 2.5 - float domeresbuf DNA_DEPRECATED; // XXX deprecated since 2.5 - float pad2; - struct Text *dometext DNA_DEPRECATED; // XXX deprecated since 2.5 - /* Freestyle line thickness options */ int line_thickness_mode; float unit_line_thickness; /* in pixels */ @@ -803,180 +796,6 @@ typedef struct RenderProfile { } RenderProfile; -/* *************************************************************** */ -/* Game Engine - Dome */ - -typedef struct GameDome { - short res, mode; - short angle, tilt; - float resbuf, pad2; - struct Text *warptext; -} GameDome; - -/* GameDome.mode */ -#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 - -/* *************************************************************** */ -/* Game Engine */ - -typedef struct GameFraming { - float col[3]; - char type, pad1, pad2, pad3; -} GameFraming; - -/* GameFraming.type */ -#define SCE_GAMEFRAMING_BARS 0 -#define SCE_GAMEFRAMING_EXTEND 1 -#define SCE_GAMEFRAMING_SCALE 2 - -typedef struct RecastData { - float cellsize; - float cellheight; - float agentmaxslope; - float agentmaxclimb; - float agentheight; - float agentradius; - float edgemaxlen; - float edgemaxerror; - float regionminsize; - float regionmergesize; - int vertsperpoly; - float detailsampledist; - float detailsamplemaxerror; - char partitioning; - char pad1; - short pad2; -} RecastData; - -/* RecastData.partitioning */ -#define RC_PARTITION_WATERSHED 0 -#define RC_PARTITION_MONOTONE 1 -#define RC_PARTITION_LAYERS 2 - -typedef struct GameData { - - /* standalone player */ - struct GameFraming framing; - short playerflag, xplay, yplay, freqplay; - short depth, attrib, rt1, rt2; - short aasamples, pad4[3]; - - /* stereo/dome mode */ - struct GameDome dome; - short stereoflag, stereomode; - float eyeseparation; - RecastData recastData; - - - /* physics (it was in world)*/ - float gravity; /*Gravitation constant for the game world*/ - - /* - * Radius of the activity bubble, in Manhattan length. Objects - * outside the box are activity-culled. */ - float activityBoxRadius; - - /* - * bit 3: (gameengine): Activity culling is enabled. - * bit 5: (gameengine) : enable Bullet DBVT tree for view frustum culling - */ - int flag; - short mode, matmode; - short occlusionRes; /* resolution of occlusion Z buffer in pixel */ - short physicsEngine; - short exitkey; - short vsync; /* Controls vsync: off, on, or adaptive (if supported) */ - short ticrate, maxlogicstep, physubstep, maxphystep; - short obstacleSimulation; - short raster_storage; - float levelHeight; - float deactivationtime, lineardeactthreshold, angulardeactthreshold; - - /* Scene LoD */ - short lodflag, pad2; - int scehysteresis, pad5; - -} GameData; - -/* GameData.stereoflag */ -#define STEREO_NOSTEREO 1 -#define STEREO_ENABLED 2 -#define STEREO_DOME 3 - -/* GameData.stereomode */ -//#define STEREO_NOSTEREO 1 -#define STEREO_QUADBUFFERED 2 -#define STEREO_ABOVEBELOW 3 -#define STEREO_INTERLACED 4 -#define STEREO_ANAGLYPH 5 -#define STEREO_SIDEBYSIDE 6 -#define STEREO_VINTERLACE 7 -//#define STEREO_DOME 8 -#define STEREO_3DTVTOPBOTTOM 9 - -/* GameData.physicsEngine */ -#define WOPHY_NONE 0 -#define WOPHY_BULLET 5 - -/* obstacleSimulation */ -#define OBSTSIMULATION_NONE 0 -#define OBSTSIMULATION_TOI_rays 1 -#define OBSTSIMULATION_TOI_cells 2 - -/* GameData.raster_storage */ -#define RAS_STORE_AUTO 0 -/* #define RAS_STORE_IMMEDIATE 1 */ /* DEPRECATED */ -#define RAS_STORE_VA 2 -#define RAS_STORE_VBO 3 - -/* GameData.vsync */ -#define VSYNC_ON 0 -#define VSYNC_OFF 1 -#define VSYNC_ADAPTIVE 2 - -/* GameData.flag */ -#define GAME_RESTRICT_ANIM_UPDATES (1 << 0) -#define GAME_ENABLE_ALL_FRAMES (1 << 1) -#define GAME_SHOW_DEBUG_PROPS (1 << 2) -#define GAME_SHOW_FRAMERATE (1 << 3) -#define GAME_SHOW_PHYSICS (1 << 4) -// #define GAME_DISPLAY_LISTS (1 << 5) /* deprecated */ -#define GAME_GLSL_NO_LIGHTS (1 << 6) -#define GAME_GLSL_NO_SHADERS (1 << 7) -#define GAME_GLSL_NO_SHADOWS (1 << 8) -#define GAME_GLSL_NO_RAMPS (1 << 9) -#define GAME_GLSL_NO_NODES (1 << 10) -#define GAME_GLSL_NO_EXTRA_TEX (1 << 11) -#define GAME_IGNORE_DEPRECATION_WARNINGS (1 << 12) -#define GAME_ENABLE_ANIMATION_RECORD (1 << 13) -#define GAME_SHOW_MOUSE (1 << 14) -#define GAME_GLSL_NO_COLOR_MANAGEMENT (1 << 15) -#define GAME_SHOW_OBSTACLE_SIMULATION (1 << 16) -#define GAME_NO_MATERIAL_CACHING (1 << 17) -#define GAME_GLSL_NO_ENV_LIGHTING (1 << 18) -/* Note: GameData.flag is now an int (max 32 flags). A short could only take 16 flags */ - -/* GameData.playerflag */ -#define GAME_PLAYER_FULLSCREEN (1 << 0) -#define GAME_PLAYER_DESKTOP_RESOLUTION (1 << 1) - -/* GameData.matmode */ -enum { -#ifdef DNA_DEPRECATED - GAME_MAT_TEXFACE = 0, /* deprecated */ -#endif - GAME_MAT_MULTITEX = 1, - GAME_MAT_GLSL = 2, -}; - -/* GameData.lodflag */ -#define SCE_LOD_USE_HYST (1 << 0) - /* UV Paint */ /* ToolSettings.uv_sculpt_settings */ #define UV_SCULPT_LOCK_BORDERS 1 @@ -1678,10 +1497,6 @@ typedef struct Scene { /* User-Defined KeyingSets */ int active_keyingset; /* index of the active KeyingSet. first KeyingSet has index 1, 'none' active is 0, 'add new' is -1 */ ListBase keyingsets; /* KeyingSets for this scene */ - - /* Game Settings */ - struct GameFraming framing DNA_DEPRECATED; // XXX deprecated since 2.5 - struct GameData gm; /* Units */ struct UnitSettings unit; @@ -1716,8 +1531,6 @@ typedef struct Scene { IDProperty *collection_properties; /* settings to be overriden by layer collections */ IDProperty *layer_properties; /* settings to be override by workspaces */ - int pad5[2]; - ViewRender view_render; } Scene; @@ -1910,7 +1723,6 @@ enum { /* RenderData.engine (scene.c) */ extern const char *RE_engine_id_BLENDER_RENDER; -extern const char *RE_engine_id_BLENDER_GAME; extern const char *RE_engine_id_BLENDER_CLAY; extern const char *RE_engine_id_BLENDER_EEVEE; extern const char *RE_engine_id_BLENDER_WORKBENCH; diff --git a/source/blender/makesdna/DNA_sensor_types.h b/source/blender/makesdna/DNA_sensor_types.h deleted file mode 100644 index 37064854920..00000000000 --- a/source/blender/makesdna/DNA_sensor_types.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 DNA_sensor_types.h - * \ingroup DNA - * \since mar-2001 - * \author nzc - * - * #bSensor type is specifically for use by Object logic-bricks in the game-engine. - */ - -#ifndef __DNA_SENSOR_TYPES_H__ -#define __DNA_SENSOR_TYPES_H__ - -struct Object; -struct Material; - -/* ****************** SENSORS ********************* */ - -typedef struct bNearSensor { - char name[64]; /* MAX_NAME */ - float dist, resetdist; - int lastval, pad; -} bNearSensor; - -/** - * Defines the settings of a mouse sensor. - */ -typedef struct bMouseSensor { - /** - * The type of key this sensor listens to. - */ - short type; - short flag; - short pad1; - short mode; /* flag to choose material or property */ - char propname[64]; - char matname[64]; -} bMouseSensor; - -/* DEPRECATED */ -typedef struct bTouchSensor { - char name[64]; /* MAX_NAME */ - struct Material *ma; - float dist, pad; -} bTouchSensor; - -typedef struct bKeyboardSensor { - short key, qual; - short type, qual2; - /** - * Name of the target property - */ - char targetName[64]; /* MAX_NAME */ - /** - * Name of the toggle property - */ - char toggleName[64]; /* MAX_NAME */ -} bKeyboardSensor; - -typedef struct bPropertySensor { - int type; - int pad; - char name[64]; /* MAX_NAME */ - char value[64]; - char maxvalue[64]; -} bPropertySensor; - -typedef struct bActuatorSensor { - int type; - int pad; - char name[64]; /* MAX_NAME */ -} bActuatorSensor; - -typedef struct bDelaySensor { - short delay; - short duration; - short flag; - short pad; -} bDelaySensor; - -typedef struct bCollisionSensor { - char name[64]; /* property name. MAX_NAME */ - char materialName[64]; /* material */ - // struct Material *ma; // XXX remove materialName - short damptimer, damp; - short mode; /* flag to choose material or property */ - short pad2; -} bCollisionSensor; - -typedef struct bRadarSensor { - char name[64]; /* MAX_NAME */ - float angle; - float range; - short flag, axis; -} bRadarSensor; - -typedef struct bRandomSensor { - char name[64]; /* MAX_NAME */ - int seed; - int delay; -} bRandomSensor; - -typedef struct bRaySensor { - char name[64]; /* MAX_NAME */ - float range; - char propname[64]; - char matname[64]; - //struct Material *ma; // XXX remove materialName - short mode; - short pad1; - int axisflag; -} bRaySensor; - -typedef struct bArmatureSensor { - char posechannel[64]; /* MAX_NAME */ - char constraint[64]; /* MAX_NAME */ - int type; - float value; -} bArmatureSensor; - -typedef struct bMessageSensor { - /** - * (Possible future use) pointer to a single sender object - */ - struct Object *fromObject; - - /** - * Can be used to filter on subjects like this - */ - char subject[64]; - - /** - * (Possible future use) body to filter on - */ - char body[64]; -} bMessageSensor; - -typedef struct bSensor { - struct bSensor *next, *prev; - /* pulse and freq are the bool toggle and frame count for pulse mode */ - short type, otype, flag, pulse; - short freq, totlinks, pad1, pad2; /* freq makes reference to skipped ticks between 2 active pulses */ - char name[64]; /* MAX_NAME */ - void *data; - - struct bController **links; - - struct Object *ob; - - /* just add here, to avoid align errors... */ - short invert; /* Whether or not to invert the output. */ - short level; /* Whether the sensor is level base (edge by default) */ - short tap; - short pad; -} bSensor; - -typedef struct bJoystickSensor { - char name[64]; /* MAX_NAME */ - char type; - char joyindex; - short flag; - short axis; - short axis_single; - int axisf; - int button; - int hat; - int hatf; - int precision; -} bJoystickSensor; - -/* bMouseSensor->type: uses blender event defines */ - -/* bMouseSensor->flag: only pulse for now */ -#define SENS_MOUSE_FOCUS_PULSE 1 - -/* propertysensor->type */ -#define SENS_PROP_EQUAL 0 -#define SENS_PROP_NEQUAL 1 -#define SENS_PROP_INTERVAL 2 -#define SENS_PROP_CHANGED 3 -#define SENS_PROP_EXPRESSION 4 -#define SENS_PROP_LESSTHAN 5 -#define SENS_PROP_GREATERTHAN 6 - -/* raysensor->axisflag */ -/* flip x and y to make y default!!! */ -#define SENS_RAY_X_AXIS 1 -#define SENS_RAY_Y_AXIS 0 -#define SENS_RAY_Z_AXIS 2 -#define SENS_RAY_NEG_X_AXIS 3 -#define SENS_RAY_NEG_Y_AXIS 4 -#define SENS_RAY_NEG_Z_AXIS 5 -//#define SENS_RAY_NEGATIVE_AXIS 1 - -/* bRadarSensor->axis */ -#define SENS_RADAR_X_AXIS 0 -#define SENS_RADAR_Y_AXIS 1 -#define SENS_RADAR_Z_AXIS 2 -#define SENS_RADAR_NEG_X_AXIS 3 -#define SENS_RADAR_NEG_Y_AXIS 4 -#define SENS_RADAR_NEG_Z_AXIS 5 - -/* bMessageSensor->type */ -#define SENS_MESG_MESG 0 -#define SENS_MESG_PROP 1 - -/* bArmatureSensor->type */ -#define SENS_ARM_STATE_CHANGED 0 -#define SENS_ARM_LIN_ERROR_BELOW 1 -#define SENS_ARM_LIN_ERROR_ABOVE 2 -#define SENS_ARM_ROT_ERROR_BELOW 3 -#define SENS_ARM_ROT_ERROR_ABOVE 4 -/* update this when adding new type */ -#define SENS_ARM_MAXTYPE 4 - -/* sensor->type */ -#define SENS_ALWAYS 0 -#define SENS_TOUCH 1 /* DEPRECATED */ -#define SENS_NEAR 2 -#define SENS_KEYBOARD 3 -#define SENS_PROPERTY 4 -#define SENS_MOUSE 5 -#define SENS_COLLISION 6 -#define SENS_RADAR 7 -#define SENS_RANDOM 8 -#define SENS_RAY 9 -#define SENS_MESSAGE 10 -#define SENS_JOYSTICK 11 -#define SENS_ACTUATOR 12 -#define SENS_DELAY 13 -#define SENS_ARMATURE 14 -/* sensor->flag */ -#define SENS_SHOW 1 -#define SENS_DEL 2 -#define SENS_NEW 4 -#define SENS_NOT 8 -#define SENS_VISIBLE 16 -#define SENS_PIN 32 -#define SENS_DEACTIVATE 64 - -/* sensor->pulse */ -#define SENS_PULSE_CONT 0 -#define SENS_PULSE_REPEAT 1 -//#define SENS_PULSE_ONCE 2 -#define SENS_NEG_PULSE_MODE 4 - -/* sensor->suppress */ -#define SENS_SUPPRESS_POSITIVE (1 << 0) -#define SENS_SUPPRESS_NEGATIVE (1 << 1) - -/* collision, ray sensor modes: */ -/* A little bit fake: when property is active, the first bit is - * reset. Bite me :) So we don't actually use it, so we comment it out - * ... The reason for this is that we need to be backward compatible, - * and have a proper default value for this thing. - * */ -#define SENS_COLLISION_PROPERTY 0 -#define SENS_COLLISION_MATERIAL 1 -#define SENS_COLLISION_PULSE 2 - -/* ray specific mode */ -/* X-Ray means that the ray will traverse objects that don't have the property/material */ -#define SENS_RAY_PROPERTY 0 -#define SENS_RAY_MATERIAL 1 -#define SENS_RAY_XRAY 2 - -/* Some stuff for the mouse sensor Type: */ -#define BL_SENS_MOUSE_LEFT_BUTTON 1 -#define BL_SENS_MOUSE_MIDDLE_BUTTON 2 -#define BL_SENS_MOUSE_RIGHT_BUTTON 4 -#define BL_SENS_MOUSE_WHEEL_UP 5 -#define BL_SENS_MOUSE_WHEEL_DOWN 6 -#define BL_SENS_MOUSE_MOVEMENT 8 -#define BL_SENS_MOUSE_MOUSEOVER 16 -#define BL_SENS_MOUSE_MOUSEOVER_ANY 32 - -/* Joystick sensor - sorted by axis types */ -#define SENS_JOY_ANY_EVENT 1 - -#define SENS_JOY_BUTTON 0 /* axis type */ - -#define SENS_JOY_AXIS 1 /* axis type */ -#define SENS_JOY_X_AXIS 0 -#define SENS_JOY_Y_AXIS 1 -#define SENS_JOY_NEG_X_AXIS 2 -#define SENS_JOY_NEG_Y_AXIS 3 -#define SENS_JOY_PRECISION 4 - -#define SENS_JOY_HAT 2 /* axis type */ -#define SENS_JOY_HAT_DIR 0 -#define SENS_JOY_HAT_UP 1 -#define SENS_JOY_HAT_RIGHT 2 -#define SENS_JOY_HAT_DOWN 4 -#define SENS_JOY_HAT_LEFT 8 - -#define SENS_JOY_HAT_UP_RIGHT SENS_JOY_HAT_UP | SENS_JOY_HAT_RIGHT -#define SENS_JOY_HAT_DOWN_RIGHT SENS_JOY_HAT_DOWN | SENS_JOY_HAT_RIGHT -#define SENS_JOY_HAT_UP_LEFT SENS_JOY_HAT_UP | SENS_JOY_HAT_LEFT -#define SENS_JOY_HAT_DOWN_LEFT SENS_JOY_HAT_DOWN | SENS_JOY_HAT_LEFT - - -#define SENS_JOY_AXIS_SINGLE 3 /* axis type */ - - -#define SENS_DELAY_REPEAT 1 -// should match JOYINDEX_MAX in SCA_JoystickDefines.h */ -#define SENS_JOY_MAXINDEX 8 - -#endif /* __DNA_SENSOR_TYPES_H__ */ diff --git a/source/blender/makesdna/DNA_space_types.h b/source/blender/makesdna/DNA_space_types.h index 077ac4f7aa3..d763c7ca4f9 100644 --- a/source/blender/makesdna/DNA_space_types.h +++ b/source/blender/makesdna/DNA_space_types.h @@ -146,7 +146,7 @@ typedef struct SpaceButs { #define CONTEXT_SHADING 3 #define CONTEXT_EDITING 4 #define CONTEXT_SCRIPT 5 -#define CONTEXT_LOGIC 6 +//#define CONTEXT_LOGIC 6 /* sbuts->mainb old (deprecated) */ #ifdef DNA_DEPRECATED_ALLOW @@ -158,7 +158,7 @@ typedef struct SpaceButs { #define BUTS_WORLD 5 #define BUTS_RENDER 6 #define BUTS_EDIT 7 -#define BUTS_GAME 8 +// #define BUTS_GAME 8 #define BUTS_FPAINT 9 #define BUTS_RADIO 10 #define BUTS_SCRIPT 11 @@ -1243,23 +1243,6 @@ enum { SNODE_INSERTOFS_DIR_LEFT = 1, }; -/* Game Logic Editor ===================================== */ - -/* Logic Editor */ -typedef struct SpaceLogic { - SpaceLink *next, *prev; - ListBase regionbase; /* storage of regions for inactive spaces */ - int spacetype; - float blockscale DNA_DEPRECATED; - - short blockhandler[8] DNA_DEPRECATED; - - short flag, scaflag; - int pad; - - struct bGPdata *gpd; /* grease-pencil data */ -} SpaceLogic; - /* Console ================================================ */ /* Console content */ @@ -1432,7 +1415,7 @@ typedef enum eSpace_Type { SPACE_SCRIPT = 14, /* Deprecated */ SPACE_TIME = 15, SPACE_NODE = 16, - SPACE_LOGIC = 17, + SPACE_LOGIC = 17, /* deprecated */ SPACE_CONSOLE = 18, SPACE_USERPREF = 19, SPACE_CLIP = 20, diff --git a/source/blender/makesdna/DNA_userdef_types.h b/source/blender/makesdna/DNA_userdef_types.h index 3da0bdb6ca2..1eb17b49cfd 100644 --- a/source/blender/makesdna/DNA_userdef_types.h +++ b/source/blender/makesdna/DNA_userdef_types.h @@ -397,7 +397,6 @@ typedef struct bTheme { ThemeSpace toops; ThemeSpace ttime; ThemeSpace tnode; - ThemeSpace tlogic; ThemeSpace tuserpref; ThemeSpace tconsole; ThemeSpace tclip; @@ -466,7 +465,7 @@ typedef struct UserDef { short versions; short dbl_click_time; - short gameflags; + short pad; short wheellinescroll; int uiflag; /* eUserpref_UI_Flag */ int uiflag2; /* eUserpref_UI_Flag2 */ @@ -568,7 +567,7 @@ typedef struct UserDef { float gpencil_new_layer_col[4]; /* default color for newly created Grease Pencil layers */ short tweak_threshold; - char navigation_mode, pad; + char navigation_mode, pad10; char author[80]; /* author name for file formats supporting it */ @@ -787,15 +786,6 @@ typedef enum eDupli_ID_Flags { USER_DUP_PSYS = (1 << 11) } eDupli_ID_Flags; -/* UserDef.gameflags */ -typedef enum eOpenGL_RenderingOptions { - USER_GL_RENDER_DEPRECATED_0 = (1 << 0), - USER_GL_RENDER_DEPRECATED_1 = (1 << 1), - USER_DISABLE_MIPMAP = (1 << 2), - USER_GL_RENDER_DEPRECATED_3 = (1 << 3), - USER_GL_RENDER_DEPRECATED_4 = (1 << 4), -} eOpenGL_RenderingOptions; - /* selection method for opengl gpu_select_method */ typedef enum eOpenGL_SelectOptions { USER_SELECT_AUTO = 0, diff --git a/source/blender/makesdna/DNA_view3d_types.h b/source/blender/makesdna/DNA_view3d_types.h index 619f9fd4f6e..cc0389ec568 100644 --- a/source/blender/makesdna/DNA_view3d_types.h +++ b/source/blender/makesdna/DNA_view3d_types.h @@ -270,7 +270,7 @@ typedef struct View3D { #define RV3D_CLIPPING 4 #define RV3D_NAVIGATING 8 #define RV3D_GPULIGHT_UPDATE 16 -#define RV3D_IS_GAME_ENGINE 32 /* runtime flag, used to check if LoD's should be used */ +/*#define RV3D_IS_GAME_ENGINE 32 *//* UNUSED */ /** * Disable zbuffer offset, skip calls to #ED_view3d_polygon_offset. * Use when precise surface depth is needed and picking bias isn't, see T45434). diff --git a/source/blender/makesdna/DNA_world_types.h b/source/blender/makesdna/DNA_world_types.h index 3361e50e257..f30ffa84b73 100644 --- a/source/blender/makesdna/DNA_world_types.h +++ b/source/blender/makesdna/DNA_world_types.h @@ -47,8 +47,7 @@ struct MTex; /** * World defines general modeling data such as a background fill, - * gravity, color model etc. It mixes game-data, rendering - * data and modeling data. */ + * gravity, color model etc. It mixes rendering data and modeling data. */ typedef struct World { ID id; struct AnimData *adt; /* animation data (must be immediately after id for utilities to use it) */ @@ -67,16 +66,6 @@ typedef struct World { */ float exposure, exp, range; float linfac, logfac; - - /** - * Gravitation constant for the game world - */ - float gravity; // XXX moved to scene->gamedata in 2.5 - - /** - * Radius of the activity bubble, in Manhattan length. Objects - * outside the box are activity-culled. */ - float activityBoxRadius; // XXX moved to scene->gamedata in 2.5 short skytype; /** @@ -89,16 +78,10 @@ typedef struct World { * bit 5: (gameengine) : enable Bullet DBVT tree for view frustum culling */ short mode; // partially moved to scene->gamedata in 2.5 - short occlusionRes; /* resolution of occlusion Z buffer in pixel */ // XXX moved to scene->gamedata in 2.5 - short physicsEngine; /* here it's aligned */ // XXX moved to scene->gamedata in 2.5 - short ticrate, maxlogicstep, physubstep, maxphystep; // XXX moved to scene->gamedata in 2.5 - + short pad2[2]; + float misi, miststa, mistdist, misthi; - - float starr DNA_DEPRECATED, starg DNA_DEPRECATED, starb DNA_DEPRECATED, stark DNA_DEPRECATED; /* Deprecated */ - float starsize DNA_DEPRECATED, starmindist DNA_DEPRECATED; - float stardist DNA_DEPRECATED, starcolnoise DNA_DEPRECATED; - + /* unused now: DOF */ short dofsta, dofend, dofmin, dofmax; @@ -147,9 +130,9 @@ typedef struct World { #define WO_MIST 1 //#define WO_STARS 2 /* deprecated */ /*#define WO_DOF 4*/ -#define WO_ACTIVITY_CULLING 8 +//#define WO_ACTIVITY_CULLING 8 /* deprecated */ #define WO_ENV_LIGHT 16 -#define WO_DBVT_CULLING 32 +//#define WO_DBVT_CULLING 32 /* deprecated */ #define WO_AMB_OCC 64 #define WO_INDIRECT_LIGHT 128 diff --git a/source/blender/makesdna/intern/makesdna.c b/source/blender/makesdna/intern/makesdna.c index f0f1c2210f0..d276e2c0859 100644 --- a/source/blender/makesdna/intern/makesdna.c +++ b/source/blender/makesdna/intern/makesdna.c @@ -100,10 +100,6 @@ static const char *includefiles[] = { "DNA_sequence_types.h", "DNA_effect_types.h", "DNA_outliner_types.h", - "DNA_property_types.h", - "DNA_sensor_types.h", - "DNA_controller_types.h", - "DNA_actuator_types.h", "DNA_sound_types.h", "DNA_group_types.h", "DNA_armature_types.h", @@ -1327,10 +1323,6 @@ int main(int argc, char **argv) #include "DNA_sequence_types.h" #include "DNA_effect_types.h" #include "DNA_outliner_types.h" -#include "DNA_property_types.h" -#include "DNA_sensor_types.h" -#include "DNA_controller_types.h" -#include "DNA_actuator_types.h" #include "DNA_sound_types.h" #include "DNA_group_types.h" #include "DNA_armature_types.h" diff --git a/source/blender/makesrna/RNA_access.h b/source/blender/makesrna/RNA_access.h index 562855c01cc..d991e28a648 100644 --- a/source/blender/makesrna/RNA_access.h +++ b/source/blender/makesrna/RNA_access.h @@ -277,14 +277,6 @@ extern StructRNA RNA_GPencilStroke; extern StructRNA RNA_GPencilStrokePoint; extern StructRNA RNA_GPencilSculptSettings; extern StructRNA RNA_GPencilSculptBrush; -extern StructRNA RNA_GameBooleanProperty; -extern StructRNA RNA_GameFloatProperty; -extern StructRNA RNA_GameIntProperty; -extern StructRNA RNA_GameObjectSettings; -extern StructRNA RNA_GameProperty; -extern StructRNA RNA_GameSoftBodySettings; -extern StructRNA RNA_GameStringProperty; -extern StructRNA RNA_GameTimerProperty; extern StructRNA RNA_GaussianBlurSequence; extern StructRNA RNA_GlowSequence; extern StructRNA RNA_GreasePencil; @@ -521,7 +513,6 @@ extern StructRNA RNA_RigidBodyObject; extern StructRNA RNA_RigidBodyJointConstraint; extern StructRNA RNA_SPHFluidSettings; extern StructRNA RNA_Scene; -extern StructRNA RNA_SceneGameData; extern StructRNA RNA_SceneRenderLayer; extern StructRNA RNA_SceneSequence; extern StructRNA RNA_SceneObjects; @@ -591,7 +582,6 @@ extern StructRNA RNA_SpaceFileBrowser; extern StructRNA RNA_SpaceGraphEditor; extern StructRNA RNA_SpaceImageEditor; extern StructRNA RNA_SpaceInfo; -extern StructRNA RNA_SpaceLogicEditor; extern StructRNA RNA_SpaceNLA; extern StructRNA RNA_SpaceNodeEditor; extern StructRNA RNA_SpaceOutliner; diff --git a/source/blender/makesrna/RNA_enum_types.h b/source/blender/makesrna/RNA_enum_types.h index 345c47ae1bf..0c0a22cc467 100644 --- a/source/blender/makesrna/RNA_enum_types.h +++ b/source/blender/makesrna/RNA_enum_types.h @@ -165,8 +165,6 @@ extern const EnumPropertyItem rna_enum_property_type_items[]; extern const EnumPropertyItem rna_enum_property_subtype_items[]; extern const EnumPropertyItem rna_enum_property_unit_items[]; -extern const EnumPropertyItem rna_enum_gameproperty_type_items[]; - extern const EnumPropertyItem rna_enum_viewport_shade_items[]; extern const EnumPropertyItem rna_enum_navigation_mode_items[]; diff --git a/source/blender/makesrna/intern/CMakeLists.txt b/source/blender/makesrna/intern/CMakeLists.txt index 74c36c456b0..5e815e16a82 100644 --- a/source/blender/makesrna/intern/CMakeLists.txt +++ b/source/blender/makesrna/intern/CMakeLists.txt @@ -32,7 +32,6 @@ endif() set(DEFSRC rna_ID.c rna_action.c - rna_actuator.c rna_animation.c rna_animviz.c rna_armature.c @@ -44,7 +43,6 @@ set(DEFSRC rna_color.c rna_constraint.c rna_context.c - rna_controller.c rna_curve.c rna_depsgraph.c rna_dynamicpaint.c @@ -74,14 +72,12 @@ set(DEFSRC rna_particle.c rna_pose.c rna_lightprobe.c - rna_property.c rna_render.c rna_rigidbody.c rna_rna.c rna_scene.c rna_screen.c rna_sculpt_paint.c - rna_sensor.c rna_sequencer.c rna_smoke.c rna_sound.c @@ -103,11 +99,9 @@ set(DEFSRC set(APISRC rna_action_api.c - rna_actuator_api.c rna_animation_api.c rna_armature_api.c rna_camera_api.c - rna_controller_api.c rna_curve_api.c rna_fcurve_api.c rna_image_api.c @@ -120,7 +114,6 @@ set(APISRC rna_object_api.c rna_pose_api.c rna_scene_api.c - rna_sensor_api.c rna_sequencer_api.c rna_sound_api.c rna_space_api.c @@ -193,10 +186,6 @@ if(WITH_PYTHON) ) endif() -if(WITH_GAMEENGINE) - add_definitions(-DWITH_GAMEENGINE) -endif() - if(WITH_CLAY_ENGINE) add_definitions(-DWITH_CLAY_ENGINE) endif() diff --git a/source/blender/makesrna/intern/makesrna.c b/source/blender/makesrna/intern/makesrna.c index 9745ca39872..40028eec4c8 100644 --- a/source/blender/makesrna/intern/makesrna.c +++ b/source/blender/makesrna/intern/makesrna.c @@ -3350,7 +3350,6 @@ static RNAProcessItem PROCESS_ITEMS[] = { {"rna_action.c", "rna_action_api.c", RNA_def_action}, {"rna_animation.c", "rna_animation_api.c", RNA_def_animation}, {"rna_animviz.c", NULL, RNA_def_animviz}, - {"rna_actuator.c", "rna_actuator_api.c", RNA_def_actuator}, {"rna_armature.c", "rna_armature_api.c", RNA_def_armature}, {"rna_boid.c", NULL, RNA_def_boid}, {"rna_brush.c", NULL, RNA_def_brush}, @@ -3360,7 +3359,6 @@ static RNAProcessItem PROCESS_ITEMS[] = { {"rna_color.c", NULL, RNA_def_color}, {"rna_constraint.c", NULL, RNA_def_constraint}, {"rna_context.c", NULL, RNA_def_context}, - {"rna_controller.c", "rna_controller_api.c", RNA_def_controller}, {"rna_curve.c", "rna_curve_api.c", RNA_def_curve}, {"rna_dynamicpaint.c", NULL, RNA_def_dynamic_paint}, {"rna_fcurve.c", "rna_fcurve_api.c", RNA_def_fcurve}, @@ -3388,13 +3386,11 @@ static RNAProcessItem PROCESS_ITEMS[] = { {"rna_particle.c", NULL, RNA_def_particle}, {"rna_pose.c", "rna_pose_api.c", RNA_def_pose}, {"rna_lightprobe.c", NULL, RNA_def_lightprobe}, - {"rna_property.c", NULL, RNA_def_gameproperty}, {"rna_render.c", NULL, RNA_def_render}, {"rna_rigidbody.c", NULL, RNA_def_rigidbody}, {"rna_scene.c", "rna_scene_api.c", RNA_def_scene}, {"rna_screen.c", NULL, RNA_def_screen}, {"rna_sculpt_paint.c", NULL, RNA_def_sculpt_paint}, - {"rna_sensor.c", "rna_sensor_api.c", RNA_def_sensor}, {"rna_sequencer.c", "rna_sequencer_api.c", RNA_def_sequencer}, {"rna_smoke.c", NULL, RNA_def_smoke}, {"rna_space.c", "rna_space_api.c", RNA_def_space}, diff --git a/source/blender/makesrna/intern/rna_actuator.c b/source/blender/makesrna/intern/rna_actuator.c deleted file mode 100644 index 26ec813a14f..00000000000 --- a/source/blender/makesrna/intern/rna_actuator.c +++ /dev/null @@ -1,2220 +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): Blender Foundation (2008). - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file blender/makesrna/intern/rna_actuator.c - * \ingroup RNA - */ - - -#include - -#include "DNA_constraint_types.h" -#include "DNA_object_types.h" -#include "DNA_actuator_types.h" -#include "DNA_scene_types.h" /* for MAXFRAME */ - -#include "BLI_math.h" -#include "BLI_string_utils.h" -#include "BLI_utildefines.h" - -#include "BLT_translation.h" - -#include "RNA_define.h" -#include "RNA_access.h" -#include "RNA_enum_types.h" - -#include "rna_internal.h" - -#include "WM_types.h" - -/* Always keep in alphabetical order */ -static const EnumPropertyItem actuator_type_items[] = { - {ACT_ACTION, "ACTION", 0, "Action", ""}, - {ACT_ARMATURE, "ARMATURE", 0, "Armature", ""}, - {ACT_CAMERA, "CAMERA", 0, "Camera", ""}, - {ACT_CONSTRAINT, "CONSTRAINT", 0, "Constraint", ""}, - {ACT_EDIT_OBJECT, "EDIT_OBJECT", 0, "Edit Object", ""}, - {ACT_2DFILTER, "FILTER_2D", 0, "Filter 2D", ""}, - {ACT_GAME, "GAME", 0, "Game", ""}, - {ACT_MESSAGE, "MESSAGE", 0, "Message", ""}, - {ACT_OBJECT, "MOTION", 0, "Motion", ""}, - {ACT_MOUSE, "MOUSE", 0, "Mouse", ""}, - {ACT_PARENT, "PARENT", 0, "Parent", ""}, - {ACT_PROPERTY, "PROPERTY", 0, "Property", ""}, - {ACT_RANDOM, "RANDOM", 0, "Random", ""}, - {ACT_SCENE, "SCENE", 0, "Scene", ""}, - {ACT_SOUND, "SOUND", 0, "Sound", ""}, - {ACT_STATE, "STATE", 0, "State", ""}, - {ACT_STEERING, "STEERING", 0, "Steering", ""}, - {ACT_VISIBILITY, "VISIBILITY", 0, "Visibility", ""}, - {0, NULL, 0, NULL, NULL} -}; - -#ifdef RNA_RUNTIME - -#include "BKE_sca.h" - -static StructRNA *rna_Actuator_refine(struct PointerRNA *ptr) -{ - bActuator *actuator = (bActuator *)ptr->data; - - switch (actuator->type) { - case ACT_ACTION: - return &RNA_ActionActuator; - case ACT_OBJECT: - return &RNA_ObjectActuator; - case ACT_CAMERA: - return &RNA_CameraActuator; - case ACT_SOUND: - return &RNA_SoundActuator; - case ACT_PROPERTY: - return &RNA_PropertyActuator; - case ACT_CONSTRAINT: - return &RNA_ConstraintActuator; - case ACT_EDIT_OBJECT: - return &RNA_EditObjectActuator; - case ACT_SCENE: - return &RNA_SceneActuator; - case ACT_RANDOM: - return &RNA_RandomActuator; - case ACT_MESSAGE: - return &RNA_MessageActuator; - case ACT_GAME: - return &RNA_GameActuator; - case ACT_VISIBILITY: - return &RNA_VisibilityActuator; - case ACT_2DFILTER: - return &RNA_Filter2DActuator; - case ACT_PARENT: - return &RNA_ParentActuator; - case ACT_STATE: - return &RNA_StateActuator; - case ACT_ARMATURE: - return &RNA_ArmatureActuator; - case ACT_STEERING: - return &RNA_SteeringActuator; - case ACT_MOUSE: - return &RNA_MouseActuator; - default: - return &RNA_Actuator; - } -} - -static void rna_Actuator_name_set(PointerRNA *ptr, const char *value) -{ - Object *ob = ptr->id.data; - bActuator *act = ptr->data; - BLI_strncpy_utf8(act->name, value, sizeof(act->name)); - BLI_uniquename(&ob->actuators, act, DATA_("Actuator"), '.', offsetof(bActuator, name), sizeof(act->name)); -} - -static void rna_Actuator_type_set(struct PointerRNA *ptr, int value) -{ - bActuator *act = (bActuator *)ptr->data; - - if (value != act->type) { - act->type = value; - init_actuator(act); - } -} - -static void rna_ConstraintActuator_type_set(struct PointerRNA *ptr, int value) -{ - bActuator *act = (bActuator *)ptr->data; - bConstraintActuator *ca = act->data; - - if (value != ca->type) { - ca->type = value; - switch (ca->type) { - case ACT_CONST_TYPE_ORI: - /* negative axis not supported in the orientation mode */ - if (ELEM(ca->mode, ACT_CONST_DIRNX, ACT_CONST_DIRNY, ACT_CONST_DIRNZ)) - ca->mode = ACT_CONST_NONE; - break; - - case ACT_CONST_TYPE_LOC: - case ACT_CONST_TYPE_DIST: - case ACT_CONST_TYPE_FH: - default: - break; - } - } -} - -static float rna_ConstraintActuator_limitmin_get(struct PointerRNA *ptr) -{ - bActuator *act = (bActuator *)ptr->data; - bConstraintActuator *ca = act->data; - float *fp; - - if (ca->flag & ACT_CONST_LOCX) fp = ca->minloc; - else if (ca->flag & ACT_CONST_LOCY) fp = ca->minloc + 1; - else if (ca->flag & ACT_CONST_LOCZ) fp = ca->minloc + 2; - else if (ca->flag & ACT_CONST_ROTX) fp = ca->minrot; - else if (ca->flag & ACT_CONST_ROTY) fp = ca->minrot + 1; - else fp = ca->minrot + 2; - - return *fp; -} - -static void rna_ConstraintActuator_limitmin_set(struct PointerRNA *ptr, float value) -{ - bActuator *act = (bActuator *)ptr->data; - bConstraintActuator *ca = act->data; - float *fp; - - if (ca->flag & ACT_CONST_LOCX) fp = ca->minloc; - else if (ca->flag & ACT_CONST_LOCY) fp = ca->minloc + 1; - else if (ca->flag & ACT_CONST_LOCZ) fp = ca->minloc + 2; - else if (ca->flag & ACT_CONST_ROTX) fp = ca->minrot; - else if (ca->flag & ACT_CONST_ROTY) fp = ca->minrot + 1; - else fp = ca->minrot + 2; - - *fp = value; -} - -static float rna_ConstraintActuator_limitmax_get(struct PointerRNA *ptr) -{ - bActuator *act = (bActuator *)ptr->data; - bConstraintActuator *ca = act->data; - float *fp; - - if (ca->flag & ACT_CONST_LOCX) fp = ca->maxloc; - else if (ca->flag & ACT_CONST_LOCY) fp = ca->maxloc + 1; - else if (ca->flag & ACT_CONST_LOCZ) fp = ca->maxloc + 2; - else if (ca->flag & ACT_CONST_ROTX) fp = ca->maxrot; - else if (ca->flag & ACT_CONST_ROTY) fp = ca->maxrot + 1; - else fp = ca->maxrot + 2; - - return *fp; -} - -static void rna_ConstraintActuator_limitmax_set(struct PointerRNA *ptr, float value) -{ - bActuator *act = (bActuator *)ptr->data; - bConstraintActuator *ca = act->data; - float *fp; - - if (ca->flag & ACT_CONST_LOCX) fp = ca->maxloc; - else if (ca->flag & ACT_CONST_LOCY) fp = ca->maxloc + 1; - else if (ca->flag & ACT_CONST_LOCZ) fp = ca->maxloc + 2; - else if (ca->flag & ACT_CONST_ROTX) fp = ca->maxrot; - else if (ca->flag & ACT_CONST_ROTY) fp = ca->maxrot + 1; - else fp = ca->maxrot + 2; - - *fp = value; -} - -static float rna_ConstraintActuator_distance_get(struct PointerRNA *ptr) -{ - bActuator *act = (bActuator *)ptr->data; - bConstraintActuator *ca = act->data; - float *fp; - - if (ca->mode & (ACT_CONST_DIRPX | ACT_CONST_DIRNX)) fp = ca->minloc; - else if (ca->mode & (ACT_CONST_DIRPY | ACT_CONST_DIRNY)) fp = ca->minloc + 1; - else fp = ca->minloc + 2; - - return *fp; -} - -static void rna_ConstraintActuator_distance_set(struct PointerRNA *ptr, float value) -{ - bActuator *act = (bActuator *)ptr->data; - bConstraintActuator *ca = act->data; - float *fp; - - if (ca->mode & (ACT_CONST_DIRPX | ACT_CONST_DIRNX)) fp = ca->minloc; - else if (ca->mode & (ACT_CONST_DIRPY | ACT_CONST_DIRNY)) fp = ca->minloc + 1; - else fp = ca->minloc + 2; - - *fp = value; -} - -static float rna_ConstraintActuator_range_get(struct PointerRNA *ptr) -{ - bActuator *act = (bActuator *)ptr->data; - bConstraintActuator *ca = act->data; - float *fp; - - if (ca->mode & (ACT_CONST_DIRPX | ACT_CONST_DIRNX)) fp = ca->maxloc; - else if (ca->mode & (ACT_CONST_DIRPY | ACT_CONST_DIRNY)) fp = ca->maxloc + 1; - else fp = ca->maxloc + 2; - - return *fp; -} - -static void rna_ConstraintActuator_range_set(struct PointerRNA *ptr, float value) -{ - bActuator *act = (bActuator *)ptr->data; - bConstraintActuator *ca = act->data; - float *fp; - - if (ca->mode & (ACT_CONST_DIRPX | ACT_CONST_DIRNX)) fp = ca->maxloc; - else if (ca->mode & (ACT_CONST_DIRPY | ACT_CONST_DIRNY)) fp = ca->maxloc + 1; - else fp = ca->maxloc + 2; - - *fp = value; -} - -static float rna_ConstraintActuator_fhheight_get(struct PointerRNA *ptr) -{ - bActuator *act = (bActuator *)ptr->data; - bConstraintActuator *ca = act->data; - float *fp; - - if (ca->mode & (ACT_CONST_DIRPX | ACT_CONST_DIRNX)) fp = ca->minloc; - else if (ca->mode & (ACT_CONST_DIRPY | ACT_CONST_DIRNY)) fp = ca->minloc + 1; - else fp = ca->minloc + 2; - - return *fp; -} - -static void rna_ConstraintActuator_fhheight_set(struct PointerRNA *ptr, float value) -{ - bActuator *act = (bActuator *)ptr->data; - bConstraintActuator *ca = act->data; - float *fp; - - if (ca->mode & (ACT_CONST_DIRPX | ACT_CONST_DIRNX)) fp = ca->minloc; - else if (ca->mode & (ACT_CONST_DIRPY | ACT_CONST_DIRNY)) fp = ca->minloc + 1; - else fp = ca->minloc + 2; - - *fp = value; -} - -static float rna_ConstraintActuator_spring_get(struct PointerRNA *ptr) -{ - bActuator *act = (bActuator *)ptr->data; - bConstraintActuator *ca = act->data; - float *fp; - - if (ca->mode & (ACT_CONST_DIRPX | ACT_CONST_DIRNX)) fp = ca->maxloc; - else if (ca->mode & (ACT_CONST_DIRPY | ACT_CONST_DIRNY)) fp = ca->maxloc + 1; - else fp = ca->maxloc + 2; - - return *fp; -} - -static void rna_ConstraintActuator_spring_set(struct PointerRNA *ptr, float value) -{ - bActuator *act = (bActuator *)ptr->data; - bConstraintActuator *ca = act->data; - float *fp; - - if (ca->mode & (ACT_CONST_DIRPX | ACT_CONST_DIRNX)) fp = ca->maxloc; - else if (ca->mode & (ACT_CONST_DIRPY | ACT_CONST_DIRNY)) fp = ca->maxloc + 1; - else fp = ca->maxloc + 2; - - *fp = value; -} -/* ConstraintActuator uses the same property for Material and Property. - * Therefore we need to clear the property when "use_material_detect" mode changes */ -static void rna_Actuator_constraint_detect_material_set(struct PointerRNA *ptr, int value) -{ - bActuator *act = (bActuator *)ptr->data; - bConstraintActuator *ca = act->data; - - short old_value = (ca->flag & ACT_CONST_MATERIAL) ? 1 : 0; - - if (old_value != value) { - ca->flag ^= ACT_CONST_MATERIAL; - ca->matprop[0] = '\0'; - } -} - -static void rna_ActionActuator_add_set(struct PointerRNA *ptr, int value) -{ - bActuator *act = (bActuator *)ptr->data; - bActionActuator *aa = act->data; - - if (value == 1) { - aa->flag &= ~ACT_IPOFORCE; - aa->flag |= ACT_IPOADD; - } - else { - aa->flag &= ~ACT_IPOADD; - } -} - -static void rna_ActionActuator_force_set(struct PointerRNA *ptr, int value) -{ - bActuator *act = (bActuator *)ptr->data; - bActionActuator *aa = act->data; - - if (value == 1) { - aa->flag &= ~ACT_IPOADD; - aa->flag |= ACT_IPOFORCE; - } - else { - aa->flag &= ~ACT_IPOFORCE; - } -} - -static void rna_ObjectActuator_type_set(struct PointerRNA *ptr, int value) -{ - bActuator *act = (bActuator *)ptr->data; - bObjectActuator *oa = act->data; - if (value != oa->type) { - oa->type = value; - switch (oa->type) { - case ACT_OBJECT_NORMAL: - memset(oa, 0, sizeof(bObjectActuator)); - oa->flag = ACT_FORCE_LOCAL | ACT_TORQUE_LOCAL | ACT_DLOC_LOCAL | ACT_DROT_LOCAL; - oa->type = ACT_OBJECT_NORMAL; - break; - - case ACT_OBJECT_SERVO: - memset(oa, 0, sizeof(bObjectActuator)); - oa->flag = ACT_LIN_VEL_LOCAL; - oa->type = ACT_OBJECT_SERVO; - oa->forcerot[0] = 30.0f; - oa->forcerot[1] = 0.5f; - oa->forcerot[2] = 0.0f; - break; - - case ACT_OBJECT_CHARACTER: - memset(oa, 0, sizeof(bObjectActuator)); - oa->flag = ACT_DLOC_LOCAL | ACT_DROT_LOCAL; - oa->type = ACT_OBJECT_CHARACTER; - break; - } - } -} - -static void rna_ObjectActuator_integralcoefficient_set(struct PointerRNA *ptr, float value) -{ - bActuator *act = (bActuator *)ptr->data; - bObjectActuator *oa = act->data; - - oa->forcerot[1] = value; - oa->forcerot[0] = 60.0f * oa->forcerot[1]; -} - -static void rna_StateActuator_state_set(PointerRNA *ptr, const int *values) -{ - bActuator *act = (bActuator *)ptr->data; - bStateActuator *sa = act->data; - - int i, tot = 0; - - /* ensure we always have some state selected */ - for (i = 0; i < OB_MAX_STATES; i++) - if (values[i]) - tot++; - - if (tot == 0) - return; - - for (i = 0; i < OB_MAX_STATES; i++) { - if (values[i]) sa->mask |= (1 << i); - else sa->mask &= ~(1 << i); - } -} - -/* Always keep in alphabetical order */ -const EnumPropertyItem *rna_Actuator_type_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free) -{ - EnumPropertyItem *item = NULL; - Object *ob = NULL; - int totitem = 0; - - if (ptr->type == &RNA_Actuator || RNA_struct_is_a(ptr->type, &RNA_Actuator)) { - ob = (Object *)ptr->id.data; - } - else { - /* can't use ob from ptr->id.data because that enum is also used by operators */ - ob = CTX_data_active_object(C); - } - - if (ob != NULL) { - if (ob->type == OB_ARMATURE) { - RNA_enum_items_add_value(&item, &totitem, actuator_type_items, ACT_ARMATURE); - } - } - - RNA_enum_items_add_value(&item, &totitem, actuator_type_items, ACT_ACTION); - RNA_enum_items_add_value(&item, &totitem, actuator_type_items, ACT_CAMERA); - RNA_enum_items_add_value(&item, &totitem, actuator_type_items, ACT_CONSTRAINT); - RNA_enum_items_add_value(&item, &totitem, actuator_type_items, ACT_EDIT_OBJECT); - RNA_enum_items_add_value(&item, &totitem, actuator_type_items, ACT_2DFILTER); - RNA_enum_items_add_value(&item, &totitem, actuator_type_items, ACT_GAME); - RNA_enum_items_add_value(&item, &totitem, actuator_type_items, ACT_MESSAGE); - RNA_enum_items_add_value(&item, &totitem, actuator_type_items, ACT_MOUSE); - RNA_enum_items_add_value(&item, &totitem, actuator_type_items, ACT_OBJECT); - RNA_enum_items_add_value(&item, &totitem, actuator_type_items, ACT_PARENT); - RNA_enum_items_add_value(&item, &totitem, actuator_type_items, ACT_PROPERTY); - RNA_enum_items_add_value(&item, &totitem, actuator_type_items, ACT_RANDOM); - RNA_enum_items_add_value(&item, &totitem, actuator_type_items, ACT_SCENE); - RNA_enum_items_add_value(&item, &totitem, actuator_type_items, ACT_STEERING); - - RNA_enum_items_add_value(&item, &totitem, actuator_type_items, ACT_SOUND); - RNA_enum_items_add_value(&item, &totitem, actuator_type_items, ACT_STATE); - RNA_enum_items_add_value(&item, &totitem, actuator_type_items, ACT_VISIBILITY); - - RNA_enum_item_end(&item, &totitem); - *r_free = true; - - return item; -} - -static void rna_Actuator_Armature_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *ptr) -{ - bActuator *act = (bActuator *)ptr->data; - bArmatureActuator *aa = act->data; - Object *ob = (Object *)ptr->id.data; - - char *posechannel = aa->posechannel; - char *constraint = aa->constraint; - - /* check that bone exist in the active object */ - if (ob->type == OB_ARMATURE && ob->pose) { - bPoseChannel *pchan; - bPose *pose = ob->pose; - for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) { - if (STREQ(pchan->name, posechannel)) { - /* found it, now look for constraint channel */ - bConstraint *con; - for (con = pchan->constraints.first; con; con = con->next) { - if (STREQ(con->name, constraint)) { - /* found it, all ok */ - return; - } - } - /* didn't find constraint, make empty */ - constraint[0] = 0; - return; - } - } - } - /* didn't find any */ - posechannel[0] = 0; - constraint[0] = 0; -} - -static void rna_SteeringActuator_navmesh_set(PointerRNA *ptr, PointerRNA value) -{ - bActuator *act = (bActuator *)ptr->data; - bSteeringActuator *sa = (bSteeringActuator *) act->data; - - Object *obj = value.data; - if (obj && obj->body_type == OB_BODY_TYPE_NAVMESH) - sa->navmesh = obj; - else - sa->navmesh = NULL; -} - -/* note: the following set functions exists only to avoid id refcounting */ -static void rna_Actuator_editobject_mesh_set(PointerRNA *ptr, PointerRNA value) -{ - bActuator *act = (bActuator *)ptr->data; - bEditObjectActuator *eoa = (bEditObjectActuator *) act->data; - - eoa->me = value.data; -} - -#else - -static void rna_def_actuator(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - srna = RNA_def_struct(brna, "Actuator", NULL); - RNA_def_struct_ui_text(srna, "Actuator", "Actuator to apply actions in the game engine"); - RNA_def_struct_sdna(srna, "bActuator"); - RNA_def_struct_refine_func(srna, "rna_Actuator_refine"); - - prop = RNA_def_property(srna, "name", PROP_STRING, PROP_NONE); - RNA_def_property_ui_text(prop, "Name", ""); - RNA_def_property_string_funcs(prop, NULL, NULL, "rna_Actuator_name_set"); - RNA_def_struct_name_property(srna, prop); - - prop = RNA_def_property(srna, "type", PROP_ENUM, PROP_NONE); - RNA_def_property_clear_flag(prop, PROP_ANIMATABLE); - RNA_def_property_enum_items(prop, actuator_type_items); - RNA_def_property_enum_funcs(prop, NULL, "rna_Actuator_type_set", "rna_Actuator_type_itemf"); - RNA_def_property_ui_text(prop, "Type", ""); - - prop = RNA_def_property(srna, "pin", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_PIN); - RNA_def_property_ui_text(prop, "Pinned", "Display when not linked to a visible states controller"); - RNA_def_property_ui_icon(prop, ICON_UNPINNED, 1); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "show_expanded", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_SHOW); - RNA_def_property_ui_text(prop, "Expanded", "Set actuator expanded in the user interface"); - RNA_def_property_ui_icon(prop, ICON_TRIA_RIGHT, 1); - - prop = RNA_def_property(srna, "active", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", ACT_DEACTIVATE); - RNA_def_property_ui_text(prop, "Active", "Set the active state of the actuator"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - RNA_api_actuator(srna); -} - -static void rna_def_action_actuator(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - static const EnumPropertyItem prop_type_items[] = { - {ACT_ACTION_PLAY, "PLAY", 0, "Play", ""}, - {ACT_ACTION_PINGPONG, "PINGPONG", 0, "Ping Pong", ""}, - {ACT_ACTION_FLIPPER, "FLIPPER", 0, "Flipper", ""}, - {ACT_ACTION_LOOP_STOP, "LOOPSTOP", 0, "Loop Stop", ""}, - {ACT_ACTION_LOOP_END, "LOOPEND", 0, "Loop End", ""}, - {ACT_ACTION_FROM_PROP, "PROPERTY", 0, "Property", ""}, -#ifdef __NLA_ACTION_BY_MOTION_ACTUATOR - {ACT_ACTION_MOTION, "MOTION", 0, "Displacement", ""}, -#endif - {0, NULL, 0, NULL, NULL} - }; - - static const EnumPropertyItem prop_blend_items[] = { - {ACT_ACTION_BLEND, "BLEND", 0, "Blend", ""}, - {ACT_ACTION_ADD, "ADD", 0, "Add", ""}, - {0, NULL, 0, NULL, NULL} - }; - - srna = RNA_def_struct(brna, "ActionActuator", "Actuator"); - RNA_def_struct_ui_text(srna, "Action Actuator", "Actuator to control the object movement"); - RNA_def_struct_sdna_from(srna, "bActionActuator", "data"); - - prop = RNA_def_property(srna, "play_mode", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "type"); - RNA_def_property_enum_items(prop, prop_type_items); - RNA_def_property_ui_text(prop, "Action Type", "Action playback type"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "action", PROP_POINTER, PROP_NONE); - RNA_def_property_pointer_sdna(prop, NULL, "act"); - RNA_def_property_struct_type(prop, "Action"); - RNA_def_property_flag(prop, PROP_EDITABLE | PROP_ID_REFCOUNT); - RNA_def_property_ui_text(prop, "Action", ""); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_continue_last_frame", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_negative_sdna(prop, NULL, "end_reset", 1); - RNA_def_property_ui_text(prop, "Continue", - "Restore last frame when switching on/off, otherwise play from the start each time"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "property", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "name"); - RNA_def_property_ui_text(prop, "Property", "Use this property to define the Action position"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "frame_start", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "sta"); - RNA_def_property_ui_range(prop, 0.0, MAXFRAME, 100, 2); - RNA_def_property_ui_text(prop, "Start Frame", ""); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "frame_end", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "end"); - RNA_def_property_ui_range(prop, 0.0, MAXFRAME, 100, 2); - RNA_def_property_ui_text(prop, "End Frame", ""); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "frame_blend_in", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "blendin"); - RNA_def_property_range(prop, 0, 32767); - RNA_def_property_ui_text(prop, "Blendin", "Number of frames of motion blending"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "priority", PROP_INT, PROP_NONE); - RNA_def_property_range(prop, 0, 100); - RNA_def_property_ui_text(prop, "Priority", - "Execution priority - lower numbers will override actions with higher numbers " - "(with 2 or more actions at once, the overriding channels must be lower in the stack)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "layer", PROP_INT, PROP_NONE); - RNA_def_property_range(prop, 0, 32766); /* This should match BL_ActionManager::MAX_ACTION_LAYERS - 1 */ - RNA_def_property_ui_text(prop, "Layer", "The animation layer to play the action on"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "layer_weight", PROP_FLOAT, PROP_NONE); - RNA_def_property_range(prop, 0.0, 1.0); - RNA_def_property_ui_text(prop, "Layer Weight", - "How much of the previous layer to blend into this one"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "frame_property", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "frameProp"); - RNA_def_property_ui_text(prop, "Frame Property", "Assign the action's current frame number to this property"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* booleans */ - prop = RNA_def_property(srna, "use_additive", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_IPOADD); - RNA_def_property_boolean_funcs(prop, NULL, "rna_ActionActuator_add_set"); - RNA_def_property_ui_text(prop, "Add", - "Action is added to the current loc/rot/scale in global or local coordinate according to " - "Local flag"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_force", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_IPOFORCE); - RNA_def_property_boolean_funcs(prop, NULL, "rna_ActionActuator_force_set"); - RNA_def_property_ui_text(prop, "Force", - "Apply Action as a global or local force depending on the local option " - "(dynamic objects only)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_local", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_IPOLOCAL); - RNA_def_property_ui_text(prop, "L", "Let the Action act in local coordinates, used in Force and Add mode"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "apply_to_children", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_IPOCHILD); - RNA_def_property_ui_text(prop, "Child", "Update Action on all children Objects as well"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "blend_mode", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "blend_mode"); - RNA_def_property_enum_items(prop, prop_blend_items); - RNA_def_property_ui_text(prop, "Blend Mode", "How this layer is blended with previous layers"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - -#ifdef __NLA_ACTION_BY_MOTION_ACTUATOR - prop = RNA_def_property(srna, "stride_length", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "stridelength"); - RNA_def_property_range(prop, 0.0, 2500.0); - RNA_def_property_ui_text(prop, "Cycle", "Distance covered by a single cycle of the action"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -#endif -} - -static void rna_def_object_actuator(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - static const EnumPropertyItem prop_type_items[] = { - {ACT_OBJECT_NORMAL, "OBJECT_NORMAL", 0, "Simple Motion", ""}, - {ACT_OBJECT_SERVO, "OBJECT_SERVO", 0, "Servo Control", ""}, - {ACT_OBJECT_CHARACTER, "OBJECT_CHARACTER", 0, "Character Motion", ""}, - {0, NULL, 0, NULL, NULL} - }; - - srna = RNA_def_struct(brna, "ObjectActuator", "Actuator"); - RNA_def_struct_ui_text(srna, "Motion Actuator", "Actuator to control the object movement"); - RNA_def_struct_sdna_from(srna, "bObjectActuator", "data"); - - - prop = RNA_def_property(srna, "mode", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "type"); - RNA_def_property_enum_items(prop, prop_type_items); - RNA_def_property_enum_funcs(prop, NULL, "rna_ObjectActuator_type_set", NULL); - RNA_def_property_ui_text(prop, "Motion Type", "Specify the motion system"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "reference_object", PROP_POINTER, PROP_NONE); - RNA_def_property_struct_type(prop, "Object"); - RNA_def_property_pointer_sdna(prop, NULL, "reference"); - RNA_def_property_flag(prop, PROP_EDITABLE); - RNA_def_property_ui_text(prop, "Reference Object", - "Reference object for velocity calculation, leave empty for world reference"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "damping", PROP_INT, PROP_NONE); - RNA_def_property_ui_range(prop, 0, 1000, 1, 1); - RNA_def_property_ui_text(prop, "Damping Frames", "Number of frames to reach the target velocity"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "proportional_coefficient", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "forcerot[0]"); - RNA_def_property_ui_range(prop, 0.0, 200.0, 10, 2); - RNA_def_property_ui_text(prop, "Proportional Coefficient", "Typical value is 60x integral coefficient"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "integral_coefficient", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "forcerot[1]"); - RNA_def_property_ui_range(prop, 0.0, 3.0, 10, 2); - RNA_def_property_float_funcs(prop, NULL, "rna_ObjectActuator_integralcoefficient_set", NULL); - RNA_def_property_ui_text(prop, "Integral Coefficient", - "Low value (0.01) for slow response, high value (0.5) for fast response"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "derivate_coefficient", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "forcerot[2]"); - RNA_def_property_ui_range(prop, -100.0, 100.0, 10, 2); - RNA_def_property_ui_text(prop, "Derivate Coefficient", "Not required, high values can cause instability"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* Servo Limit */ - prop = RNA_def_property(srna, "force_max_x", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "dloc[0]"); - RNA_def_property_ui_range(prop, -100.0, 100.0, 1, 2); - RNA_def_property_ui_text(prop, "Max", "Upper limit for X force"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "force_min_x", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "drot[0]"); - RNA_def_property_ui_range(prop, -100.0, 100.0, 1, 2); - RNA_def_property_ui_text(prop, "Min", "Lower limit for X force"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "force_max_y", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "dloc[1]"); - RNA_def_property_ui_range(prop, -100.0, 100.0, 1, 2); - RNA_def_property_ui_text(prop, "Max", "Upper limit for Y force"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "force_min_y", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "drot[1]"); - RNA_def_property_ui_range(prop, -100.0, 100.0, 1, 2); - RNA_def_property_ui_text(prop, "Min", "Lower limit for Y force"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "force_max_z", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "dloc[2]"); - RNA_def_property_ui_range(prop, -100.0, 100.0, 1, 2); - RNA_def_property_ui_text(prop, "Max", "Upper limit for Z force"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "force_min_z", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "drot[2]"); - RNA_def_property_ui_range(prop, -100.0, 100.0, 1, 2); - RNA_def_property_ui_text(prop, "Min", "Lower limit for Z force"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* floats 3 Arrays*/ - prop = RNA_def_property(srna, "offset_location", PROP_FLOAT, PROP_XYZ); - RNA_def_property_float_sdna(prop, NULL, "dloc"); - RNA_def_property_array(prop, 3); - RNA_def_property_ui_range(prop, -10000.0, 10000.0, 10, 2); - RNA_def_property_ui_text(prop, "Loc", "Location"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "offset_rotation", PROP_FLOAT, PROP_EULER); - RNA_def_property_float_sdna(prop, NULL, "drot"); - RNA_def_property_array(prop, 3); - RNA_def_property_ui_range(prop, -10000.0, 10000.0, 10, 2); - RNA_def_property_ui_text(prop, "Rot", "Rotation"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "force", PROP_FLOAT, PROP_XYZ); - RNA_def_property_float_sdna(prop, NULL, "forceloc"); - RNA_def_property_array(prop, 3); - RNA_def_property_ui_range(prop, -10000.0, 10000.0, 10, 2); - RNA_def_property_ui_text(prop, "Force", "Force"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "torque", PROP_FLOAT, PROP_XYZ); - RNA_def_property_float_sdna(prop, NULL, "forcerot"); - RNA_def_property_array(prop, 3); - RNA_def_property_ui_range(prop, -10000.0, 10000.0, 10, 2); - RNA_def_property_ui_text(prop, "Torque", "Torque"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "linear_velocity", PROP_FLOAT, PROP_XYZ); - RNA_def_property_float_sdna(prop, NULL, "linearvelocity"); - RNA_def_property_array(prop, 3); - RNA_def_property_ui_range(prop, -10000.0, 10000.0, 10, 2); - RNA_def_property_ui_text(prop, "Linear Velocity", - "Linear velocity (in Servo mode it sets the target relative linear velocity, it will be " - "achieved by automatic application of force - Null velocity is a valid target)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "angular_velocity", PROP_FLOAT, PROP_XYZ); - RNA_def_property_float_sdna(prop, NULL, "angularvelocity"); - RNA_def_property_array(prop, 3); - RNA_def_property_ui_range(prop, -10000.0, 10000.0, 10, 2); - RNA_def_property_ui_text(prop, "Angular Velocity", "Angular velocity"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* booleans */ - prop = RNA_def_property(srna, "use_local_location", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_DLOC_LOCAL); - RNA_def_property_ui_text(prop, "L", "Location is defined in local coordinates"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_local_rotation", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_DROT_LOCAL); - RNA_def_property_ui_text(prop, "L", "Rotation is defined in local coordinates"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_local_force", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_FORCE_LOCAL); - RNA_def_property_ui_text(prop, "L", "Force is defined in local coordinates"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_local_torque", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_TORQUE_LOCAL); - RNA_def_property_ui_text(prop, "L", "Torque is defined in local coordinates"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_local_linear_velocity", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_LIN_VEL_LOCAL); - RNA_def_property_ui_text(prop, "L", "Velocity is defined in local coordinates"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_local_angular_velocity", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_ANG_VEL_LOCAL); - RNA_def_property_ui_text(prop, "L", "Angular velocity is defined in local coordinates"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_add_linear_velocity", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_ADD_LIN_VEL); - RNA_def_property_ui_text(prop, "Add", "Toggles between ADD and SET linV"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_add_character_location", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_ADD_CHAR_LOC); - RNA_def_property_ui_text(prop, "Add", "Toggle between ADD and SET character location"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_servo_limit_x", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_SERVO_LIMIT_X); - RNA_def_property_ui_text(prop, "X", "Set limit to force along the X axis"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_servo_limit_y", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_SERVO_LIMIT_Y); - RNA_def_property_ui_text(prop, "Y", "Set limit to force along the Y axis"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_servo_limit_z", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_SERVO_LIMIT_Z); - RNA_def_property_ui_text(prop, "Z", "Set limit to force along the Z axis"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_character_jump", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_CHAR_JUMP); - RNA_def_property_ui_text(prop, "Jump", "Make the character jump using the settings in the physics properties"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -static void rna_def_camera_actuator(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - static const EnumPropertyItem prop_axis_items[] = { - {OB_POSX, "POS_X", 0, "+X", "Camera tries to get behind the X axis"}, - {OB_POSY, "POS_Y", 0, "+Y", "Camera tries to get behind the Y axis"}, - {OB_NEGX, "NEG_X", 0, "-X", "Camera tries to get behind the -X axis"}, - {OB_NEGY, "NEG_Y", 0, "-Y", "Camera tries to get behind the -Y axis"}, - {0, NULL, 0, NULL, NULL} - }; - - srna = RNA_def_struct(brna, "CameraActuator", "Actuator"); - RNA_def_struct_ui_text(srna, "Camera Actuator", ""); - RNA_def_struct_sdna_from(srna, "bCameraActuator", "data"); - - prop = RNA_def_property(srna, "object", PROP_POINTER, PROP_NONE); - RNA_def_property_struct_type(prop, "Object"); - RNA_def_property_pointer_sdna(prop, NULL, "ob"); - RNA_def_property_flag(prop, PROP_EDITABLE); - RNA_def_property_ui_text(prop, "Camera Object", "Look at this Object"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* floats */ - prop = RNA_def_property(srna, "height", PROP_FLOAT, PROP_NONE); - RNA_def_property_ui_range(prop, 0.0, 20.0, 1, 2); - RNA_def_property_ui_text(prop, "Height", ""); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "min", PROP_FLOAT, PROP_NONE); - RNA_def_property_ui_range(prop, 0.0, 20.0, 1, 2); - RNA_def_property_ui_text(prop, "Min", ""); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "max", PROP_FLOAT, PROP_NONE); - RNA_def_property_ui_range(prop, 0.0, 20.0, 1, 2); - RNA_def_property_ui_text(prop, "Max", ""); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "damping", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "damping"); - RNA_def_property_range(prop, 0, 10.0); - RNA_def_property_ui_range(prop, 0, 5.0, 1, 2); - RNA_def_property_ui_text(prop, "Damping", "Strength of the constraint that drives the camera behind the target"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* +x/+y/-x/-y */ - prop = RNA_def_property(srna, "axis", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "axis"); - RNA_def_property_enum_items(prop, prop_axis_items); - RNA_def_property_ui_text(prop, "Axis", "Axis the Camera will try to get behind"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -static void rna_def_sound_actuator(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - static const EnumPropertyItem prop_type_items[] = { - {ACT_SND_PLAY_STOP_SOUND, "PLAYSTOP", 0, "Play Stop", ""}, - {ACT_SND_PLAY_END_SOUND, "PLAYEND", 0, "Play End", ""}, - {ACT_SND_LOOP_STOP_SOUND, "LOOPSTOP", 0, "Loop Stop", ""}, - {ACT_SND_LOOP_END_SOUND, "LOOPEND", 0, "Loop End", ""}, - {ACT_SND_LOOP_BIDIRECTIONAL_SOUND, "LOOPBIDIRECTIONAL", 0, "Loop Bidirectional", ""}, - {ACT_SND_LOOP_BIDIRECTIONAL_STOP_SOUND, "LOOPBIDIRECTIONALSTOP", 0, "Loop Bidirectional Stop", ""}, - {0, NULL, 0, NULL, NULL} - }; - - srna = RNA_def_struct(brna, "SoundActuator", "Actuator"); - RNA_def_struct_ui_text(srna, "Sound Actuator", "Actuator to handle sound"); - RNA_def_struct_sdna_from(srna, "bSoundActuator", "data"); - - prop = RNA_def_property(srna, "sound", PROP_POINTER, PROP_NONE); - RNA_def_property_struct_type(prop, "Sound"); - RNA_def_property_flag(prop, PROP_EDITABLE); - RNA_def_struct_ui_text(srna, "Sound", "Sound file"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "mode", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "type"); - RNA_def_property_enum_items(prop, prop_type_items); - RNA_def_property_ui_text(prop, "Play Mode", ""); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "volume", PROP_FLOAT, PROP_NONE); - RNA_def_property_ui_range(prop, 0.0, 1.0, 1, 2); - RNA_def_property_range(prop, 0.0, 2.0); - RNA_def_property_ui_text(prop, "Volume", "Initial volume of the sound"); - RNA_def_property_translation_context(prop, BLT_I18NCONTEXT_ID_SOUND); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "pitch", PROP_FLOAT, PROP_NONE); - RNA_def_property_ui_range(prop, -12.0, 12.0, 1, 2); - RNA_def_property_ui_text(prop, "Pitch", "Pitch of the sound"); - RNA_def_property_translation_context(prop, BLT_I18NCONTEXT_ID_SOUND); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* floats - 3D Parameters */ - prop = RNA_def_property(srna, "gain_3d_min", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "sound3D.min_gain"); - RNA_def_property_ui_range(prop, 0.0, 1.0, 1, 2); - RNA_def_property_ui_text(prop, "Minimum Gain", "The minimum gain of the sound, no matter how far it is away"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "gain_3d_max", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "sound3D.max_gain"); - RNA_def_property_ui_range(prop, 0.0, 1.0, 1, 2); - RNA_def_property_ui_text(prop, "Maximum Gain", "The maximum gain of the sound, no matter how near it is"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "distance_3d_reference", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "sound3D.reference_distance"); - RNA_def_property_ui_range(prop, 0.0, FLT_MAX, 1, 2); - RNA_def_property_ui_text(prop, "Reference Distance", "The distance where the sound has a gain of 1.0"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "distance_3d_max", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "sound3D.max_distance"); - RNA_def_property_ui_range(prop, 0.0, FLT_MAX, 1, 2); - RNA_def_property_ui_text(prop, "Maximum Distance", "The maximum distance at which you can hear the sound"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "rolloff_factor_3d", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "sound3D.rolloff_factor"); - RNA_def_property_ui_range(prop, 0.0, 5.0, 1, 2); - RNA_def_property_ui_text(prop, "Rolloff", "The influence factor on volume depending on distance"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "cone_outer_gain_3d", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "sound3D.cone_outer_gain"); - RNA_def_property_ui_range(prop, 0.0, 1.0, 1, 2); - RNA_def_property_ui_text(prop, "Cone Outer Gain", - "The gain outside the outer cone (the gain in the outer cone will be interpolated " - "between this value and the normal gain in the inner cone)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "cone_outer_angle_3d", PROP_FLOAT, PROP_ANGLE); - RNA_def_property_float_sdna(prop, NULL, "sound3D.cone_outer_angle"); - RNA_def_property_ui_range(prop, 0.0, DEG2RADF(360.0f), 1, 2); - RNA_def_property_ui_text(prop, "Cone Outer Angle", "The angle of the outer cone"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "cone_inner_angle_3d", PROP_FLOAT, PROP_ANGLE); - RNA_def_property_float_sdna(prop, NULL, "sound3D.cone_inner_angle"); - RNA_def_property_ui_range(prop, 0.0, DEG2RADF(360.0f), 1, 2); - RNA_def_property_ui_text(prop, "Cone Inner Angle", "The angle of the inner cone"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* booleans */ - prop = RNA_def_property(srna, "use_sound_3d", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_SND_3D_SOUND); - RNA_def_property_ui_text(prop, "3D Sound", "Enable/Disable 3D Sound"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -static void rna_def_property_actuator(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - static const EnumPropertyItem prop_type_items[] = { - {ACT_PROP_ASSIGN, "ASSIGN", 0, "Assign", ""}, - {ACT_PROP_ADD, "ADD", 0, "Add", ""}, - {ACT_PROP_COPY, "COPY", 0, "Copy", ""}, - {ACT_PROP_TOGGLE, "TOGGLE", 0, "Toggle", "For bool/int/float/timer properties only"}, - {ACT_PROP_LEVEL, "LEVEL", 0, "Level", "For bool/int/float/timer properties only"}, - {0, NULL, 0, NULL, NULL} - }; - - srna = RNA_def_struct(brna, "PropertyActuator", "Actuator"); - RNA_def_struct_ui_text(srna, "Property Actuator", "Actuator to handle properties"); - RNA_def_struct_sdna_from(srna, "bPropertyActuator", "data"); - - prop = RNA_def_property(srna, "mode", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "type"); - RNA_def_property_enum_items(prop, prop_type_items); - RNA_def_property_ui_text(prop, "Mode", ""); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "property", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "name"); - RNA_def_property_ui_text(prop, "Property", "The name of the property"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "value", PROP_STRING, PROP_NONE); - RNA_def_property_ui_text(prop, "Value", "The name of the property or the value to use (use \"\" around strings)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* Copy Mode */ - prop = RNA_def_property(srna, "object", PROP_POINTER, PROP_NONE); - RNA_def_property_struct_type(prop, "Object"); - RNA_def_property_pointer_sdna(prop, NULL, "ob"); - RNA_def_property_flag(prop, PROP_EDITABLE); - RNA_def_property_ui_text(prop, "Object", "Copy from this Object"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /*XXX add even magic'er property lookup (need to look for the property list of the target object) */ - prop = RNA_def_property(srna, "object_property", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "value"); - RNA_def_property_ui_text(prop, "Property Name", "Copy this property"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -static void rna_def_constraint_actuator(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - static const EnumPropertyItem prop_type_items[] = { - {ACT_CONST_TYPE_LOC, "LOC", 0, "Location Constraint", ""}, - {ACT_CONST_TYPE_DIST, "DIST", 0, "Distance Constraint", ""}, - {ACT_CONST_TYPE_ORI, "ORI", 0, "Orientation Constraint", ""}, - {ACT_CONST_TYPE_FH, "FH", 0, "Force Field Constraint", ""}, - {0, NULL, 0, NULL, NULL} - }; - - static const EnumPropertyItem prop_limit_items[] = { - {ACT_CONST_NONE, "NONE", 0, "None", ""}, - {ACT_CONST_LOCX, "LOCX", 0, "Loc X", ""}, - {ACT_CONST_LOCY, "LOCY", 0, "Loc Y", ""}, - {ACT_CONST_LOCZ, "LOCZ", 0, "Loc Z", ""}, - {0, NULL, 0, NULL, NULL} - }; - - static const EnumPropertyItem prop_direction_items[] = { - {ACT_CONST_NONE, "NONE", 0, "None", ""}, - {ACT_CONST_DIRPX, "DIRPX", 0, "X axis", ""}, - {ACT_CONST_DIRPY, "DIRPY", 0, "Y axis", ""}, - {ACT_CONST_DIRPZ, "DIRPZ", 0, "Z axis", ""}, - {ACT_CONST_DIRNX, "DIRNX", 0, "-X axis", ""}, - {ACT_CONST_DIRNY, "DIRNY", 0, "-Y axis", ""}, - {ACT_CONST_DIRNZ, "DIRNZ", 0, "-Z axis", ""}, - {0, NULL, 0, NULL, NULL} - }; - - static const EnumPropertyItem prop_direction_pos_items[] = { - {ACT_CONST_NONE, "NONE", 0, "None", ""}, - {ACT_CONST_DIRPX, "DIRPX", 0, "X axis", ""}, - {ACT_CONST_DIRPY, "DIRPY", 0, "Y axis", ""}, - {ACT_CONST_DIRPZ, "DIRPZ", 0, "Z axis", ""}, - {0, NULL, 0, NULL, NULL} - }; - - srna = RNA_def_struct(brna, "ConstraintActuator", "Actuator"); - RNA_def_struct_ui_text(srna, "Constraint Actuator", "Actuator to handle Constraints"); - RNA_def_struct_sdna_from(srna, "bConstraintActuator", "data"); - - prop = RNA_def_property(srna, "mode", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "type"); - RNA_def_property_enum_items(prop, prop_type_items); - RNA_def_property_enum_funcs(prop, NULL, "rna_ConstraintActuator_type_set", NULL); - RNA_def_property_ui_text(prop, "Constraints Mode", "The type of the constraint"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "limit", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "flag"); - RNA_def_property_enum_items(prop, prop_limit_items); - RNA_def_property_ui_text(prop, "Limit", ""); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "direction", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "mode"); - RNA_def_property_enum_items(prop, prop_direction_items); - RNA_def_property_ui_text(prop, "Direction", "Direction of the ray"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "direction_axis", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "mode"); - RNA_def_property_enum_items(prop, prop_direction_items); - RNA_def_property_ui_text(prop, "Direction", "Select the axis to be aligned along the reference direction"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* ACT_CONST_TYPE_LOC */ - prop = RNA_def_property(srna, "limit_min", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_funcs(prop, "rna_ConstraintActuator_limitmin_get", - "rna_ConstraintActuator_limitmin_set", NULL); - RNA_def_property_ui_range(prop, -2000.f, 2000.f, 1, 2); - RNA_def_property_ui_text(prop, "Min", ""); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "limit_max", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_funcs(prop, "rna_ConstraintActuator_limitmax_get", - "rna_ConstraintActuator_limitmax_set", NULL); - RNA_def_property_ui_range(prop, -2000.f, 2000.f, 1, 2); - RNA_def_property_ui_text(prop, "Max", ""); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "damping", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "damp"); - RNA_def_property_ui_range(prop, 0, 100, 1, 1); - RNA_def_property_ui_text(prop, "Damping", "Damping factor: time constant (in frame) of low pass filter"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* ACT_CONST_TYPE_DIST */ - prop = RNA_def_property(srna, "range", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_funcs(prop, "rna_ConstraintActuator_range_get", "rna_ConstraintActuator_range_set", NULL); - RNA_def_property_ui_range(prop, 0.f, 2000.f, 1, 2); - RNA_def_property_ui_text(prop, "Range", "Maximum length of ray"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "distance", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_funcs(prop, "rna_ConstraintActuator_distance_get", - "rna_ConstraintActuator_distance_set", NULL); - RNA_def_property_ui_range(prop, -2000.f, 2000.f, 1, 2); - RNA_def_property_ui_text(prop, "Distance", "Keep this distance to target"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /*XXX to use a pointer or add a material lookup */ - prop = RNA_def_property(srna, "material", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "matprop"); - RNA_def_property_flag(prop, PROP_EDITABLE); - RNA_def_property_ui_text(prop, "Material", "Ray detects only Objects with this material"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /*XXX add magic property lookup */ - prop = RNA_def_property(srna, "property", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "matprop"); - RNA_def_property_ui_text(prop, "Property", "Ray detects only Objects with this property"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "time", PROP_INT, PROP_NONE); - RNA_def_property_ui_range(prop, 0, 1000, 1, 2); - RNA_def_property_ui_text(prop, "Time", "Maximum activation time in frame, 0 for unlimited"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "damping_rotation", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "rotdamp"); - RNA_def_property_ui_range(prop, 0, 100, 1, 1); - RNA_def_property_ui_text(prop, "RotDamp", "Use a different damping for orientation"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* ACT_CONST_TYPE_ORI */ - prop = RNA_def_property(srna, "direction_axis_pos", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "mode"); - RNA_def_property_enum_items(prop, prop_direction_pos_items); - RNA_def_property_ui_text(prop, "Direction", "Select the axis to be aligned along the reference direction"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "rotation_max", PROP_FLOAT, PROP_XYZ); - RNA_def_property_float_sdna(prop, NULL, "maxrot"); - RNA_def_property_array(prop, 3); - RNA_def_property_ui_range(prop, -2000.0, 2000.0, 10, 2); - RNA_def_property_ui_text(prop, "Reference Direction", "Reference Direction"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "angle_min", PROP_FLOAT, PROP_ANGLE); - RNA_def_property_float_sdna(prop, NULL, "minloc[0]"); - RNA_def_property_range(prop, 0.0f, DEG2RADF(180.0f)); - RNA_def_property_ui_text(prop, "Min Angle", - "Minimum angle to maintain with target direction " - "(no correction is done if angle with target direction is between min and max)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "angle_max", PROP_FLOAT, PROP_ANGLE); - RNA_def_property_float_sdna(prop, NULL, "maxloc[0]"); - RNA_def_property_range(prop, 0.0f, DEG2RADF(180.0f)); - RNA_def_property_ui_text(prop, "Max Angle", - "Maximum angle allowed with target direction " - "(no correction is done if angle with target direction is between min and max)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* ACT_CONST_TYPE_FH */ - prop = RNA_def_property(srna, "fh_height", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_funcs(prop, "rna_ConstraintActuator_fhheight_get", - "rna_ConstraintActuator_fhheight_set", NULL); - RNA_def_property_ui_range(prop, 0.01, 2000.0, 10, 2); - RNA_def_property_ui_text(prop, "Distance", "Height of the force field area"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "fh_force", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_funcs(prop, "rna_ConstraintActuator_spring_get", "rna_ConstraintActuator_spring_set", NULL); - RNA_def_property_ui_range(prop, 0.0, 1.0, 10, 2); - RNA_def_property_ui_text(prop, "Force", "Spring force within the force field area"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "fh_damping", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "maxrot[0]"); - RNA_def_property_ui_range(prop, 0.0, 1.0, 10, 2); - RNA_def_property_ui_text(prop, "Damping", "Damping factor of the force field spring"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* booleans */ - prop = RNA_def_property(srna, "use_force_distance", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_CONST_DISTANCE); - RNA_def_property_ui_text(prop, "Force Distance", "Force distance of object to point of impact of ray"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_local", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_CONST_LOCAL); - RNA_def_property_ui_text(prop, "L", "Set ray along object's axis or global axis"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_normal", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_CONST_NORMAL); - RNA_def_property_ui_text(prop, "N", - "Set object axis along (local axis) or parallel (global axis) to the normal at " - "hit position"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_persistent", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_CONST_PERMANENT); - RNA_def_property_ui_text(prop, "PER", "Persistent actuator: stays active even if ray does not reach target"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /*XXX to use an enum instead of a flag if possible */ - prop = RNA_def_property(srna, "use_material_detect", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_CONST_MATERIAL); - RNA_def_property_ui_text(prop, "M/P", "Detect material instead of property"); - RNA_def_property_boolean_funcs(prop, NULL, "rna_Actuator_constraint_detect_material_set"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_fh_paralel_axis", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_CONST_DOROTFH); - RNA_def_property_ui_text(prop, "Rot Fh", "Keep object axis parallel to normal"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_fh_normal", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_CONST_NORMAL); - RNA_def_property_ui_text(prop, "N", "Add a horizontal spring force on slopes"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -static void rna_def_edit_object_actuator(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - static const EnumPropertyItem prop_dyn_items[] = { - {ACT_EDOB_RESTORE_DYN, "RESTOREDYN", 0, "Restore Dynamics", ""}, - {ACT_EDOB_SUSPEND_DYN, "SUSPENDDYN", 0, "Suspend Dynamics", ""}, - {ACT_EDOB_ENABLE_RB, "ENABLERIGIDBODY", 0, "Enable Rigid Body", ""}, - {ACT_EDOB_DISABLE_RB, "DISABLERIGIDBODY", 0, "Disable Rigid Body", ""}, - {ACT_EDOB_SET_MASS, "SETMASS", 0, "Set Mass", ""}, - {0, NULL, 0, NULL, NULL} - }; - - static const EnumPropertyItem prop_type_items[] = { - {ACT_EDOB_ADD_OBJECT, "ADDOBJECT", 0, "Add Object", ""}, - {ACT_EDOB_END_OBJECT, "ENDOBJECT", 0, "End Object", ""}, - {ACT_EDOB_REPLACE_MESH, "REPLACEMESH", 0, "Replace Mesh", ""}, - {ACT_EDOB_TRACK_TO, "TRACKTO", 0, "Track to", ""}, - {ACT_EDOB_DYNAMICS, "DYNAMICS", 0, "Dynamics", ""}, - {0, NULL, 0, NULL, NULL} - }; - - static const EnumPropertyItem prop_track_axis_items[] = { - {ACT_TRACK_TRAXIS_X, "TRACKAXISX", 0, "X axis", ""}, - {ACT_TRACK_TRAXIS_Y, "TRACKAXISY", 0, "Y axis", ""}, - {ACT_TRACK_TRAXIS_Z, "TRACKAXISZ", 0, "Z axis", ""}, - {ACT_TRACK_TRAXIS_NEGX, "TRACKAXISNEGX", 0, "-X axis", ""}, - {ACT_TRACK_TRAXIS_NEGY, "TRACKAXISNEGY", 0, "-Y axis", ""}, - {ACT_TRACK_TRAXIS_NEGZ, "TRACKAXISNEGZ", 0, "-Z axis", ""}, - {0, NULL, 0, NULL, NULL} - }; - - static const EnumPropertyItem prop_up_axis_items[] = { - {ACT_TRACK_UP_X, "UPAXISX", 0, "X axis", ""}, - {ACT_TRACK_UP_Y, "UPAXISY", 0, "Y axis", ""}, - {ACT_TRACK_UP_Z, "UPAXISZ", 0, "Z axis", ""}, - {0, NULL, 0, NULL, NULL} - }; - - srna = RNA_def_struct(brna, "EditObjectActuator", "Actuator"); - RNA_def_struct_ui_text(srna, "Edit Object Actuator", "Actuator used to edit objects"); - RNA_def_struct_sdna_from(srna, "bEditObjectActuator", "data"); - - prop = RNA_def_property(srna, "mode", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "type"); - RNA_def_property_enum_items(prop, prop_type_items); - RNA_def_property_ui_text(prop, "Edit Object", "The mode of the actuator"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "dynamic_operation", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "dyn_operation"); - RNA_def_property_enum_items(prop, prop_dyn_items); - RNA_def_property_ui_text(prop, "Dynamic Operation", ""); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "up_axis", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "upflag"); - RNA_def_property_enum_items(prop, prop_up_axis_items); - RNA_def_property_ui_text(prop, "Up Axis", "The axis that points upward"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "track_axis", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "trackflag"); - RNA_def_property_enum_items(prop, prop_track_axis_items); - RNA_def_property_ui_text(prop, "Track Axis", "The axis that points to the target object"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "object", PROP_POINTER, PROP_NONE); - RNA_def_property_struct_type(prop, "Object"); - RNA_def_property_pointer_sdna(prop, NULL, "ob"); - RNA_def_property_flag(prop, PROP_EDITABLE); - RNA_def_property_ui_text(prop, "Object", "Add this Object and all its children (can't be on a visible layer)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "track_object", PROP_POINTER, PROP_NONE); - RNA_def_property_struct_type(prop, "Object"); - RNA_def_property_pointer_sdna(prop, NULL, "ob"); - RNA_def_property_flag(prop, PROP_EDITABLE); - RNA_def_property_ui_text(prop, "Object", "Track to this Object"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "mesh", PROP_POINTER, PROP_NONE); - RNA_def_property_struct_type(prop, "Mesh"); - RNA_def_property_pointer_sdna(prop, NULL, "me"); - RNA_def_property_flag(prop, PROP_EDITABLE); - RNA_def_property_ui_text(prop, "Mesh", - "Replace the existing, when left blank 'Phys' will remake the existing physics mesh"); - /* note: custom set function is ONLY to avoid rna setting a user for this. */ - RNA_def_property_pointer_funcs(prop, NULL, "rna_Actuator_editobject_mesh_set", NULL, NULL); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "time", PROP_INT, PROP_NONE); - RNA_def_property_ui_range(prop, 0, 2000, 1, 1); - RNA_def_property_ui_text(prop, "Time", "Duration the new Object lives or the track takes"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "mass", PROP_FLOAT, PROP_NONE); - RNA_def_property_ui_range(prop, 0, 10000, 1, 2); - RNA_def_property_ui_text(prop, "Mass", "The mass of the object"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* floats 3 Arrays*/ - prop = RNA_def_property(srna, "linear_velocity", PROP_FLOAT, PROP_XYZ); - RNA_def_property_float_sdna(prop, NULL, "linVelocity"); - RNA_def_property_array(prop, 3); - RNA_def_property_ui_range(prop, -100.0, 100.0, 10, 2); - RNA_def_property_ui_text(prop, "Linear Velocity", "Velocity upon creation"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "angular_velocity", PROP_FLOAT, PROP_XYZ); - RNA_def_property_float_sdna(prop, NULL, "angVelocity"); - RNA_def_property_array(prop, 3); - RNA_def_property_ui_range(prop, -10000.0, 10000.0, 10, 2); - RNA_def_property_ui_text(prop, "Angular Velocity", "Angular velocity upon creation"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* booleans */ - prop = RNA_def_property(srna, "use_local_linear_velocity", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "localflag", ACT_EDOB_LOCAL_LINV); - RNA_def_property_ui_text(prop, "L", "Apply the transformation locally"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_local_angular_velocity", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "localflag", ACT_EDOB_LOCAL_ANGV); - RNA_def_property_ui_text(prop, "L", "Apply the rotation locally"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_replace_display_mesh", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", ACT_EDOB_REPLACE_MESH_NOGFX); - RNA_def_property_ui_text(prop, "Gfx", "Replace the display mesh"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_replace_physics_mesh", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_EDOB_REPLACE_MESH_PHYS); - RNA_def_property_ui_text(prop, "Phys", - "Replace the physics mesh (triangle bounds only - compound shapes not supported)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_3d_tracking", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_TRACK_3D); - RNA_def_property_ui_text(prop, "3D", "Enable 3D tracking"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -static void rna_def_scene_actuator(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - static const EnumPropertyItem prop_type_items[] = { - {ACT_SCENE_RESTART, "RESTART", 0, "Restart", ""}, - {ACT_SCENE_SET, "SET", 0, "Set Scene", ""}, - {ACT_SCENE_CAMERA, "CAMERA", 0, "Set Camera", ""}, - {ACT_SCENE_ADD_FRONT, "ADDFRONT", 0, "Add Overlay Scene", ""}, - {ACT_SCENE_ADD_BACK, "ADDBACK", 0, "Add Background Scene", ""}, - {ACT_SCENE_REMOVE, "REMOVE", 0, "Remove Scene", ""}, - {ACT_SCENE_SUSPEND, "SUSPEND", 0, "Suspend Scene", ""}, - {ACT_SCENE_RESUME, "RESUME", 0, "Resume Scene", ""}, - {0, NULL, 0, NULL, NULL} - }; - - srna = RNA_def_struct(brna, "SceneActuator", "Actuator"); - RNA_def_struct_ui_text(srna, "Scene Actuator", ""); - RNA_def_struct_sdna_from(srna, "bSceneActuator", "data"); - - prop = RNA_def_property(srna, "mode", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "type"); - RNA_def_property_enum_items(prop, prop_type_items); - RNA_def_property_ui_text(prop, "Mode", ""); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "camera", PROP_POINTER, PROP_NONE); - RNA_def_property_struct_type(prop, "Object"); - RNA_def_property_pointer_funcs(prop, NULL, NULL, NULL, "rna_Camera_object_poll"); - RNA_def_property_flag(prop, PROP_EDITABLE); - RNA_def_property_ui_text(prop, "Camera Object", "Set this Camera (leave empty to refer to self object)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "scene", PROP_POINTER, PROP_NONE); - RNA_def_property_struct_type(prop, "Scene"); - RNA_def_property_flag(prop, PROP_EDITABLE); - RNA_def_property_ui_text(prop, "Scene", "Scene to be added/removed/paused/resumed"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -static void rna_def_random_actuator(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - static const EnumPropertyItem prop_distribution_items[] = { - {ACT_RANDOM_BOOL_CONST, "BOOL_CONSTANT", 0, "Bool Constant", ""}, - {ACT_RANDOM_BOOL_UNIFORM, "BOOL_UNIFORM", 0, "Bool Uniform", ""}, - {ACT_RANDOM_BOOL_BERNOUILLI, "BOOL_BERNOUILLI", 0, "Bool Bernoulli", ""}, - {ACT_RANDOM_INT_CONST, "INT_CONSTANT", 0, "Int Constant", ""}, - {ACT_RANDOM_INT_UNIFORM, "INT_UNIFORM", 0, "Int Uniform", ""}, - {ACT_RANDOM_INT_POISSON, "INT_POISSON", 0, "Int Poisson", ""}, - {ACT_RANDOM_FLOAT_CONST, "FLOAT_CONSTANT", 0, "Float Constant", ""}, - {ACT_RANDOM_FLOAT_UNIFORM, "FLOAT_UNIFORM", 0, "Float Uniform", ""}, - {ACT_RANDOM_FLOAT_NORMAL, "FLOAT_NORMAL", 0, "Float Normal", ""}, - {ACT_RANDOM_FLOAT_NEGATIVE_EXPONENTIAL, "FLOAT_NEGATIVE_EXPONENTIAL", 0, "Float Neg. Exp.", ""}, - {0, NULL, 0, NULL, NULL} - }; - - srna = RNA_def_struct(brna, "RandomActuator", "Actuator"); - RNA_def_struct_ui_text(srna, "Random Actuator", ""); - RNA_def_struct_sdna_from(srna, "bRandomActuator", "data"); - - prop = RNA_def_property(srna, "seed", PROP_INT, PROP_NONE); - RNA_def_property_ui_range(prop, 0, 1000, 1, 1); - RNA_def_property_range(prop, 0, MAXFRAME); - RNA_def_property_ui_text(prop, "Seed", - "Initial seed of the random generator, use Python for more freedom " - "(choose 0 for not random)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "property", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "propname"); - RNA_def_property_ui_text(prop, "Property", "Assign the random value to this property"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "distribution", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_items(prop, prop_distribution_items); - RNA_def_property_ui_text(prop, "Distribution", "Choose the type of distribution"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* arguments for the distribution */ - /* int_arg_1, int_arg_2, float_arg_1, float_arg_2 */ - - /* ACT_RANDOM_BOOL_CONST */ - prop = RNA_def_property(srna, "use_always_true", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "int_arg_1", 1); - RNA_def_property_ui_text(prop, "Always True", "Always false or always true"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* ACT_RANDOM_BOOL_UNIFORM */ - /* label => "Choose between true and false, 50% chance each" */ - - /* ACT_RANDOM_BOOL_BERNOUILLI */ - prop = RNA_def_property(srna, "chance", PROP_FLOAT, PROP_PERCENTAGE); - RNA_def_property_float_sdna(prop, NULL, "float_arg_1"); - RNA_def_property_range(prop, 0.0, 1.0); - RNA_def_property_ui_text(prop, "Chance", "Pick a number between 0 and 1, success if it's below this value"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* ACT_RANDOM_INT_CONST */ - prop = RNA_def_property(srna, "int_value", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "int_arg_1"); - RNA_def_property_ui_range(prop, -1000, 1000, 1, 1); - RNA_def_property_ui_text(prop, "Value", "Always return this number"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* ACT_RANDOM_INT_UNIFORM */ - prop = RNA_def_property(srna, "int_min", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "int_arg_1"); - RNA_def_property_range(prop, -1000, 1000); - RNA_def_property_ui_text(prop, "Min", "Choose a number from a range: lower boundary of the range"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "int_max", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "int_arg_2"); - RNA_def_property_range(prop, -1000, 1000); - RNA_def_property_ui_text(prop, "Max", "Choose a number from a range: upper boundary of the range"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* ACT_RANDOM_INT_POISSON */ - prop = RNA_def_property(srna, "int_mean", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "float_arg_1"); - RNA_def_property_range(prop, 0.01, 100.0); - RNA_def_property_ui_text(prop, "Mean", "Expected mean value of the distribution"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* ACT_RANDOM_FLOAT_CONST */ - prop = RNA_def_property(srna, "float_value", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "float_arg_1"); - RNA_def_property_range(prop, 0.0, 1.0); - RNA_def_property_ui_text(prop, "Value", "Always return this number"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* ACT_RANDOM_FLOAT_UNIFORM */ - prop = RNA_def_property(srna, "float_min", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "float_arg_1"); - RNA_def_property_range(prop, -1000.0, 1000.0); - RNA_def_property_ui_text(prop, "Min", "Choose a number from a range: lower boundary of the range"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "float_max", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "float_arg_2"); - RNA_def_property_range(prop, -1000.0, 1000.0); - RNA_def_property_ui_text(prop, "Max", "Choose a number from a range: upper boundary of the range"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* ACT_RANDOM_FLOAT_NORMAL */ - prop = RNA_def_property(srna, "float_mean", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "float_arg_1"); - RNA_def_property_range(prop, -1000.0, 1000.0); - RNA_def_property_ui_text(prop, "Mean", "A normal distribution: mean of the distribution"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "standard_derivation", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "float_arg_2"); - RNA_def_property_range(prop, -1000.0, 1000.0); - RNA_def_property_ui_text(prop, "SD", "A normal distribution: standard deviation of the distribution"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* ACT_RANDOM_FLOAT_NEGATIVE_EXPONENTIAL */ - prop = RNA_def_property(srna, "half_life_time", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "float_arg_1"); - RNA_def_property_range(prop, -1000.0, 1000.0); - RNA_def_property_ui_text(prop, "Half-Life Time", "Negative exponential dropoff"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -static void rna_def_message_actuator(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - static const EnumPropertyItem prop_body_type_items[] = { - {ACT_MESG_MESG, "TEXT", 0, "Text", ""}, - {ACT_MESG_PROP, "PROPERTY", 0, "Property", ""}, - {0, NULL, 0, NULL, NULL} - }; - - srna = RNA_def_struct(brna, "MessageActuator", "Actuator"); - RNA_def_struct_ui_text(srna, "Message Actuator", ""); - RNA_def_struct_sdna_from(srna, "bMessageActuator", "data"); - - prop = RNA_def_property(srna, "to_property", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "toPropName"); - RNA_def_property_ui_text(prop, "To", - "Optional, send message to objects with this name only, or empty to broadcast"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "subject", PROP_STRING, PROP_NONE); - RNA_def_property_ui_text(prop, "Subject", "Optional, message subject (this is what can be filtered on)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "body_type", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "bodyType"); - RNA_def_property_enum_items(prop, prop_body_type_items); - RNA_def_property_ui_text(prop, "Body", "Toggle message type: either Text or a PropertyName"); - - /* ACT_MESG_MESG */ - prop = RNA_def_property(srna, "body_message", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "body"); - RNA_def_property_ui_text(prop, "Body", "Optional, message body Text"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* ACT_MESG_PROP */ - prop = RNA_def_property(srna, "body_property", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "body"); - RNA_def_property_ui_text(prop, "Prop Name", "The message body will be set by the Property Value"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -static void rna_def_game_actuator(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - static const EnumPropertyItem prop_type_items[] = { -/* {ACT_GAME_LOAD, "LOAD", 0, "Load Game", ""}, */ -/* {ACT_GAME_START, "START", 0, "Start Loaded Game", ""}, */ -/* keeping the load/start hacky for compatibility with 2.49 */ -/* ideally we could use ACT_GAME_START again and do a do_version() */ - - {ACT_GAME_LOAD, "START", 0, "Start Game From File", ""}, - {ACT_GAME_RESTART, "RESTART", 0, "Restart Game", ""}, - {ACT_GAME_QUIT, "QUIT", 0, "Quit Game", ""}, - {ACT_GAME_SAVECFG, "SAVECFG", 0, "Save bge.logic.globalDict", ""}, - {ACT_GAME_LOADCFG, "LOADCFG", 0, "Load bge.logic.globalDict", ""}, - {ACT_GAME_SCREENSHOT, "SCREENSHOT", 0, "Screenshot", ""}, - {0, NULL, 0, NULL, NULL} - }; - - srna = RNA_def_struct(brna, "GameActuator", "Actuator"); - RNA_def_struct_ui_text(srna, "Game Actuator", ""); - RNA_def_struct_sdna_from(srna, "bGameActuator", "data"); - - prop = RNA_def_property(srna, "mode", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "type"); - RNA_def_property_enum_items(prop, prop_type_items); - RNA_def_property_ui_text(prop, "Game", ""); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* ACT_GAME_LOAD */ - prop = RNA_def_property(srna, "filename", PROP_STRING, PROP_FILEPATH); - RNA_def_property_ui_text(prop, "File", - "The file to use, depending on the mode (e.g. the blend file to load or a destination " - "for saving a screenshot) - use the \"//\" prefix for a relative path"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - /*XXX to do: an operator that calls file_browse with relative_path on and blender filtering active */ -} - -static void rna_def_visibility_actuator(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - srna = RNA_def_struct(brna, "VisibilityActuator", "Actuator"); - RNA_def_struct_ui_text(srna, "Visibility Actuator", "Actuator to set visibility and occlusion of the object"); - RNA_def_struct_sdna_from(srna, "bVisibilityActuator", "data"); - - prop = RNA_def_property(srna, "use_visible", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", ACT_VISIBILITY_INVISIBLE); - RNA_def_property_ui_text(prop, "Visible", - "Set the objects visible (initialized from the object render restriction toggle in " - "physics button)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_occlusion", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_VISIBILITY_OCCLUSION); - RNA_def_property_ui_text(prop, "Occlusion", - "Set the object to occlude objects behind it (initialized from the object type in " - "physics button)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "apply_to_children", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_VISIBILITY_RECURSIVE); - RNA_def_property_ui_text(prop, "Children", - "Set all the children of this object to the same visibility/occlusion recursively"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -static void rna_def_twodfilter_actuator(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - static const EnumPropertyItem prop_type_items[] = { - {ACT_2DFILTER_ENABLED, "ENABLE", 0, "Enable Filter", ""}, - {ACT_2DFILTER_DISABLED, "DISABLE", 0, "Disable Filter", ""}, - {ACT_2DFILTER_NOFILTER, "REMOVE", 0, "Remove Filter", ""}, - {ACT_2DFILTER_MOTIONBLUR, "MOTIONBLUR", 0, "Motion Blur", ""}, - {ACT_2DFILTER_BLUR, "BLUR", 0, "Blur", ""}, - {ACT_2DFILTER_SHARPEN, "SHARPEN", 0, "Sharpen", ""}, - {ACT_2DFILTER_DILATION, "DILATION", 0, "Dilation", ""}, - {ACT_2DFILTER_EROSION, "EROSION", 0, "Erosion", ""}, - {ACT_2DFILTER_LAPLACIAN, "LAPLACIAN", 0, "Laplacian", ""}, - {ACT_2DFILTER_SOBEL, "SOBEL", 0, "Sobel", ""}, - {ACT_2DFILTER_PREWITT, "PREWITT", 0, "Prewitt", ""}, - {ACT_2DFILTER_GRAYSCALE, "GRAYSCALE", 0, "Gray Scale", ""}, - {ACT_2DFILTER_SEPIA, "SEPIA", 0, "Sepia", ""}, - {ACT_2DFILTER_INVERT, "INVERT", 0, "Invert", ""}, - {ACT_2DFILTER_CUSTOMFILTER, "CUSTOMFILTER", 0, "Custom Filter", ""}, -/* {ACT_2DFILTER_NUMBER_OF_FILTERS, "", 0, "Do not use it. Sentinel", ""}, */ - {0, NULL, 0, NULL, NULL} - }; - - srna = RNA_def_struct(brna, "Filter2DActuator", "Actuator"); - RNA_def_struct_ui_text(srna, "Filter 2D Actuator", "Actuator to apply screen graphic effects"); - RNA_def_struct_sdna_from(srna, "bTwoDFilterActuator", "data"); - - prop = RNA_def_property(srna, "mode", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "type"); - RNA_def_property_enum_items(prop, prop_type_items); - RNA_def_property_ui_text(prop, "Filter 2D Type", ""); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "glsl_shader", PROP_POINTER, PROP_NONE); - RNA_def_property_pointer_sdna(prop, NULL, "text"); - RNA_def_property_struct_type(prop, "Text"); - RNA_def_property_flag(prop, PROP_EDITABLE); - RNA_def_property_ui_text(prop, "Script", ""); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "filter_pass", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "int_arg"); - RNA_def_property_ui_text(prop, "Pass Number", "Set filter order"); - RNA_def_property_range(prop, 0, 99); /*MAX_RENDER_PASS-1 */ - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "motion_blur_factor", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "float_arg"); - RNA_def_property_ui_text(prop, "Value", "Motion blur factor"); - RNA_def_property_range(prop, 0.0, 1.0); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* booleans */ - prop = RNA_def_property(srna, "use_motion_blur", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", 1); - RNA_def_property_ui_text(prop, "Enable", "Enable/Disable Motion Blur"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -static void rna_def_parent_actuator(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - static const EnumPropertyItem prop_type_items[] = { - {ACT_PARENT_SET, "SETPARENT", 0, "Set Parent", ""}, - {ACT_PARENT_REMOVE, "REMOVEPARENT", 0, "Remove Parent", ""}, - {0, NULL, 0, NULL, NULL} - }; - - srna = RNA_def_struct(brna, "ParentActuator", "Actuator"); - RNA_def_struct_ui_text(srna, "Parent Actuator", ""); - RNA_def_struct_sdna_from(srna, "bParentActuator", "data"); - - prop = RNA_def_property(srna, "mode", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "type"); - RNA_def_property_enum_items(prop, prop_type_items); - RNA_def_property_ui_text(prop, "Scene", ""); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "object", PROP_POINTER, PROP_NONE); - RNA_def_property_struct_type(prop, "Object"); - RNA_def_property_pointer_sdna(prop, NULL, "ob"); - RNA_def_property_flag(prop, PROP_EDITABLE); - RNA_def_property_ui_text(prop, "Parent Object", "Set this object as parent"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* booleans */ - prop = RNA_def_property(srna, "use_compound", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", ACT_PARENT_COMPOUND); - RNA_def_property_ui_text(prop, "Compound", - "Add this object shape to the parent shape " - "(only if the parent shape is already compound)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_ghost", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", ACT_PARENT_GHOST); - RNA_def_property_ui_text(prop, "Ghost", "Make this object ghost while parented"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -static void rna_def_state_actuator(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - static const EnumPropertyItem prop_type_items[] = { - {ACT_STATE_SET, "SET", 0, "Set State", ""}, - {ACT_STATE_ADD, "ADD", 0, "Add State", ""}, - {ACT_STATE_REMOVE, "REMOVE", 0, "Remove State", ""}, - {ACT_STATE_CHANGE, "CHANGE", 0, "Change State", ""}, - {0, NULL, 0, NULL, NULL} - }; - - srna = RNA_def_struct(brna, "StateActuator", "Actuator"); - RNA_def_struct_ui_text(srna, "State Actuator", "Actuator to handle states"); - RNA_def_struct_sdna_from(srna, "bStateActuator", "data"); - - prop = RNA_def_property(srna, "operation", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "type"); - RNA_def_property_enum_items(prop, prop_type_items); - RNA_def_property_ui_text(prop, "Operation", "Select the bit operation on object state mask"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "states", PROP_BOOLEAN, PROP_LAYER_MEMBER); - RNA_def_property_boolean_sdna(prop, NULL, "mask", 1); - RNA_def_property_array(prop, OB_MAX_STATES); - RNA_def_property_ui_text(prop, "State", ""); - RNA_def_property_boolean_funcs(prop, NULL, "rna_StateActuator_state_set"); -} - -static void rna_def_armature_actuator(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - static const EnumPropertyItem prop_type_items[] = { - {ACT_ARM_RUN, "RUN", 0, "Run Armature", ""}, - {ACT_ARM_ENABLE, "ENABLE", 0, "Enable", ""}, - {ACT_ARM_DISABLE, "DISABLE", 0, "Disable", ""}, - {ACT_ARM_SETTARGET, "SETTARGET", 0, "Set Target", ""}, - {ACT_ARM_SETWEIGHT, "SETWEIGHT", 0, "Set Weight", ""}, - {ACT_ARM_SETINFLUENCE, "SETINFLUENCE", 0, "Set Influence", ""}, - {0, NULL, 0, NULL, NULL} - }; - - srna = RNA_def_struct(brna, "ArmatureActuator", "Actuator"); - RNA_def_struct_ui_text(srna, "Armature Actuator", ""); - RNA_def_struct_sdna_from(srna, "bArmatureActuator", "data"); - - prop = RNA_def_property(srna, "mode", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "type"); - RNA_def_property_enum_items(prop, prop_type_items); - RNA_def_property_ui_text(prop, "Constraint Type", ""); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "bone", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "posechannel"); - RNA_def_property_ui_text(prop, "Bone", "Bone on which the constraint is defined"); - RNA_def_property_update(prop, NC_LOGIC, "rna_Actuator_Armature_update"); - - prop = RNA_def_property(srna, "constraint", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "constraint"); - RNA_def_property_ui_text(prop, "Constraint", "Name of the constraint to control"); - RNA_def_property_update(prop, NC_LOGIC, "rna_Actuator_Armature_update"); - - prop = RNA_def_property(srna, "target", PROP_POINTER, PROP_NONE); - RNA_def_property_struct_type(prop, "Object"); - RNA_def_property_flag(prop, PROP_EDITABLE); - RNA_def_property_ui_text(prop, "Target", "Set this object as the target of the constraint"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "secondary_target", PROP_POINTER, PROP_NONE); - RNA_def_property_pointer_sdna(prop, NULL, "subtarget"); - RNA_def_property_struct_type(prop, "Object"); - RNA_def_property_flag(prop, PROP_EDITABLE); - RNA_def_property_ui_text(prop, "Secondary Target", - "Set this object as the secondary target of the constraint " - "(only IK polar target at the moment)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "weight", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "weight"); - RNA_def_property_range(prop, 0.0, 1.0); - RNA_def_property_ui_text(prop, "Weight", "Weight of this constraint"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "influence", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "influence"); - RNA_def_property_range(prop, 0.0, 1.0); - RNA_def_property_ui_text(prop, "Influence", "Influence of this constraint"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -static void rna_def_steering_actuator(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - static const EnumPropertyItem prop_type_items[] = { - {ACT_STEERING_SEEK, "SEEK", 0, "Seek", ""}, - {ACT_STEERING_FLEE, "FLEE", 0, "Flee", ""}, - {ACT_STEERING_PATHFOLLOWING, "PATHFOLLOWING", 0, "Path following", ""}, - {0, NULL, 0, NULL, NULL} - }; - - static const EnumPropertyItem facingaxis_items[] = { - {1, "X", 0, "X", ""}, - {2, "Y", 0, "Y", ""}, - {3, "Z", 0, "Z", ""}, - {4, "NEG_X", 0, "-X", ""}, - {5, "NEG_Y", 0, "-Y", ""}, - {6, "NEG_Z", 0, "-Z", ""}, - {0, NULL, 0, NULL, NULL} - }; - - srna = RNA_def_struct(brna, "SteeringActuator", "Actuator"); - RNA_def_struct_ui_text(srna, "Steering Actuator", ""); - RNA_def_struct_sdna_from(srna, "bSteeringActuator", "data"); - - prop = RNA_def_property(srna, "mode", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "type"); - RNA_def_property_enum_items(prop, prop_type_items); - RNA_def_property_ui_text(prop, "Behavior", ""); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "velocity", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "velocity"); - RNA_def_property_range(prop, 0.0, 1000.0); - RNA_def_property_ui_text(prop, "Velocity", "Velocity magnitude"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "acceleration", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "acceleration"); - RNA_def_property_range(prop, 0.0, 1000.0); - RNA_def_property_ui_text(prop, "Acceleration", "Max acceleration"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "turn_speed", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "turnspeed"); - RNA_def_property_range(prop, 0.0, 720.0); - RNA_def_property_ui_text(prop, "Turn Speed", "Max turn speed"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "distance", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "dist"); - RNA_def_property_range(prop, 0.0, 1000.0); - RNA_def_property_ui_text(prop, "Dist", "Relax distance"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "target", PROP_POINTER, PROP_NONE); - RNA_def_property_struct_type(prop, "Object"); - RNA_def_property_pointer_sdna(prop, NULL, "target"); - RNA_def_property_flag(prop, PROP_EDITABLE); - RNA_def_property_ui_text(prop, "Target Object", "Target object"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "self_terminated", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_STEERING_SELFTERMINATED); - RNA_def_property_ui_text(prop, "Self Terminated", "Terminate when target is reached"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "show_visualization", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_STEERING_ENABLEVISUALIZATION); - RNA_def_property_ui_text(prop, "Visualize", "Enable debug visualization for 'Path following'"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "update_period", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "updateTime"); - RNA_def_property_ui_range(prop, -1, 100000, 1, 1); - RNA_def_property_ui_text(prop, "Update period", "Path update period"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "navmesh", PROP_POINTER, PROP_NONE); - RNA_def_property_struct_type(prop, "Object"); - RNA_def_property_pointer_sdna(prop, NULL, "navmesh"); - RNA_def_property_flag(prop, PROP_EDITABLE); - RNA_def_property_ui_text(prop, "Navigation Mesh Object", "Navigation mesh"); - RNA_def_property_pointer_funcs(prop, NULL, "rna_SteeringActuator_navmesh_set", NULL, NULL); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "facing", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_STEERING_AUTOMATICFACING); - RNA_def_property_ui_text(prop, "Facing", "Enable automatic facing"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "facing_axis", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "facingaxis"); - RNA_def_property_enum_items(prop, facingaxis_items); - RNA_def_property_ui_text(prop, "Axis", "Axis for automatic facing"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "normal_up", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_STEERING_NORMALUP); - RNA_def_property_ui_text(prop, "N", "Use normal of the navmesh to set \"UP\" vector"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "lock_z_velocity", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_STEERING_LOCKZVEL); - RNA_def_property_ui_text(prop, "Lock Z velocity", "Disable simulation of linear motion along Z axis"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -static void rna_def_mouse_actuator(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - static const EnumPropertyItem prop_type_items[] = { - {ACT_MOUSE_VISIBILITY, "VISIBILITY", 0, "Visibility", ""}, - {ACT_MOUSE_LOOK, "LOOK", 0, "Look", ""}, - {0, NULL, 0, NULL, NULL} - }; - - static const EnumPropertyItem prop_object_axis_items[] = { - {ACT_MOUSE_OBJECT_AXIS_X, "OBJECT_AXIS_X", 0, "X Axis", ""}, - {ACT_MOUSE_OBJECT_AXIS_Y, "OBJECT_AXIS_Y", 0, "Y Axis", ""}, - {ACT_MOUSE_OBJECT_AXIS_Z, "OBJECT_AXIS_Z", 0, "Z Axis", ""}, - {0, NULL, 0, NULL, NULL} - }; - - srna = RNA_def_struct(brna, "MouseActuator", "Actuator"); - RNA_def_struct_ui_text(srna, "Mouse Actuator", ""); - RNA_def_struct_sdna_from(srna, "bMouseActuator", "data"); - - prop = RNA_def_property(srna, "mode", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "type"); - RNA_def_property_enum_items(prop, prop_type_items); - RNA_def_property_ui_text(prop, "Mode", ""); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* Visibility */ - prop = RNA_def_property(srna, "visible", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_MOUSE_VISIBLE); - RNA_def_property_ui_text(prop, "Visible", "Make mouse cursor visible"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* Mouse Look */ - prop = RNA_def_property(srna, "use_axis_x", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_MOUSE_USE_AXIS_X); - RNA_def_property_ui_text(prop, "Use X Axis", "Calculate mouse movement on the X axis"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_axis_y", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_MOUSE_USE_AXIS_Y); - RNA_def_property_ui_text(prop, "Use Y Axis", "Calculate mouse movement on the Y axis"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "reset_x", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_MOUSE_RESET_X); - RNA_def_property_ui_text(prop, "Reset", - "Reset the cursor's X position to the center of the screen space after calculating"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "reset_y", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_MOUSE_RESET_Y); - RNA_def_property_ui_text(prop, "Reset", - "Reset the cursor's Y position to the center of the screen space after calculating"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "local_x", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_MOUSE_LOCAL_X); - RNA_def_property_ui_text(prop, "Local", "Apply rotation locally"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "local_y", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", ACT_MOUSE_LOCAL_Y); - RNA_def_property_ui_text(prop, "Local", "Apply rotation locally"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "threshold_x", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "threshold[0]"); - RNA_def_property_ui_range(prop, 0, 0.5, 1, 3); - RNA_def_property_ui_text(prop, "Threshold", "Amount of X motion before mouse movement will register"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "threshold_y", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "threshold[1]"); - RNA_def_property_ui_range(prop, 0, 0.5, 1, 3); - RNA_def_property_ui_text(prop, "Threshold", "Amount of Y motion before mouse movement will register"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "object_axis_x", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "object_axis[0]"); - RNA_def_property_enum_items(prop, prop_object_axis_items); - RNA_def_property_ui_text(prop, "Object Axis", "Local object axis mouse movement in the X direction will apply to"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "object_axis_y", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "object_axis[1]"); - RNA_def_property_enum_items(prop, prop_object_axis_items); - RNA_def_property_ui_text(prop, "Object Axis", "Local object axis mouse movement in the Y direction will apply to"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "sensitivity_x", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "sensitivity[0]"); - RNA_def_property_ui_range(prop, -100.0, 100.0, 0.2, 3); - RNA_def_property_ui_text(prop, "Sensitivity", "Sensitivity of the X axis"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "sensitivity_y", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "sensitivity[1]"); - RNA_def_property_ui_range(prop, -100.0, 100.0, 0.2, 3); - RNA_def_property_ui_text(prop, "Sensitivity", "Sensitivity of the Y axis"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "min_x", PROP_FLOAT, PROP_ANGLE); - RNA_def_property_float_sdna(prop, NULL, "limit_x[0]"); - RNA_def_property_ui_range(prop, DEG2RADF(-3600.0f), 0.0, 9, 3); - RNA_def_property_ui_text(prop, "Min", "Maximum negative rotation allowed by X mouse movement (0 for infinite)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "max_x", PROP_FLOAT, PROP_ANGLE); - RNA_def_property_float_sdna(prop, NULL, "limit_x[1]"); - RNA_def_property_ui_range(prop, 0.0, DEG2RADF(3600.0f), 9, 3); - RNA_def_property_ui_text(prop, "Max", "Maximum positive rotation allowed by X mouse movement (0 for infinite)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "min_y", PROP_FLOAT, PROP_ANGLE); - RNA_def_property_float_sdna(prop, NULL, "limit_y[0]"); - RNA_def_property_ui_range(prop, DEG2RADF(-3600.0f), 0.0, 9, 3); - RNA_def_property_ui_text(prop, "Min", "Maximum negative rotation allowed by Y mouse movement (0 for infinite)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "max_y", PROP_FLOAT, PROP_ANGLE); - RNA_def_property_float_sdna(prop, NULL, "limit_y[1]"); - RNA_def_property_ui_range(prop, 0.0, DEG2RADF(3600.0f), 9, 3); - RNA_def_property_ui_text(prop, "Max", "Maximum positive rotation allowed by Y mouse movement (0 for infinite)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -void RNA_def_actuator(BlenderRNA *brna) -{ - rna_def_actuator(brna); - - rna_def_action_actuator(brna); - rna_def_object_actuator(brna); - rna_def_camera_actuator(brna); - rna_def_sound_actuator(brna); - rna_def_property_actuator(brna); - rna_def_constraint_actuator(brna); - rna_def_edit_object_actuator(brna); - rna_def_scene_actuator(brna); - rna_def_random_actuator(brna); - rna_def_message_actuator(brna); - rna_def_game_actuator(brna); - rna_def_visibility_actuator(brna); - rna_def_twodfilter_actuator(brna); - rna_def_parent_actuator(brna); - rna_def_state_actuator(brna); - rna_def_armature_actuator(brna); - rna_def_steering_actuator(brna); - rna_def_mouse_actuator(brna); -} - -#endif diff --git a/source/blender/makesrna/intern/rna_actuator_api.c b/source/blender/makesrna/intern/rna_actuator_api.c deleted file mode 100644 index 23fdd8a1d5b..00000000000 --- a/source/blender/makesrna/intern/rna_actuator_api.c +++ /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) 2010 Blender Foundation. - * All rights reserved. - * - * - * Contributor(s): - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file blender/makesrna/intern/rna_actuator_api.c - * \ingroup RNA - */ - - -#include -#include - -#include "WM_types.h" -#include "RNA_define.h" - -#include "rna_internal.h" /* own include */ - -#ifdef RNA_RUNTIME - -#include "BKE_sca.h" -#include "DNA_controller_types.h" -#include "DNA_actuator_types.h" - -static void rna_Actuator_link(bActuator *act, bController *cont) -{ - link_logicbricks((void **)&act, (void ***)&(cont->links), &cont->totlinks, sizeof(bActuator *)); -} - -static void rna_Actuator_unlink(bActuator *act, bController *cont) -{ - unlink_logicbricks((void **)&act, (void ***)&(cont->links), &cont->totlinks); -} - -#else - -void RNA_api_actuator(StructRNA *srna) -{ - FunctionRNA *func; - PropertyRNA *parm; - - func = RNA_def_function(srna, "link", "rna_Actuator_link"); - RNA_def_function_ui_description(func, "Link the actuator to a controller"); - parm = RNA_def_pointer(func, "controller", "Controller", "", "Controller to link to"); - RNA_def_parameter_flags(parm, 0, PARM_REQUIRED); - RNA_def_property_update(parm, NC_LOGIC, NULL); - - func = RNA_def_function(srna, "unlink", "rna_Actuator_unlink"); - RNA_def_function_ui_description(func, "Unlink the actuator from a controller"); - parm = RNA_def_pointer(func, "controller", "Controller", "", "Controller to unlink from"); - RNA_def_parameter_flags(parm, 0, PARM_REQUIRED); - RNA_def_property_update(parm, NC_LOGIC, NULL); -} - -#endif - diff --git a/source/blender/makesrna/intern/rna_armature.c b/source/blender/makesrna/intern/rna_armature.c index 05074bc9f16..3afa682e75f 100644 --- a/source/blender/makesrna/intern/rna_armature.c +++ b/source/blender/makesrna/intern/rna_armature.c @@ -989,11 +989,6 @@ static void rna_def_armature(BlenderRNA *brna) {ARM_WIRE, "WIRE", 0, "Wire", "Display bones as thin wires, showing subdivision and B-Splines"}, {0, NULL, 0, NULL, NULL} }; - static const EnumPropertyItem prop_vdeformer[] = { - {ARM_VDEF_BLENDER, "BLENDER", 0, "Blender", "Use Blender's armature vertex deformation"}, - {ARM_VDEF_BGE_CPU, "BGE_CPU", 0, "BGE", "Use vertex deformation code optimized for the BGE"}, - {0, NULL, 0, NULL, NULL} - }; static const EnumPropertyItem prop_ghost_type_items[] = { {ARM_GHOST_CUR, "CURRENT_FRAME", 0, "Around Frame", "Display Ghosts of poses within a fixed number of frames around the current frame"}, @@ -1050,13 +1045,6 @@ static void rna_def_armature(BlenderRNA *brna) RNA_def_property_update(prop, 0, "rna_Armature_redraw_data"); RNA_def_property_flag(prop, PROP_LIB_EXCEPTION); - prop = RNA_def_property(srna, "deform_method", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "gevertdeformer"); - RNA_def_property_enum_items(prop, prop_vdeformer); - RNA_def_property_ui_text(prop, "Vertex Deformer", "Vertex Deformer Method (Game Engine only)"); - RNA_def_property_update(prop, 0, "rna_Armature_redraw_data"); - RNA_def_property_flag(prop, PROP_LIB_EXCEPTION); - /* XXX deprecated ....... old animviz for armatures only */ prop = RNA_def_property(srna, "ghost_type", PROP_ENUM, PROP_NONE); RNA_def_property_enum_sdna(prop, NULL, "ghosttype"); diff --git a/source/blender/makesrna/intern/rna_constraint.c b/source/blender/makesrna/intern/rna_constraint.c index 8eb6bc1261e..97114e02e48 100644 --- a/source/blender/makesrna/intern/rna_constraint.c +++ b/source/blender/makesrna/intern/rna_constraint.c @@ -100,8 +100,8 @@ const EnumPropertyItem rna_enum_constraint_type_items[] = { "Use to animate an object/bone following a path"}, {CONSTRAINT_TYPE_PIVOT, "PIVOT", ICON_CONSTRAINT_DATA, "Pivot", "Change pivot point for transforms (buggy)"}, - {CONSTRAINT_TYPE_RIGIDBODYJOINT, "RIGID_BODY_JOINT", ICON_CONSTRAINT_DATA, "Rigid Body Joint", - "Use to define a Rigid Body Constraint (for Game Engine use only)"}, + /* {CONSTRAINT_TYPE_RIGIDBODYJOINT, "RIGID_BODY_JOINT", ICON_CONSTRAINT_DATA, "Rigid Body Joint", + "Use to define a Rigid Body Constraint (for Game Engine use only)"}, */ /* {CONSTRAINT_TYPE_PYTHON, "SCRIPT", ICON_CONSTRAINT_DATA, "Script", "Custom constraint(s) written in Python (Not yet implemented)"}, */ {CONSTRAINT_TYPE_SHRINKWRAP, "SHRINKWRAP", ICON_CONSTRAINT_DATA, "Shrinkwrap", @@ -190,8 +190,6 @@ static StructRNA *rna_ConstraintType_refine(struct PointerRNA *ptr) return &RNA_StretchToConstraint; case CONSTRAINT_TYPE_MINMAX: return &RNA_FloorConstraint; - case CONSTRAINT_TYPE_RIGIDBODYJOINT: - return &RNA_RigidBodyJointConstraint; case CONSTRAINT_TYPE_CLAMPTO: return &RNA_ClampToConstraint; case CONSTRAINT_TYPE_TRANSFORM: @@ -1419,178 +1417,6 @@ static void rna_def_constraint_stretch_to(BlenderRNA *brna) RNA_def_property_update(prop, NC_OBJECT | ND_CONSTRAINT, "rna_Constraint_update"); } -static void rna_def_constraint_rigid_body_joint(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - static const EnumPropertyItem pivot_items[] = { - {CONSTRAINT_RB_BALL, "BALL", 0, "Ball", "Allow rotations around all axes"}, - {CONSTRAINT_RB_HINGE, "HINGE", 0, "Hinge", "Work in one plane, allow rotations around one axis only"}, - {CONSTRAINT_RB_CONETWIST, "CONE_TWIST", 0, "Cone Twist", - "Allow rotations around all axes with limits for the cone and twist axes"}, - {CONSTRAINT_RB_GENERIC6DOF, "GENERIC_6_DOF", 0, "Generic 6 DoF", - "No constraints by default, limits can be set individually"}, - {0, NULL, 0, NULL, NULL} - }; - - srna = RNA_def_struct(brna, "RigidBodyJointConstraint", "Constraint"); - RNA_def_struct_ui_text(srna, "Rigid Body Joint Constraint", "For use with the Game Engine"); - RNA_def_struct_sdna_from(srna, "bRigidBodyJointConstraint", "data"); - - prop = RNA_def_property(srna, "target", PROP_POINTER, PROP_NONE); - RNA_def_property_pointer_sdna(prop, NULL, "tar"); - RNA_def_property_ui_text(prop, "Target", "Target Object"); - RNA_def_property_flag(prop, PROP_EDITABLE); - RNA_def_property_update(prop, NC_OBJECT | ND_CONSTRAINT, "rna_Constraint_dependency_update"); - - prop = RNA_def_property(srna, "child", PROP_POINTER, PROP_NONE); - RNA_def_property_ui_text(prop, "Child Object", "Child object"); - RNA_def_property_flag(prop, PROP_EDITABLE); - RNA_def_property_update(prop, NC_OBJECT | ND_CONSTRAINT, "rna_Constraint_dependency_update"); - - prop = RNA_def_property(srna, "pivot_type", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "type"); - RNA_def_property_enum_items(prop, pivot_items); - RNA_def_property_ui_text(prop, "Pivot Type", ""); - RNA_def_property_update(prop, NC_OBJECT | ND_CONSTRAINT, "rna_Constraint_update"); - - prop = RNA_def_property(srna, "pivot_x", PROP_FLOAT, PROP_DISTANCE); - RNA_def_property_float_sdna(prop, NULL, "pivX"); - RNA_def_property_range(prop, -1000.0, 1000.f); - RNA_def_property_ui_text(prop, "Pivot X", "Offset pivot on X"); - RNA_def_property_update(prop, NC_OBJECT | ND_CONSTRAINT, "rna_Constraint_update"); - - prop = RNA_def_property(srna, "pivot_y", PROP_FLOAT, PROP_DISTANCE); - RNA_def_property_float_sdna(prop, NULL, "pivY"); - RNA_def_property_range(prop, -1000.0, 1000.f); - RNA_def_property_ui_text(prop, "Pivot Y", "Offset pivot on Y"); - RNA_def_property_update(prop, NC_OBJECT | ND_CONSTRAINT, "rna_Constraint_update"); - - prop = RNA_def_property(srna, "pivot_z", PROP_FLOAT, PROP_DISTANCE); - RNA_def_property_float_sdna(prop, NULL, "pivZ"); - RNA_def_property_range(prop, -1000.0, 1000.f); - RNA_def_property_ui_text(prop, "Pivot Z", "Offset pivot on Z"); - RNA_def_property_update(prop, NC_OBJECT | ND_CONSTRAINT, "rna_Constraint_update"); - - prop = RNA_def_property(srna, "axis_x", PROP_FLOAT, PROP_ANGLE); - RNA_def_property_float_sdna(prop, NULL, "axX"); - RNA_def_property_range(prop, -M_PI * 2, M_PI * 2); - RNA_def_property_ui_text(prop, "Axis X", "Rotate pivot on X axis"); - RNA_def_property_update(prop, NC_OBJECT | ND_CONSTRAINT, "rna_Constraint_update"); - - prop = RNA_def_property(srna, "axis_y", PROP_FLOAT, PROP_ANGLE); - RNA_def_property_float_sdna(prop, NULL, "axY"); - RNA_def_property_range(prop, -M_PI * 2, M_PI * 2); - RNA_def_property_ui_text(prop, "Axis Y", "Rotate pivot on Y axis"); - RNA_def_property_update(prop, NC_OBJECT | ND_CONSTRAINT, "rna_Constraint_update"); - - prop = RNA_def_property(srna, "axis_z", PROP_FLOAT, PROP_ANGLE); - RNA_def_property_float_sdna(prop, NULL, "axZ"); - RNA_def_property_range(prop, -M_PI * 2, M_PI * 2); - RNA_def_property_ui_text(prop, "Axis Z", "Rotate pivot on Z axis"); - RNA_def_property_update(prop, NC_OBJECT | ND_CONSTRAINT, "rna_Constraint_update"); - - prop = RNA_def_property(srna, "use_linked_collision", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", CONSTRAINT_DISABLE_LINKED_COLLISION); - RNA_def_property_ui_text(prop, "Disable Linked Collision", "Disable collision between linked bodies"); - RNA_def_property_update(prop, NC_OBJECT | ND_CONSTRAINT, "rna_Constraint_update"); - - prop = RNA_def_property(srna, "show_pivot", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", CONSTRAINT_DRAW_PIVOT); - RNA_def_property_ui_text(prop, "Draw Pivot", "Display the pivot point and rotation in 3D view"); - RNA_def_property_update(prop, NC_OBJECT | ND_CONSTRAINT, "rna_Constraint_update"); - - - /* Limits */ - /* Limit Min/Max */ - prop = RNA_def_property(srna, "limit_min_x", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "minLimit[0]"); - RNA_def_property_ui_text(prop, "Minimum Limit X", ""); - - prop = RNA_def_property(srna, "limit_min_y", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "minLimit[1]"); - RNA_def_property_ui_text(prop, "Minimum Limit Y", ""); - - prop = RNA_def_property(srna, "limit_min_z", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "minLimit[2]"); - RNA_def_property_ui_text(prop, "Minimum Limit Z", ""); - - prop = RNA_def_property(srna, "limit_max_x", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "maxLimit[0]"); - RNA_def_property_ui_text(prop, "Maximum Limit X", ""); - - prop = RNA_def_property(srna, "limit_max_y", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "maxLimit[1]"); - RNA_def_property_ui_text(prop, "Maximum Limit Y", ""); - - prop = RNA_def_property(srna, "limit_max_z", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "maxLimit[2]"); - RNA_def_property_ui_text(prop, "Maximum Limit Z", ""); - - /* Limit Min/Max for angle */ - prop = RNA_def_property(srna, "limit_angle_min_x", PROP_FLOAT, PROP_ANGLE); - RNA_def_property_float_sdna(prop, NULL, "minLimit[3]"); - RNA_def_property_range(prop, -M_PI * 2, M_PI * 2); - RNA_def_property_ui_text(prop, "Minimum Angular Limit X", ""); - - prop = RNA_def_property(srna, "limit_angle_min_y", PROP_FLOAT, PROP_ANGLE); - RNA_def_property_float_sdna(prop, NULL, "minLimit[4]"); - RNA_def_property_range(prop, -M_PI * 2, M_PI * 2); - RNA_def_property_ui_text(prop, "Minimum Angular Limit Y", ""); - - prop = RNA_def_property(srna, "limit_angle_min_z", PROP_FLOAT, PROP_ANGLE); - RNA_def_property_float_sdna(prop, NULL, "minLimit[5]"); - RNA_def_property_range(prop, -M_PI * 2, M_PI * 2); - RNA_def_property_ui_text(prop, "Minimum Angular Limit Z", ""); - - prop = RNA_def_property(srna, "limit_angle_max_x", PROP_FLOAT, PROP_ANGLE); - RNA_def_property_float_sdna(prop, NULL, "maxLimit[3]"); - RNA_def_property_range(prop, -M_PI * 2, M_PI * 2); - RNA_def_property_ui_text(prop, "Maximum Angular Limit X", ""); - - prop = RNA_def_property(srna, "limit_angle_max_y", PROP_FLOAT, PROP_ANGLE); - RNA_def_property_float_sdna(prop, NULL, "maxLimit[4]"); - RNA_def_property_range(prop, -M_PI * 2, M_PI * 2); - RNA_def_property_ui_text(prop, "Maximum Angular Limit Y", ""); - - prop = RNA_def_property(srna, "limit_angle_max_z", PROP_FLOAT, PROP_ANGLE); - RNA_def_property_float_sdna(prop, NULL, "maxLimit[5]"); - RNA_def_property_range(prop, -M_PI * 2, M_PI * 2); - RNA_def_property_ui_text(prop, "Maximum Angular Limit Z", ""); - - /* Limit Booleans */ - prop = RNA_def_property(srna, "use_limit_x", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", 1); - RNA_def_property_ui_text(prop, "Limit X", "Use minimum/maximum X limit"); - RNA_def_property_update(prop, NC_OBJECT | ND_CONSTRAINT, "rna_Constraint_update"); - - prop = RNA_def_property(srna, "use_limit_y", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", 2); - RNA_def_property_ui_text(prop, "Limit Y", "Use minimum/maximum y limit"); - RNA_def_property_update(prop, NC_OBJECT | ND_CONSTRAINT, "rna_Constraint_update"); - - prop = RNA_def_property(srna, "use_limit_z", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", 4); - RNA_def_property_ui_text(prop, "Limit Z", "Use minimum/maximum z limit"); - RNA_def_property_update(prop, NC_OBJECT | ND_CONSTRAINT, "rna_Constraint_update"); - - prop = RNA_def_property(srna, "use_angular_limit_x", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", 8); - RNA_def_property_ui_text(prop, "Angular X Limit", "Use minimum/maximum X angular limit"); - RNA_def_property_update(prop, NC_OBJECT | ND_CONSTRAINT, "rna_Constraint_update"); - - prop = RNA_def_property(srna, "use_angular_limit_y", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", 16); - RNA_def_property_ui_text(prop, "Angular Y Limit", "Use minimum/maximum Y angular limit"); - RNA_def_property_update(prop, NC_OBJECT | ND_CONSTRAINT, "rna_Constraint_update"); - - prop = RNA_def_property(srna, "use_angular_limit_z", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", 32); - RNA_def_property_ui_text(prop, "Angular Z Limit", "Use minimum/maximum Z angular limit"); - RNA_def_property_update(prop, NC_OBJECT | ND_CONSTRAINT, "rna_Constraint_update"); -} - static void rna_def_constraint_clamp_to(BlenderRNA *brna) { StructRNA *srna; @@ -2718,7 +2544,6 @@ void RNA_def_constraint(BlenderRNA *brna) rna_def_constraint_minmax(brna); rna_def_constraint_track_to(brna); rna_def_constraint_kinematic(brna); - rna_def_constraint_rigid_body_joint(brna); rna_def_constraint_clamp_to(brna); rna_def_constraint_distance_limit(brna); rna_def_constraint_size_limit(brna); diff --git a/source/blender/makesrna/intern/rna_controller.c b/source/blender/makesrna/intern/rna_controller.c deleted file mode 100644 index bdb3daedebb..00000000000 --- a/source/blender/makesrna/intern/rna_controller.c +++ /dev/null @@ -1,327 +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): Blender Foundation (2008). - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file blender/makesrna/intern/rna_controller.c - * \ingroup RNA - */ - -#include - -#include "DNA_object_types.h" -#include "DNA_controller_types.h" - -#include "BLI_string_utils.h" -#include "BLI_utildefines.h" - -#include "BLT_translation.h" - -#include "RNA_define.h" -#include "RNA_enum_types.h" - -#include "rna_internal.h" - -#include "WM_types.h" - -const EnumPropertyItem rna_enum_controller_type_items[] = { - {CONT_LOGIC_AND, "LOGIC_AND", 0, "And", "Logic And"}, - {CONT_LOGIC_OR, "LOGIC_OR", 0, "Or", "Logic Or"}, - {CONT_LOGIC_NAND, "LOGIC_NAND", 0, "Nand", "Logic Nand"}, - {CONT_LOGIC_NOR, "LOGIC_NOR", 0, "Nor", "Logic Nor"}, - {CONT_LOGIC_XOR, "LOGIC_XOR", 0, "Xor", "Logic Xor"}, - {CONT_LOGIC_XNOR, "LOGIC_XNOR", 0, "Xnor", "Logic Xnor"}, - {CONT_EXPRESSION, "EXPRESSION", 0, "Expression", ""}, - {CONT_PYTHON, "PYTHON", 0, "Python", ""}, - {0, NULL, 0, NULL, NULL} -}; - -#ifdef RNA_RUNTIME - -#include "BKE_sca.h" -#include "DNA_actuator_types.h" - -static StructRNA *rna_Controller_refine(struct PointerRNA *ptr) -{ - bController *controller = (bController *)ptr->data; - - switch (controller->type) { - case CONT_LOGIC_AND: - return &RNA_AndController; - case CONT_LOGIC_OR: - return &RNA_OrController; - case CONT_LOGIC_NAND: - return &RNA_NandController; - case CONT_LOGIC_NOR: - return &RNA_NorController; - case CONT_LOGIC_XOR: - return &RNA_XorController; - case CONT_LOGIC_XNOR: - return &RNA_XnorController; - case CONT_EXPRESSION: - return &RNA_ExpressionController; - case CONT_PYTHON: - return &RNA_PythonController; - default: - return &RNA_Controller; - } -} - -static void rna_Constroller_name_set(PointerRNA *ptr, const char *value) -{ - Object *ob = ptr->id.data; - bController *cont = ptr->data; - BLI_strncpy_utf8(cont->name, value, sizeof(cont->name)); - BLI_uniquename(&ob->controllers, cont, DATA_("Controller"), '.', offsetof(bController, name), sizeof(cont->name)); -} - -static void rna_Controller_type_set(struct PointerRNA *ptr, int value) -{ - bController *cont = (bController *)ptr->data; - - if (value != cont->type) { - cont->type = value; - init_controller(cont); - } -} - -static void rna_Controller_mode_set(struct PointerRNA *ptr, int value) -{ - bController *cont = (bController *)ptr->data; - bPythonCont *pycon = (bPythonCont *)cont->data; - - /* if mode changed and previous mode were Script */ - if (value != pycon->mode && pycon->mode == CONT_PY_SCRIPT) { - /* clear script to avoid it to get linked with the controller */ - pycon->text = NULL; - } - pycon->mode = value; -} - -static int rna_Controller_state_number_get(struct PointerRNA *ptr) -{ - bController *cont = (bController *)ptr->data; - int bit; - - for (bit = 0; bit < 32; bit++) { - if (cont->state_mask & (1u << bit)) - return bit + 1; - } - return 0; -} - -static void rna_Controller_state_number_set(struct PointerRNA *ptr, const int value) -{ - bController *cont = (bController *)ptr->data; - if (value < 1 || value > OB_MAX_STATES) - return; - - cont->state_mask = (1 << (value - 1)); -} - -static void rna_Controller_actuators_begin(CollectionPropertyIterator *iter, PointerRNA *ptr) -{ - bController *cont = (bController *)ptr->data; - rna_iterator_array_begin(iter, cont->links, sizeof(bActuator *), (int)cont->totlinks, 0, NULL); -} - -static int rna_Controller_actuators_length(PointerRNA *ptr) -{ - bController *cont = (bController *)ptr->data; - return (int) cont->totlinks; -} - -#if 0 /* editable is set to false, comment for now. */ -static void rna_Controller_state_get(PointerRNA *ptr, int *values) -{ - bController *cont = (bController *)ptr->data; - int i; - - memset(values, 0, sizeof(int) * OB_MAX_STATES); - for (i = 0; i < OB_MAX_STATES; i++) - values[i] = (cont->state_mask & (1 << i)); -} - -static void rna_Controller_state_set(PointerRNA *ptr, const int *values) -{ - bController *cont = (bController *)ptr->data; - int i, tot = 0; - - /* ensure we always have some state selected */ - for (i = 0; i < OB_MAX_STATES; i++) - if (values[i]) - tot++; - - if (tot == 0) - return; - - /* only works for one state at once */ - if (tot > 1) - return; - - for (i = 0; i < OB_MAX_STATES; i++) { - if (values[i]) cont->state_mask |= (1 << i); - else cont->state_mask &= ~(1 << i); - } -} -#endif - -#else - -void RNA_def_controller(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - static const EnumPropertyItem python_controller_modes[] = { - {CONT_PY_SCRIPT, "SCRIPT", 0, "Script", ""}, - {CONT_PY_MODULE, "MODULE", 0, "Module", ""}, - {0, NULL, 0, NULL, NULL} - }; - - /* Controller */ - srna = RNA_def_struct(brna, "Controller", NULL); - RNA_def_struct_sdna(srna, "bController"); - RNA_def_struct_refine_func(srna, "rna_Controller_refine"); - RNA_def_struct_ui_text(srna, "Controller", - "Game engine logic brick to process events, connecting sensors to actuators"); - - RNA_api_controller(srna); - - prop = RNA_def_property(srna, "name", PROP_STRING, PROP_NONE); - RNA_def_property_ui_text(prop, "Name", ""); - RNA_def_property_string_funcs(prop, NULL, NULL, "rna_Constroller_name_set"); - RNA_def_struct_name_property(srna, prop); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "type", PROP_ENUM, PROP_NONE); - RNA_def_property_clear_flag(prop, PROP_ANIMATABLE); - RNA_def_property_enum_funcs(prop, NULL, "rna_Controller_type_set", NULL); - RNA_def_property_enum_items(prop, rna_enum_controller_type_items); - RNA_def_property_ui_text(prop, "Type", ""); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "show_expanded", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", CONT_SHOW); - RNA_def_property_ui_text(prop, "Expanded", "Set controller expanded in the user interface"); - RNA_def_property_ui_icon(prop, ICON_TRIA_RIGHT, 1); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "active", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", CONT_DEACTIVATE); - RNA_def_property_ui_text(prop, "Active", "Set the active state of the controller"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_priority", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", CONT_PRIO); - RNA_def_property_ui_text(prop, "Priority", - "Mark controller for execution before all non-marked controllers " - "(good for startup scripts)"); - RNA_def_property_ui_icon(prop, ICON_BOOKMARKS, 1); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "actuators", PROP_COLLECTION, PROP_NONE); - RNA_def_property_collection_sdna(prop, NULL, "links", NULL); - RNA_def_property_struct_type(prop, "Actuator"); - RNA_def_property_ui_text(prop, "Actuators", "The list containing the actuators connected to the controller"); - RNA_def_property_collection_funcs(prop, "rna_Controller_actuators_begin", "rna_iterator_array_next", - "rna_iterator_array_end", "rna_iterator_array_dereference_get", - "rna_Controller_actuators_length", NULL, NULL, NULL); - - /* State */ - - /* array of OB_MAX_STATES */ - /*prop = RNA_def_property(srna, "states", PROP_BOOLEAN, PROP_LAYER_MEMBER); */ - /*RNA_def_property_array(prop, OB_MAX_STATES); */ - /*RNA_def_property_clear_flag(prop, PROP_EDITABLE); */ - /*RNA_def_property_ui_text(prop, "", "Set Controller state index (1 to 30)"); */ - /*RNA_def_property_boolean_funcs(prop, "rna_Controller_state_get", "rna_Controller_state_set"); */ - /*RNA_def_property_update(prop, NC_LOGIC, NULL); */ - - /* number of the state */ - prop = RNA_def_property(srna, "states", PROP_INT, PROP_UNSIGNED); - RNA_def_property_int_sdna(prop, NULL, "state_mask"); - RNA_def_property_range(prop, 1, OB_MAX_STATES); - RNA_def_property_ui_text(prop, "", "Set Controller state index (1 to 30)"); - RNA_def_property_int_funcs(prop, "rna_Controller_state_number_get", "rna_Controller_state_number_set", NULL); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* Expression Controller */ - srna = RNA_def_struct(brna, "ExpressionController", "Controller"); - RNA_def_struct_sdna_from(srna, "bExpressionCont", "data"); - RNA_def_struct_ui_text(srna, "Expression Controller", - "Controller passing on events based on the evaluation of an expression"); - - prop = RNA_def_property(srna, "expression", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "str"); - RNA_def_property_ui_text(prop, "Expression", ""); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* Python Controller */ - srna = RNA_def_struct(brna, "PythonController", "Controller"); - RNA_def_struct_sdna_from(srna, "bPythonCont", "data"); - RNA_def_struct_ui_text(srna, "Python Controller", "Controller executing a python script"); - - prop = RNA_def_property(srna, "mode", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_items(prop, python_controller_modes); - RNA_def_property_enum_funcs(prop, NULL, "rna_Controller_mode_set", NULL); - RNA_def_property_ui_text(prop, "Execution Method", "Python script type (textblock or module - faster)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "text", PROP_POINTER, PROP_NONE); - RNA_def_property_struct_type(prop, "Text"); - RNA_def_property_flag(prop, PROP_EDITABLE); - RNA_def_property_ui_text(prop, "Text", "Text data-block with the python script"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "module", PROP_STRING, PROP_NONE); - RNA_def_property_ui_text(prop, "Module", - "Module name and function to run, e.g. \"someModule.main\" " - "(internal texts and external python files can be used)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_debug", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", CONT_PY_DEBUG); - RNA_def_property_ui_text(prop, "D", - "Continuously reload the module from disk for editing external modules " - "without restarting"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* Other Controllers */ - srna = RNA_def_struct(brna, "AndController", "Controller"); - RNA_def_struct_ui_text(srna, "And Controller", "Controller passing on events based on a logical AND operation"); - - srna = RNA_def_struct(brna, "OrController", "Controller"); - RNA_def_struct_ui_text(srna, "Or Controller", "Controller passing on events based on a logical OR operation"); - - srna = RNA_def_struct(brna, "NorController", "Controller"); - RNA_def_struct_ui_text(srna, "Nor Controller", "Controller passing on events based on a logical NOR operation"); - - srna = RNA_def_struct(brna, "NandController", "Controller"); - RNA_def_struct_ui_text(srna, "Nand Controller", "Controller passing on events based on a logical NAND operation"); - - srna = RNA_def_struct(brna, "XorController", "Controller"); - RNA_def_struct_ui_text(srna, "Xor Controller", "Controller passing on events based on a logical XOR operation"); - - srna = RNA_def_struct(brna, "XnorController", "Controller"); - RNA_def_struct_ui_text(srna, "Xnor Controller", "Controller passing on events based on a logical XNOR operation"); -} - -#endif diff --git a/source/blender/makesrna/intern/rna_controller_api.c b/source/blender/makesrna/intern/rna_controller_api.c deleted file mode 100644 index 639d6a330a5..00000000000 --- a/source/blender/makesrna/intern/rna_controller_api.c +++ /dev/null @@ -1,86 +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) 2010 Blender Foundation. - * All rights reserved. - * - * - * Contributor(s): - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file blender/makesrna/intern/rna_controller_api.c - * \ingroup RNA - */ - - -#include -#include - -#include "WM_types.h" -#include "RNA_define.h" - -#include "rna_internal.h" /* own include */ - -#ifdef RNA_RUNTIME - -#include "BKE_sca.h" -#include "DNA_sensor_types.h" -#include "DNA_controller_types.h" -#include "DNA_actuator_types.h" - -static void rna_Controller_link(bController *cont, bSensor *sens, bActuator *act) -{ - if (sens) - link_logicbricks((void **)&cont, (void ***)&(sens->links), &sens->totlinks, sizeof(bController *)); - if (act) - link_logicbricks((void **)&act, (void ***)&(cont->links), &cont->totlinks, sizeof(bActuator *)); -} - -static void rna_Controller_unlink(bController *cont, bSensor *sens, bActuator *act) -{ - if (sens) - unlink_logicbricks((void **)&cont, (void ***)&(sens->links), &sens->totlinks); - if (act) - unlink_logicbricks((void **)&act, (void ***)&(cont->links), &cont->totlinks); -} - -#else - -void RNA_api_controller(StructRNA *srna) -{ - FunctionRNA *func; - PropertyRNA *parm; - - func = RNA_def_function(srna, "link", "rna_Controller_link"); - RNA_def_function_ui_description(func, "Link the controller with a sensor/actuator"); - parm = RNA_def_pointer(func, "sensor", "Sensor", "", "Sensor to link the controller to"); - RNA_def_property_update(parm, NC_LOGIC, NULL); - parm = RNA_def_pointer(func, "actuator", "Actuator", "", "Actuator to link the controller to"); - RNA_def_property_update(parm, NC_LOGIC, NULL); - - func = RNA_def_function(srna, "unlink", "rna_Controller_unlink"); - RNA_def_function_ui_description(func, "Unlink the controller from a sensor/actuator"); - parm = RNA_def_pointer(func, "sensor", "Sensor", "", "Sensor to unlink the controller from"); - RNA_def_property_update(parm, NC_LOGIC, NULL); - parm = RNA_def_pointer(func, "actuator", "Actuator", "", "Actuator to unlink the controller from"); - RNA_def_property_update(parm, NC_LOGIC, NULL); -} - -#endif - diff --git a/source/blender/makesrna/intern/rna_internal.h b/source/blender/makesrna/intern/rna_internal.h index c1f82bab300..11ad39a2dd1 100644 --- a/source/blender/makesrna/intern/rna_internal.h +++ b/source/blender/makesrna/intern/rna_internal.h @@ -151,7 +151,6 @@ void RNA_def_depsgraph(struct BlenderRNA *brna); void RNA_def_dynamic_paint(struct BlenderRNA *brna); void RNA_def_fluidsim(struct BlenderRNA *brna); void RNA_def_fcurve(struct BlenderRNA *brna); -void RNA_def_gameproperty(struct BlenderRNA *brna); void RNA_def_gpencil(struct BlenderRNA *brna); void RNA_def_group(struct BlenderRNA *brna); void RNA_def_image(struct BlenderRNA *brna); diff --git a/source/blender/makesrna/intern/rna_layer.c b/source/blender/makesrna/intern/rna_layer.c index 36e6afe26d6..e6fa7bb26dd 100644 --- a/source/blender/makesrna/intern/rna_layer.c +++ b/source/blender/makesrna/intern/rna_layer.c @@ -1000,18 +1000,6 @@ static int rna_ViewRenderSettings_use_spherical_stereo_get(PointerRNA *ptr) return BKE_viewrender_use_spherical_stereo(view_render); } -static int rna_ViewRenderSettings_use_game_engine_get(PointerRNA *ptr) -{ - ViewRender *view_render = (ViewRender *)ptr->data; - RenderEngineType *type; - - for (type = R_engines.first; type; type = type->next) - if (STREQ(type->idname, view_render->engine_id)) - return (type->flag & RE_GAME) != 0; - - return 0; -} - #else static void rna_def_scene_collections(BlenderRNA *brna, PropertyRNA *cprop) @@ -2233,11 +2221,6 @@ static void rna_def_scene_view_render(BlenderRNA *brna) RNA_def_property_boolean_funcs(prop, "rna_ViewRenderSettings_use_spherical_stereo_get", NULL); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_ui_text(prop, "Use Spherical Stereo", "Active render engine supports spherical stereo rendering"); - - prop = RNA_def_property(srna, "use_game_engine", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_funcs(prop, "rna_ViewRenderSettings_use_game_engine_get", NULL); - RNA_def_property_clear_flag(prop, PROP_EDITABLE); - RNA_def_property_ui_text(prop, "Use Game Engine", "Current rendering engine is a game engine"); } void RNA_def_view_layer(BlenderRNA *brna) diff --git a/source/blender/makesrna/intern/rna_material.c b/source/blender/makesrna/intern/rna_material.c index 8bc818d2658..d800022ec82 100644 --- a/source/blender/makesrna/intern/rna_material.c +++ b/source/blender/makesrna/intern/rna_material.c @@ -153,11 +153,6 @@ static PointerRNA rna_Material_strand_get(PointerRNA *ptr) return rna_pointer_inherit_refine(ptr, &RNA_MaterialStrand, ptr->id.data); } -static PointerRNA rna_Material_physics_get(PointerRNA *ptr) -{ - return rna_pointer_inherit_refine(ptr, &RNA_MaterialPhysics, ptr->id.data); -} - static void rna_Material_type_set(PointerRNA *ptr, int value) { Material *ma = (Material *)ptr->data; @@ -843,67 +838,6 @@ static void rna_def_material_mtex(BlenderRNA *brna) RNA_def_property_update(prop, 0, "rna_Material_update"); } -static void rna_def_material_gamesettings(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - static const EnumPropertyItem prop_alpha_blend_items[] = { - {GEMAT_SOLID, "OPAQUE", 0, "Opaque", "Render color of textured face as color"}, - {GEMAT_ADD, "ADD", 0, "Add", "Render face transparent and add color of face"}, - {GEMAT_CLIP, "CLIP", 0, "Alpha Clip", "Use the image alpha values clipped with no blending (binary alpha)"}, - {GEMAT_ALPHA, "ALPHA", 0, "Alpha Blend", - "Render polygon transparent, depending on alpha channel of the texture"}, - {GEMAT_ALPHA_SORT, "ALPHA_SORT", 0, "Alpha Sort", - "Sort faces for correct alpha drawing (slow, use Alpha Clip instead when possible)"}, - {GEMAT_ALPHA_TO_COVERAGE, "ALPHA_ANTIALIASING", 0, "Alpha Anti-Aliasing", - "Use textures alpha as anti-aliasing mask, requires multi-sample OpenGL display"}, - {0, NULL, 0, NULL, NULL} - }; - - static const EnumPropertyItem prop_face_orientation_items[] = { - {GEMAT_NORMAL, "NORMAL", 0, "Normal", "No transformation"}, - {GEMAT_HALO, "HALO", 0, "Halo", "Screen aligned billboard"}, - {GEMAT_BILLBOARD, "BILLBOARD", 0, "Billboard", "Billboard with Z-axis constraint"}, - {GEMAT_SHADOW, "SHADOW", 0, "Shadow", "Faces are used for shadow"}, - {0, NULL, 0, NULL, NULL} - }; - - srna = RNA_def_struct(brna, "MaterialGameSettings", NULL); - RNA_def_struct_sdna(srna, "GameSettings"); - RNA_def_struct_nested(brna, srna, "Material"); - RNA_def_struct_ui_text(srna, "Material Game Settings", "Game Engine settings for a Material data-block"); - - prop = RNA_def_property(srna, "use_backface_culling", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", GEMAT_BACKCULL); /* use bitflags */ - RNA_def_property_ui_text(prop, "Backface Culling", "Hide Back of the face in Game Engine "); - RNA_def_property_update(prop, 0, "rna_Material_draw_update"); - - prop = RNA_def_property(srna, "text", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", GEMAT_TEXT); /* use bitflags */ - RNA_def_property_ui_text(prop, "Text", "Use material as text in Game Engine "); - RNA_def_property_update(prop, 0, "rna_Material_draw_update"); - - prop = RNA_def_property(srna, "invisible", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", GEMAT_INVISIBLE); /* use bitflags */ - RNA_def_property_ui_text(prop, "Invisible", "Make face invisible"); - RNA_def_property_update(prop, 0, "rna_Material_draw_update"); - - prop = RNA_def_property(srna, "alpha_blend", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "alpha_blend"); - RNA_def_property_enum_items(prop, prop_alpha_blend_items); - RNA_def_property_ui_text(prop, "Blend Mode", "Blend Mode for Transparent Faces"); - RNA_def_property_update(prop, 0, "rna_Material_draw_update"); - - prop = RNA_def_property(srna, "face_orientation", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_items(prop, prop_face_orientation_items); - RNA_def_property_ui_text(prop, "Face Orientations", "Especial face orientation options"); - - prop = RNA_def_property(srna, "physics", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", GEMAT_NOPHYSICS); /* use bitflags */ - RNA_def_property_ui_text(prop, "Physics", "Use physics properties of materials "); -} - static void rna_def_material_colors(StructRNA *srna) { PropertyRNA *prop; @@ -1741,50 +1675,6 @@ static void rna_def_material_strand(BlenderRNA *brna) RNA_def_property_update(prop, 0, "rna_Material_update"); } -static void rna_def_material_physics(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - srna = RNA_def_struct(brna, "MaterialPhysics", NULL); - RNA_def_struct_sdna(srna, "Material"); - RNA_def_struct_nested(brna, srna, "Material"); - RNA_def_struct_ui_text(srna, "Material Physics", "Physics settings for a Material data-block"); - - prop = RNA_def_property(srna, "friction", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "friction"); - RNA_def_property_range(prop, 0, 100); - RNA_def_property_ui_text(prop, "Friction", "Coulomb friction coefficient, when inside the physics distance area"); - - prop = RNA_def_property(srna, "elasticity", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "reflect"); - RNA_def_property_range(prop, 0, 1); - RNA_def_property_ui_text(prop, "Elasticity", "Elasticity of collisions"); - - /* FH/Force Field Settings */ - prop = RNA_def_property(srna, "use_fh_normal", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "dynamode", MA_FH_NOR); - RNA_def_property_ui_text(prop, "Align to Normal", - "Align dynamic game objects along the surface normal, " - "when inside the physics distance area"); - - prop = RNA_def_property(srna, "fh_force", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "fh"); - RNA_def_property_range(prop, 0, 1); - RNA_def_property_ui_range(prop, 0.0, 1.0, 10, 2); - RNA_def_property_ui_text(prop, "Force", "Upward spring force, when inside the physics distance area"); - - prop = RNA_def_property(srna, "fh_distance", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "fhdist"); - RNA_def_property_range(prop, 0, 20); - RNA_def_property_ui_text(prop, "Distance", "Distance of the physics area"); - - prop = RNA_def_property(srna, "fh_damping", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "xyfrict"); - RNA_def_property_range(prop, 0, 1); - RNA_def_property_ui_text(prop, "Damping", "Damping of the spring force, when inside the physics distance area"); -} - void RNA_def_material(BlenderRNA *brna) { StructRNA *srna; @@ -2149,19 +2039,6 @@ void RNA_def_material(BlenderRNA *brna) RNA_def_property_struct_type(prop, "MaterialStrand"); RNA_def_property_pointer_funcs(prop, "rna_Material_strand_get", NULL, NULL, NULL); RNA_def_property_ui_text(prop, "Strand", "Strand settings for the material"); - - prop = RNA_def_property(srna, "physics", PROP_POINTER, PROP_NONE); - RNA_def_property_flag(prop, PROP_NEVER_NULL); - RNA_def_property_struct_type(prop, "MaterialPhysics"); - RNA_def_property_pointer_funcs(prop, "rna_Material_physics_get", NULL, NULL, NULL); - RNA_def_property_ui_text(prop, "Physics", "Game physics settings"); - - /* game settings */ - prop = RNA_def_property(srna, "game_settings", PROP_POINTER, PROP_NONE); - RNA_def_property_flag(prop, PROP_NEVER_NULL); - RNA_def_property_pointer_sdna(prop, NULL, "game"); - RNA_def_property_struct_type(prop, "MaterialGameSettings"); - RNA_def_property_ui_text(prop, "Game Settings", "Game material settings"); /* nodetree */ prop = RNA_def_property(srna, "node_tree", PROP_POINTER, PROP_NONE); @@ -2210,8 +2087,6 @@ void RNA_def_material(BlenderRNA *brna) rna_def_material_sss(brna); rna_def_material_mtex(brna); rna_def_material_strand(brna); - rna_def_material_physics(brna); - rna_def_material_gamesettings(brna); RNA_api_material(srna); } diff --git a/source/blender/makesrna/intern/rna_object.c b/source/blender/makesrna/intern/rna_object.c index 1932390d0fd..9a3066207f9 100644 --- a/source/blender/makesrna/intern/rna_object.c +++ b/source/blender/makesrna/intern/rna_object.c @@ -29,13 +29,11 @@ #include "DNA_action_types.h" #include "DNA_customdata_types.h" -#include "DNA_controller_types.h" #include "DNA_group_types.h" #include "DNA_material_types.h" #include "DNA_mesh_types.h" #include "DNA_object_force_types.h" #include "DNA_object_types.h" -#include "DNA_property_types.h" #include "DNA_scene_types.h" #include "DNA_meta_types.h" #include "DNA_workspace_types.h" @@ -121,18 +119,6 @@ static EnumPropertyItem dupli_items_nogroup[] = { #undef DUPLI_ITEMS_SHARED #undef DUPLI_ITEM_GROUP -static const EnumPropertyItem collision_bounds_items[] = { - {OB_BOUND_BOX, "BOX", ICON_MESH_CUBE, "Box", ""}, - {OB_BOUND_SPHERE, "SPHERE", ICON_MESH_UVSPHERE, "Sphere", ""}, - {OB_BOUND_CYLINDER, "CYLINDER", ICON_MESH_CYLINDER, "Cylinder", ""}, - {OB_BOUND_CONE, "CONE", ICON_MESH_CONE, "Cone", ""}, - {OB_BOUND_CONVEX_HULL, "CONVEX_HULL", ICON_MESH_ICOSPHERE, "Convex Hull", ""}, - {OB_BOUND_TRIANGLE_MESH, "TRIANGLE_MESH", ICON_MESH_MONKEY, "Triangle Mesh", ""}, - {OB_BOUND_CAPSULE, "CAPSULE", ICON_MESH_CAPSULE, "Capsule", ""}, - /*{OB_DYN_MESH, "DYNAMIC_MESH", 0, "Dynamic Mesh", ""}, */ - {0, NULL, 0, NULL, NULL} -}; - const EnumPropertyItem rna_enum_metaelem_type_items[] = { {MB_BALL, "BALL", ICON_META_BALL, "Ball", ""}, {MB_TUBE, "CAPSULE", ICON_META_CAPSULE, "Capsule", ""}, @@ -192,7 +178,6 @@ const EnumPropertyItem rna_enum_object_axis_items[] = { #include "DNA_node_types.h" #include "BKE_armature.h" -#include "BKE_bullet.h" #include "BKE_constraint.h" #include "BKE_context.h" #include "BKE_curve.h" @@ -469,32 +454,6 @@ static void rna_Object_empty_draw_type_set(PointerRNA *ptr, int value) BKE_object_empty_draw_type_set(ob, value); } -static const EnumPropertyItem *rna_Object_collision_bounds_itemf(bContext *UNUSED(C), PointerRNA *ptr, - PropertyRNA *UNUSED(prop), bool *r_free) -{ - Object *ob = (Object *)ptr->data; - EnumPropertyItem *item = NULL; - int totitem = 0; - - if (ob->body_type != OB_BODY_TYPE_CHARACTER) { - RNA_enum_items_add_value(&item, &totitem, collision_bounds_items, OB_BOUND_TRIANGLE_MESH); - } - RNA_enum_items_add_value(&item, &totitem, collision_bounds_items, OB_BOUND_CONVEX_HULL); - - if (ob->body_type != OB_BODY_TYPE_SOFT) { - RNA_enum_items_add_value(&item, &totitem, collision_bounds_items, OB_BOUND_CONE); - RNA_enum_items_add_value(&item, &totitem, collision_bounds_items, OB_BOUND_CYLINDER); - RNA_enum_items_add_value(&item, &totitem, collision_bounds_items, OB_BOUND_SPHERE); - RNA_enum_items_add_value(&item, &totitem, collision_bounds_items, OB_BOUND_BOX); - RNA_enum_items_add_value(&item, &totitem, collision_bounds_items, OB_BOUND_CAPSULE); - } - - RNA_enum_item_end(&item, &totitem); - *r_free = true; - - return item; -} - static void rna_Object_parent_bone_set(PointerRNA *ptr, const char *value) { Object *ob = (Object *)ptr->data; @@ -1047,122 +1006,6 @@ static char *rna_MaterialSlot_path(PointerRNA *ptr) * * logic from check_body_type() * */ -static int rna_GameObjectSettings_physics_type_get(PointerRNA *ptr) -{ - Object *ob = (Object *)ptr->id.data; - - /* determine the body_type setting based on flags */ - if (!(ob->gameflag & OB_COLLISION)) { - if (ob->gameflag & OB_OCCLUDER) { - ob->body_type = OB_BODY_TYPE_OCCLUDER; - } - else if (ob->gameflag & OB_NAVMESH) { - ob->body_type = OB_BODY_TYPE_NAVMESH; - } - else { - ob->body_type = OB_BODY_TYPE_NO_COLLISION; - } - } - else if (ob->gameflag & OB_CHARACTER) { - ob->body_type = OB_BODY_TYPE_CHARACTER; - } - else if (ob->gameflag & OB_SENSOR) { - ob->body_type = OB_BODY_TYPE_SENSOR; - } - else if (!(ob->gameflag & OB_DYNAMIC)) { - ob->body_type = OB_BODY_TYPE_STATIC; - } - else if (!(ob->gameflag & (OB_RIGID_BODY | OB_SOFT_BODY))) { - ob->body_type = OB_BODY_TYPE_DYNAMIC; - } - else if (ob->gameflag & OB_RIGID_BODY) { - ob->body_type = OB_BODY_TYPE_RIGID; - } - else { - ob->body_type = OB_BODY_TYPE_SOFT; - /* create the structure here because we display soft body buttons in the main panel */ - if (!ob->bsoft) - ob->bsoft = bsbNew(); - } - - return ob->body_type; -} - -static void rna_GameObjectSettings_physics_type_set(PointerRNA *ptr, int value) -{ - Object *ob = (Object *)ptr->id.data; - const int gameflag_prev = ob->gameflag; - ob->body_type = value; - - switch (ob->body_type) { - case OB_BODY_TYPE_SENSOR: - ob->gameflag |= OB_SENSOR | OB_COLLISION; - ob->gameflag &= ~(OB_OCCLUDER | OB_CHARACTER | OB_DYNAMIC | OB_RIGID_BODY | OB_SOFT_BODY | OB_ACTOR | - OB_ANISOTROPIC_FRICTION | OB_DO_FH | OB_ROT_FH | OB_COLLISION_RESPONSE | OB_NAVMESH); - break; - case OB_BODY_TYPE_OCCLUDER: - ob->gameflag |= OB_OCCLUDER; - ob->gameflag &= ~(OB_SENSOR | OB_RIGID_BODY | OB_SOFT_BODY | OB_COLLISION | OB_CHARACTER | OB_DYNAMIC | OB_NAVMESH); - break; - case OB_BODY_TYPE_NAVMESH: - ob->gameflag |= OB_NAVMESH; - ob->gameflag &= ~(OB_SENSOR | OB_RIGID_BODY | OB_SOFT_BODY | OB_COLLISION | OB_CHARACTER | OB_DYNAMIC | OB_OCCLUDER); - - if (ob->type == OB_MESH) { - /* could be moved into mesh UI but for now ensure mesh data layer */ - BKE_mesh_ensure_navmesh(ob->data); - } - - break; - case OB_BODY_TYPE_NO_COLLISION: - ob->gameflag &= ~(OB_SENSOR | OB_RIGID_BODY | OB_SOFT_BODY | OB_COLLISION | OB_CHARACTER | OB_OCCLUDER | OB_DYNAMIC | OB_NAVMESH); - break; - case OB_BODY_TYPE_CHARACTER: - ob->gameflag |= OB_COLLISION | OB_CHARACTER; - ob->gameflag &= ~(OB_SENSOR | OB_OCCLUDER | OB_DYNAMIC | OB_RIGID_BODY | OB_SOFT_BODY | OB_ACTOR | - OB_ANISOTROPIC_FRICTION | OB_DO_FH | OB_ROT_FH | OB_COLLISION_RESPONSE | OB_NAVMESH); - /* When we switch to character physics and the collision bounds is set to triangle mesh - * we have to change collision bounds because triangle mesh is not supported by Characters */ - if ((ob->gameflag & OB_BOUNDS) && ob->collision_boundtype == OB_BOUND_TRIANGLE_MESH) { - ob->boundtype = ob->collision_boundtype = OB_BOUND_BOX; - } - break; - case OB_BODY_TYPE_STATIC: - ob->gameflag |= OB_COLLISION; - ob->gameflag &= ~(OB_DYNAMIC | OB_RIGID_BODY | OB_SOFT_BODY | OB_OCCLUDER | OB_CHARACTER | OB_SENSOR | OB_NAVMESH); - break; - case OB_BODY_TYPE_DYNAMIC: - ob->gameflag |= OB_COLLISION | OB_DYNAMIC | OB_ACTOR; - ob->gameflag &= ~(OB_RIGID_BODY | OB_SOFT_BODY | OB_OCCLUDER | OB_CHARACTER | OB_SENSOR | OB_NAVMESH); - break; - case OB_BODY_TYPE_RIGID: - ob->gameflag |= OB_COLLISION | OB_DYNAMIC | OB_RIGID_BODY | OB_ACTOR; - ob->gameflag &= ~(OB_SOFT_BODY | OB_OCCLUDER | OB_CHARACTER | OB_SENSOR | OB_NAVMESH); - break; - default: - case OB_BODY_TYPE_SOFT: - ob->gameflag |= OB_COLLISION | OB_DYNAMIC | OB_SOFT_BODY | OB_ACTOR; - ob->gameflag &= ~(OB_RIGID_BODY | OB_OCCLUDER | OB_CHARACTER | OB_SENSOR | OB_NAVMESH); - - /* assume triangle mesh, if no bounds chosen for soft body */ - if ((ob->gameflag & OB_BOUNDS) && (ob->boundtype < OB_BOUND_TRIANGLE_MESH)) { - ob->boundtype = OB_BOUND_TRIANGLE_MESH; - } - /* create a BulletSoftBody structure if not already existing */ - if (!ob->bsoft) - ob->bsoft = bsbNew(); - break; - } - - if ((gameflag_prev & OB_NAVMESH) != (ob->gameflag & OB_NAVMESH)) { - if (ob->type == OB_MESH) { - /* this is needed to refresh the derived meshes draw func */ - DEG_id_tag_update(ptr->id.data, OB_RECALC_DATA); - } - } - - WM_main_add_notifier(NC_OBJECT | ND_DRAW, ptr->id.data); -} static PointerRNA rna_Object_active_particle_system_get(PointerRNA *ptr) { @@ -1171,117 +1014,6 @@ static PointerRNA rna_Object_active_particle_system_get(PointerRNA *ptr) return rna_pointer_inherit_refine(ptr, &RNA_ParticleSystem, psys); } -static PointerRNA rna_Object_game_settings_get(PointerRNA *ptr) -{ - return rna_pointer_inherit_refine(ptr, &RNA_GameObjectSettings, ptr->id.data); -} - -static void rna_GameObjectSettings_state_get(PointerRNA *ptr, int *values) -{ - Object *ob = (Object *)ptr->data; - int i; - int all_states = (ob->scaflag & OB_ALLSTATE) ? 1 : 0; - - memset(values, 0, sizeof(int) * OB_MAX_STATES); - for (i = 0; i < OB_MAX_STATES; i++) { - values[i] = (ob->state & (1 << i)) ? 1 : 0 | all_states; - } -} - -static void rna_GameObjectSettings_state_set(PointerRNA *ptr, const int *values) -{ - Object *ob = (Object *)ptr->data; - int i, tot = 0; - - /* ensure we always have some state selected */ - for (i = 0; i < OB_MAX_STATES; i++) - if (values[i]) - tot++; - - if (tot == 0) - return; - - for (i = 0; i < OB_MAX_STATES; i++) { - if (values[i]) ob->state |= (1 << i); - else ob->state &= ~(1 << i); - } -} - -static void rna_GameObjectSettings_used_state_get(PointerRNA *ptr, int *values) -{ - Object *ob = (Object *)ptr->data; - bController *cont; - - memset(values, 0, sizeof(int) * OB_MAX_STATES); - for (cont = ob->controllers.first; cont; cont = cont->next) { - int i; - - for (i = 0; i < OB_MAX_STATES; i++) { - if (cont->state_mask & (1 << i)) - values[i] = 1; - } - } -} - -static void rna_GameObjectSettings_col_group_get(PointerRNA *ptr, int *values) -{ - Object *ob = (Object *)ptr->data; - int i; - - for (i = 0; i < OB_MAX_COL_MASKS; i++) { - values[i] = (ob->col_group & (1 << i)) != 0; - } -} - -static void rna_GameObjectSettings_col_group_set(PointerRNA *ptr, const int *values) -{ - Object *ob = (Object *)ptr->data; - int i, tot = 0; - - /* ensure we always have some group selected */ - for (i = 0; i < OB_MAX_COL_MASKS; i++) - if (values[i]) - tot++; - - if (tot == 0) - return; - - for (i = 0; i < OB_MAX_COL_MASKS; i++) { - if (values[i]) ob->col_group |= (1 << i); - else ob->col_group &= ~(1 << i); - } -} - -static void rna_GameObjectSettings_col_mask_get(PointerRNA *ptr, int *values) -{ - Object *ob = (Object *)ptr->data; - int i; - - for (i = 0; i < OB_MAX_COL_MASKS; i++) { - values[i] = (ob->col_mask & (1 << i)) != 0; - } -} - -static void rna_GameObjectSettings_col_mask_set(PointerRNA *ptr, const int *values) -{ - Object *ob = (Object *)ptr->data; - int i, tot = 0; - - /* ensure we always have some mask selected */ - for (i = 0; i < OB_MAX_COL_MASKS; i++) - if (values[i]) - tot++; - - if (tot == 0) - return; - - for (i = 0; i < OB_MAX_COL_MASKS; i++) { - if (values[i]) ob->col_mask |= (1 << i); - else ob->col_mask &= ~(1 << i); - } -} - - static void rna_Object_active_shape_key_index_range(PointerRNA *ptr, int *min, int *max, int *UNUSED(softmin), int *UNUSED(softmax)) { @@ -1617,16 +1349,6 @@ int rna_Object_use_dynamic_topology_sculpting_get(PointerRNA *ptr) return (ss && ss->bm); } -static void rna_Object_lod_distance_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *ptr) -{ - Object *ob = (Object *)ptr->id.data; - -#ifdef WITH_GAMEENGINE - BKE_object_lod_sort(ob); -#else - (void)ob; -#endif -} #else static void rna_def_vertex_group(BlenderRNA *brna) @@ -1777,313 +1499,6 @@ static void rna_def_material_slot(BlenderRNA *brna) RNA_def_struct_path_func(srna, "rna_MaterialSlot_path"); } -static void rna_def_object_game_settings(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - static const EnumPropertyItem body_type_items[] = { - {OB_BODY_TYPE_NO_COLLISION, "NO_COLLISION", 0, "No Collision", "Disable collision for this object"}, - {OB_BODY_TYPE_STATIC, "STATIC", 0, "Static", "Stationary object"}, - {OB_BODY_TYPE_DYNAMIC, "DYNAMIC", 0, "Dynamic", "Linear physics"}, - {OB_BODY_TYPE_RIGID, "RIGID_BODY", 0, "Rigid Body", "Linear and angular physics"}, - {OB_BODY_TYPE_SOFT, "SOFT_BODY", 0, "Soft Body", "Soft body"}, - {OB_BODY_TYPE_OCCLUDER, "OCCLUDER", 0, "Occluder", "Occluder for optimizing scene rendering"}, - {OB_BODY_TYPE_SENSOR, "SENSOR", 0, "Sensor", - "Collision Sensor, detects static and dynamic objects but not the other " - "collision sensor objects"}, - {OB_BODY_TYPE_NAVMESH, "NAVMESH", 0, "Navigation Mesh", "Navigation mesh"}, - {OB_BODY_TYPE_CHARACTER, "CHARACTER", 0, "Character", - "Simple kinematic physics appropriate for game characters"}, - {0, NULL, 0, NULL, NULL} - }; - - srna = RNA_def_struct(brna, "GameObjectSettings", NULL); - RNA_def_struct_sdna(srna, "Object"); - RNA_def_struct_nested(brna, srna, "Object"); - RNA_def_struct_ui_text(srna, "Game Object Settings", "Game engine related settings for the object"); - RNA_def_struct_ui_icon(srna, ICON_GAME); - - /* logic */ - - prop = RNA_def_property(srna, "sensors", PROP_COLLECTION, PROP_NONE); - RNA_def_property_struct_type(prop, "Sensor"); - RNA_def_property_ui_text(prop, "Sensors", "Game engine sensor to detect events"); - - prop = RNA_def_property(srna, "controllers", PROP_COLLECTION, PROP_NONE); - RNA_def_property_struct_type(prop, "Controller"); - RNA_def_property_ui_text(prop, "Controllers", - "Game engine controllers to process events, connecting sensors to actuators"); - - prop = RNA_def_property(srna, "actuators", PROP_COLLECTION, PROP_NONE); - RNA_def_property_struct_type(prop, "Actuator"); - RNA_def_property_ui_text(prop, "Actuators", "Game engine actuators to act on events"); - - prop = RNA_def_property(srna, "properties", PROP_COLLECTION, PROP_NONE); - RNA_def_property_collection_sdna(prop, NULL, "prop", NULL); - RNA_def_property_struct_type(prop, "GameProperty"); /* rna_property.c */ - RNA_def_property_ui_text(prop, "Properties", "Game engine properties"); - - prop = RNA_def_property(srna, "show_sensors", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "scaflag", OB_SHOWSENS); - RNA_def_property_ui_text(prop, "Show Sensors", "Shows sensors for this object in the user interface"); - - prop = RNA_def_property(srna, "show_controllers", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "scaflag", OB_SHOWCONT); - RNA_def_property_ui_text(prop, "Show Controllers", "Shows controllers for this object in the user interface"); - - prop = RNA_def_property(srna, "show_actuators", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "scaflag", OB_SHOWACT); - RNA_def_property_ui_text(prop, "Show Actuators", "Shows actuators for this object in the user interface"); - - /* physics */ - - prop = RNA_def_property(srna, "physics_type", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "body_type"); - RNA_def_property_enum_items(prop, body_type_items); - RNA_def_property_enum_default(prop, OB_BODY_TYPE_STATIC); - RNA_def_property_enum_funcs(prop, "rna_GameObjectSettings_physics_type_get", - "rna_GameObjectSettings_physics_type_set", NULL); - RNA_def_property_ui_text(prop, "Physics Type", "Select the type of physical representation"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_record_animation", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "gameflag", OB_RECORD_ANIMATION); - RNA_def_property_ui_text(prop, "Record Animation", "Record animation objects without physics"); - - prop = RNA_def_property(srna, "use_actor", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "gameflag", OB_ACTOR); - RNA_def_property_ui_text(prop, "Actor", "Object is detected by the Near and Radar sensor"); - - prop = RNA_def_property(srna, "use_ghost", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "gameflag", OB_GHOST); - RNA_def_property_ui_text(prop, "Ghost", "Object does not react to collisions, like a ghost"); - - prop = RNA_def_property(srna, "mass", PROP_FLOAT, PROP_NONE); - RNA_def_property_range(prop, 0.01, 10000.0); - RNA_def_property_float_default(prop, 1.0f); - RNA_def_property_ui_text(prop, "Mass", "Mass of the object"); - - prop = RNA_def_property(srna, "radius", PROP_FLOAT, PROP_NONE | PROP_UNIT_LENGTH); - RNA_def_property_float_sdna(prop, NULL, "inertia"); - RNA_def_property_range(prop, 0.01f, FLT_MAX); - RNA_def_property_ui_range(prop, 0.01f, 10.0f, 1, 3); - RNA_def_property_float_default(prop, 1.0f); - RNA_def_property_ui_text(prop, "Radius", "Radius of bounding sphere and material physics"); - RNA_def_property_update(prop, NC_OBJECT | ND_DRAW, NULL); - - prop = RNA_def_property(srna, "use_sleep", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "gameflag", OB_COLLISION_RESPONSE); - RNA_def_property_ui_text(prop, "No Sleeping", "Disable auto (de)activation in physics simulation"); - - prop = RNA_def_property(srna, "damping", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "damping"); - RNA_def_property_range(prop, 0.0, 1.0); - RNA_def_property_float_default(prop, 0.04f); - RNA_def_property_ui_text(prop, "Damping", "General movement damping"); - - prop = RNA_def_property(srna, "rotation_damping", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "rdamping"); - RNA_def_property_range(prop, 0.0, 1.0); - RNA_def_property_float_default(prop, 0.1f); - RNA_def_property_ui_text(prop, "Rotation Damping", "General rotation damping"); - - prop = RNA_def_property(srna, "velocity_min", PROP_FLOAT, PROP_DISTANCE); - RNA_def_property_float_sdna(prop, NULL, "min_vel"); - RNA_def_property_range(prop, 0.0, 1000.0); - RNA_def_property_ui_text(prop, "Velocity Min", "Clamp velocity to this minimum speed (except when totally still), " - "in distance per second"); - - prop = RNA_def_property(srna, "velocity_max", PROP_FLOAT, PROP_DISTANCE); - RNA_def_property_float_sdna(prop, NULL, "max_vel"); - RNA_def_property_range(prop, 0.0, 1000.0); - RNA_def_property_ui_text(prop, "Velocity Max", "Clamp velocity to this maximum speed, " - "in distance per second"); - - prop = RNA_def_property(srna, "angular_velocity_min", PROP_FLOAT, PROP_ANGLE); - RNA_def_property_float_sdna(prop, NULL, "min_angvel"); - RNA_def_property_range(prop, 0.0, 1000.0); - RNA_def_property_ui_text(prop, "Angular Velocity Min", - "Clamp angular velocity to this minimum speed (except when totally still), " - "in angle per second"); - - prop = RNA_def_property(srna, "angular_velocity_max", PROP_FLOAT, PROP_ANGLE); - RNA_def_property_float_sdna(prop, NULL, "max_angvel"); - RNA_def_property_range(prop, 0.0, 1000.0); - RNA_def_property_ui_text(prop, "Angular Velocity Max", "Clamp angular velocity to this maximum speed, " - "in angle per second"); - - /* Character physics */ - prop = RNA_def_property(srna, "step_height", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "step_height"); - RNA_def_property_range(prop, 0.01, 1.0); - RNA_def_property_float_default(prop, 0.15f); - RNA_def_property_ui_text(prop, "Step Height", "Maximum height of steps the character can run over"); - - prop = RNA_def_property(srna, "jump_speed", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "jump_speed"); - RNA_def_property_range(prop, 0.0, 1000.0); - RNA_def_property_float_default(prop, 10.0f); - RNA_def_property_ui_text(prop, "Jump Force", "Upward velocity applied to the character when jumping"); - - prop = RNA_def_property(srna, "fall_speed", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "fall_speed"); - RNA_def_property_range(prop, 0.0, 1000.0); - RNA_def_property_float_default(prop, 55.0f); - RNA_def_property_ui_text(prop, "Fall Speed Max", "Maximum speed at which the character will fall"); - - prop = RNA_def_property(srna, "jump_max", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "max_jumps"); - RNA_def_property_range(prop, 1, CHAR_MAX); - RNA_def_property_ui_range(prop, 1, 10, 1, 1); - RNA_def_property_int_default(prop, 1); - RNA_def_property_ui_text(prop, "Max Jumps", - "The maximum number of jumps the character can make before it hits the ground"); - - /* Collision Masks */ - prop = RNA_def_property(srna, "collision_group", PROP_BOOLEAN, PROP_LAYER_MEMBER); - RNA_def_property_boolean_sdna(prop, NULL, "col_group", 1); - RNA_def_property_array(prop, OB_MAX_COL_MASKS); - RNA_def_property_ui_text(prop, "Collision Group", "The collision group of the object"); - RNA_def_property_boolean_funcs(prop, "rna_GameObjectSettings_col_group_get", "rna_GameObjectSettings_col_group_set"); - - prop = RNA_def_property(srna, "collision_mask", PROP_BOOLEAN, PROP_LAYER_MEMBER); - RNA_def_property_boolean_sdna(prop, NULL, "col_mask", 1); - RNA_def_property_array(prop, OB_MAX_COL_MASKS); - RNA_def_property_ui_text(prop, "Collision Mask", "The groups this object can collide with"); - RNA_def_property_boolean_funcs(prop, "rna_GameObjectSettings_col_mask_get", "rna_GameObjectSettings_col_mask_set"); - - /* lock position */ - prop = RNA_def_property(srna, "lock_location_x", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "gameflag2", OB_LOCK_RIGID_BODY_X_AXIS); - RNA_def_property_ui_text(prop, "Lock X Axis", "Disable simulation of linear motion along the X axis"); - - prop = RNA_def_property(srna, "lock_location_y", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "gameflag2", OB_LOCK_RIGID_BODY_Y_AXIS); - RNA_def_property_ui_text(prop, "Lock Y Axis", "Disable simulation of linear motion along the Y axis"); - - prop = RNA_def_property(srna, "lock_location_z", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "gameflag2", OB_LOCK_RIGID_BODY_Z_AXIS); - RNA_def_property_ui_text(prop, "Lock Z Axis", "Disable simulation of linear motion along the Z axis"); - - - /* lock rotation */ - prop = RNA_def_property(srna, "lock_rotation_x", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "gameflag2", OB_LOCK_RIGID_BODY_X_ROT_AXIS); - RNA_def_property_ui_text(prop, "Lock X Rotation Axis", "Disable simulation of angular motion along the X axis"); - - prop = RNA_def_property(srna, "lock_rotation_y", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "gameflag2", OB_LOCK_RIGID_BODY_Y_ROT_AXIS); - RNA_def_property_ui_text(prop, "Lock Y Rotation Axis", "Disable simulation of angular motion along the Y axis"); - - prop = RNA_def_property(srna, "lock_rotation_z", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "gameflag2", OB_LOCK_RIGID_BODY_Z_ROT_AXIS); - RNA_def_property_ui_text(prop, "Lock Z Rotation Axis", "Disable simulation of angular motion along the Z axis"); - - /* is this used anywhere ? */ - prop = RNA_def_property(srna, "use_activity_culling", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_negative_sdna(prop, NULL, "gameflag2", OB_NEVER_DO_ACTIVITY_CULLING); - RNA_def_property_ui_text(prop, "Lock Z Rotation Axis", "Disable simulation of angular motion along the Z axis"); - - - prop = RNA_def_property(srna, "use_material_physics_fh", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "gameflag", OB_DO_FH); - RNA_def_property_ui_text(prop, "Use Material Force Field", "React to force field physics settings in materials"); - - prop = RNA_def_property(srna, "use_rotate_from_normal", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "gameflag", OB_ROT_FH); - RNA_def_property_ui_text(prop, "Rotate From Normal", - "Use face normal to rotate object, so that it points away from the surface"); - - prop = RNA_def_property(srna, "form_factor", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "formfactor"); - RNA_def_property_range(prop, 0.0, 1.0); - RNA_def_property_float_default(prop, 0.4f); - RNA_def_property_ui_text(prop, "Form Factor", "Form factor scales the inertia tensor"); - - prop = RNA_def_property(srna, "use_anisotropic_friction", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "gameflag", OB_ANISOTROPIC_FRICTION); - RNA_def_property_ui_text(prop, "Anisotropic Friction", "Enable anisotropic friction"); - - prop = RNA_def_property(srna, "friction_coefficients", PROP_FLOAT, PROP_XYZ); - RNA_def_property_float_sdna(prop, NULL, "anisotropicFriction"); - RNA_def_property_range(prop, 0.0, 1.0); - RNA_def_property_ui_text(prop, "Friction Coefficients", - "Relative friction coefficients in the in the X, Y and Z directions, " - "when anisotropic friction is enabled"); - - prop = RNA_def_property(srna, "use_collision_bounds", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "gameflag", OB_BOUNDS); - RNA_def_property_ui_text(prop, "Use Collision Bounds", "Specify a collision bounds type other than the default"); - RNA_def_property_update(prop, NC_OBJECT | ND_DRAW, NULL); - - prop = RNA_def_property(srna, "collision_bounds_type", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "collision_boundtype"); - RNA_def_property_enum_items(prop, collision_bounds_items); - RNA_def_property_enum_funcs(prop, NULL, NULL, "rna_Object_collision_bounds_itemf"); - RNA_def_property_ui_text(prop, "Collision Shape", "Select the collision shape that better fits the object"); - RNA_def_property_update(prop, NC_OBJECT | ND_DRAW, NULL); - - prop = RNA_def_property(srna, "use_collision_compound", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "gameflag", OB_CHILD); - RNA_def_property_ui_text(prop, "Collision Compound", "Add children to form a compound collision object"); - - prop = RNA_def_property(srna, "collision_margin", PROP_FLOAT, PROP_NONE | PROP_UNIT_LENGTH); - RNA_def_property_float_sdna(prop, NULL, "margin"); - RNA_def_property_range(prop, 0.0, 1.0); - RNA_def_property_float_default(prop, 0.04f); - RNA_def_property_ui_text(prop, "Collision Margin", - "Extra margin around object for collision detection, small amount required " - "for stability"); - - prop = RNA_def_property(srna, "soft_body", PROP_POINTER, PROP_NONE); - RNA_def_property_pointer_sdna(prop, NULL, "bsoft"); - RNA_def_property_ui_text(prop, "Soft Body Settings", "Settings for Bullet soft body simulation"); - - prop = RNA_def_property(srna, "use_obstacle_create", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "gameflag", OB_HASOBSTACLE); - RNA_def_property_ui_text(prop, "Create obstacle", "Create representation for obstacle simulation"); - - prop = RNA_def_property(srna, "obstacle_radius", PROP_FLOAT, PROP_NONE | PROP_UNIT_LENGTH); - RNA_def_property_float_sdna(prop, NULL, "obstacleRad"); - RNA_def_property_range(prop, 0.0, 1000.0); - RNA_def_property_float_default(prop, 1.0f); - RNA_def_property_ui_text(prop, "Obstacle Radius", "Radius of object representation in obstacle simulation"); - - /* state */ - - prop = RNA_def_property(srna, "states_visible", PROP_BOOLEAN, PROP_LAYER_MEMBER); - RNA_def_property_boolean_sdna(prop, NULL, "state", 1); - RNA_def_property_array(prop, OB_MAX_STATES); - RNA_def_property_ui_text(prop, "State", "State determining which controllers are displayed"); - RNA_def_property_boolean_funcs(prop, "rna_GameObjectSettings_state_get", "rna_GameObjectSettings_state_set"); - - prop = RNA_def_property(srna, "used_states", PROP_BOOLEAN, PROP_LAYER_MEMBER); - RNA_def_property_array(prop, OB_MAX_STATES); - RNA_def_property_ui_text(prop, "Used State", "States which are being used by controllers"); - RNA_def_property_clear_flag(prop, PROP_EDITABLE); - RNA_def_property_boolean_funcs(prop, "rna_GameObjectSettings_used_state_get", NULL); - - prop = RNA_def_property(srna, "states_initial", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "init_state", 1); - RNA_def_property_array(prop, OB_MAX_STATES); - RNA_def_property_ui_text(prop, "Initial State", "Initial state when the game starts"); - - prop = RNA_def_property(srna, "show_debug_state", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "scaflag", OB_DEBUGSTATE); - RNA_def_property_ui_text(prop, "Debug State", "Print state debug info in the game engine"); - RNA_def_property_ui_icon(prop, ICON_INFO, 0); - - prop = RNA_def_property(srna, "use_all_states", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "scaflag", OB_ALLSTATE); - RNA_def_property_ui_text(prop, "All", "Set all state bits"); - - prop = RNA_def_property(srna, "show_state_panel", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "scaflag", OB_SHOWSTATE); - RNA_def_property_ui_text(prop, "States", "Show state panel"); - RNA_def_property_ui_icon(prop, ICON_DISCLOSURE_TRI_RIGHT, 1); -} - static void rna_def_object_constraints(BlenderRNA *brna, PropertyRNA *cprop) { StructRNA *srna; @@ -2312,54 +1727,6 @@ static void rna_def_object_face_maps(BlenderRNA *brna, PropertyRNA *cprop) RNA_def_function_ui_description(func, "Delete all vertex groups from object"); } -static void rna_def_object_lodlevel(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - srna = RNA_def_struct(brna, "LodLevel", NULL); - RNA_def_struct_sdna(srna, "LodLevel"); - - prop = RNA_def_property(srna, "distance", PROP_FLOAT, PROP_DISTANCE); - RNA_def_property_float_sdna(prop, NULL, "distance"); - RNA_def_property_range(prop, 0.0, FLT_MAX); - RNA_def_property_ui_text(prop, "Distance", "Distance to begin using this level of detail"); - RNA_def_property_update(prop, NC_OBJECT | ND_LOD, "rna_Object_lod_distance_update"); - - prop = RNA_def_property(srna, "object_hysteresis_percentage", PROP_INT, PROP_PERCENTAGE); - RNA_def_property_int_sdna(prop, NULL, "obhysteresis"); - RNA_def_property_range(prop, 0, 100); - RNA_def_property_ui_range(prop, 0, 100, 10, 1); - RNA_def_property_ui_text(prop, "Hysteresis %", - "Minimum distance change required to transition to the previous level of detail"); - RNA_def_property_update(prop, NC_OBJECT | ND_LOD, NULL); - - prop = RNA_def_property(srna, "object", PROP_POINTER, PROP_NONE); - RNA_def_property_pointer_sdna(prop, NULL, "source"); - RNA_def_property_struct_type(prop, "Object"); - RNA_def_property_flag(prop, PROP_EDITABLE); - RNA_def_property_ui_text(prop, "Object", "Object to use for this level of detail"); - RNA_def_property_update(prop, NC_OBJECT | ND_LOD, NULL); - - prop = RNA_def_property(srna, "use_mesh", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flags", OB_LOD_USE_MESH); - RNA_def_property_ui_text(prop, "Use Mesh", "Use the mesh from this object at this level of detail"); - RNA_def_property_ui_icon(prop, ICON_MESH_DATA, 0); - RNA_def_property_update(prop, NC_OBJECT | ND_LOD, NULL); - - prop = RNA_def_property(srna, "use_material", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flags", OB_LOD_USE_MAT); - RNA_def_property_ui_text(prop, "Use Material", "Use the material from this object at this level of detail"); - RNA_def_property_ui_icon(prop, ICON_MATERIAL, 0); - RNA_def_property_update(prop, NC_OBJECT | ND_LOD, NULL); - - prop = RNA_def_property(srna, "use_object_hysteresis", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flags", OB_LOD_USE_HYST); - RNA_def_property_ui_text(prop, "Hysteresis Override", "Override LoD Hysteresis scene setting for this LoD level"); - RNA_def_property_update(prop, NC_OBJECT | ND_LOD, NULL); -} - - static void rna_def_object(BlenderRNA *brna) { StructRNA *srna; @@ -2710,13 +2077,6 @@ static void rna_def_object(BlenderRNA *brna) /* RNA_def_property_collection_funcs(prop, NULL, NULL, NULL, NULL, NULL, NULL, NULL, "constraints__add", "constraints__remove"); */ rna_def_object_constraints(brna, prop); - /* game engine */ - prop = RNA_def_property(srna, "game", PROP_POINTER, PROP_NONE); - RNA_def_property_flag(prop, PROP_NEVER_NULL); - RNA_def_property_struct_type(prop, "GameObjectSettings"); - RNA_def_property_pointer_funcs(prop, "rna_Object_game_settings_get", NULL, NULL, NULL); - RNA_def_property_ui_text(prop, "Game Settings", "Game engine related settings for the object"); - /* vertex groups */ prop = RNA_def_property(srna, "vertex_groups", PROP_COLLECTION, PROP_NONE); RNA_def_property_collection_sdna(prop, NULL, "defbase", NULL); @@ -3040,13 +2400,6 @@ static void rna_def_object(BlenderRNA *brna) RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_ui_text(prop, "Dynamic Topology Sculpting", NULL); - /* Levels of Detail */ - prop = RNA_def_property(srna, "lod_levels", PROP_COLLECTION, PROP_NONE); - RNA_def_property_collection_sdna(prop, NULL, "lodlevels", NULL); - RNA_def_property_struct_type(prop, "LodLevel"); - RNA_def_property_ui_text(prop, "Level of Detail Levels", "A collection of detail levels to automatically switch between"); - RNA_def_property_update(prop, NC_OBJECT | ND_LOD, NULL); - /* Base Settings */ prop = RNA_def_property(srna, "is_from_duplicator", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "base_flag", BASE_FROMDUPLI); @@ -3124,13 +2477,11 @@ void RNA_def_object(BlenderRNA *brna) rna_def_object(brna); RNA_define_animate_sdna(false); - rna_def_object_game_settings(brna); rna_def_vertex_group(brna); rna_def_face_map(brna); rna_def_material_slot(brna); rna_def_dupli_object(brna); RNA_define_animate_sdna(true); - rna_def_object_lodlevel(brna); } #endif diff --git a/source/blender/makesrna/intern/rna_object_force.c b/source/blender/makesrna/intern/rna_object_force.c index 7d062d41e4f..3a61accfad3 100644 --- a/source/blender/makesrna/intern/rna_object_force.c +++ b/source/blender/makesrna/intern/rna_object_force.c @@ -1459,78 +1459,6 @@ static void rna_def_field(BlenderRNA *brna) /* falloff_power, use_max_distance, maximum_distance */ } -static void rna_def_game_softbody(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - srna = RNA_def_struct(brna, "GameSoftBodySettings", NULL); - RNA_def_struct_sdna(srna, "BulletSoftBody"); - RNA_def_struct_ui_text(srna, "Game Soft Body Settings", - "Soft body simulation settings for an object in the game engine"); - - /* Floats */ - - prop = RNA_def_property(srna, "linear_stiffness", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "linStiff"); - RNA_def_property_range(prop, 0.0f, 1.0f); - RNA_def_property_ui_text(prop, "Linear Stiffness", "Linear stiffness of the soft body links"); - - prop = RNA_def_property(srna, "dynamic_friction", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "kDF"); - RNA_def_property_range(prop, 0.0f, 1.0f); - RNA_def_property_ui_text(prop, "Friction", "Dynamic Friction"); - - prop = RNA_def_property(srna, "shape_threshold", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "kMT"); - RNA_def_property_range(prop, 0.0f, 1.0f); - RNA_def_property_ui_text(prop, "Threshold", "Shape matching threshold"); - - prop = RNA_def_property(srna, "collision_margin", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "margin"); - RNA_def_property_range(prop, 0.01f, 1.0f); - RNA_def_property_ui_text(prop, "Margin", - "Collision margin for soft body. Small value makes the algorithm unstable"); - - prop = RNA_def_property(srna, "weld_threshold", PROP_FLOAT, PROP_DISTANCE); - RNA_def_property_float_sdna(prop, NULL, "welding"); - RNA_def_property_range(prop, 0.0f, 0.01f); - RNA_def_property_ui_text(prop, "Welding", - "Welding threshold: distance between nearby vertices to be considered equal " - "=> set to 0.0 to disable welding test and speed up scene loading " - "(ok if the mesh has no duplicates)"); - - /* Integers */ - - prop = RNA_def_property(srna, "location_iterations", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "piterations"); - RNA_def_property_range(prop, 0, 10); - RNA_def_property_ui_text(prop, "Position Iterations", "Position solver iterations"); - - prop = RNA_def_property(srna, "cluster_iterations", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "numclusteriterations"); - RNA_def_property_range(prop, 1, 128); - RNA_def_property_ui_text(prop, "Cluster Iterations", "Number of cluster iterations"); - - /* Booleans */ - - prop = RNA_def_property(srna, "use_shape_match", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", OB_BSB_SHAPE_MATCHING); - RNA_def_property_ui_text(prop, "Shape Match", "Enable soft body shape matching goal"); - - prop = RNA_def_property(srna, "use_bending_constraints", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", OB_BSB_BENDING_CONSTRAINTS); - RNA_def_property_ui_text(prop, "Bending Const", "Enable bending constraints"); - - prop = RNA_def_property(srna, "use_cluster_rigid_to_softbody", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "collisionflags", OB_BSB_COL_CL_RS); - RNA_def_property_ui_text(prop, "Rigid to Soft Body", "Enable cluster collision between soft and rigid body"); - - prop = RNA_def_property(srna, "use_cluster_soft_to_softbody", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "collisionflags", OB_BSB_COL_CL_SS); - RNA_def_property_ui_text(prop, "Soft to Soft Body", "Enable cluster collision between soft and soft body"); -} - static void rna_def_softbody(BlenderRNA *brna) { StructRNA *srna; @@ -1851,7 +1779,6 @@ void RNA_def_object_force(BlenderRNA *brna) rna_def_collision(brna); rna_def_effector_weight(brna); rna_def_field(brna); - rna_def_game_softbody(brna); rna_def_softbody(brna); } diff --git a/source/blender/makesrna/intern/rna_property.c b/source/blender/makesrna/intern/rna_property.c deleted file mode 100644 index 7ee792b5d1f..00000000000 --- a/source/blender/makesrna/intern/rna_property.c +++ /dev/null @@ -1,203 +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): Blender Foundation (2008). - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file blender/makesrna/intern/rna_property.c - * \ingroup RNA - */ - - -#include - -#include "DNA_property_types.h" -#include "DNA_object_types.h" - -#include "BLI_path_util.h" -#include "BLI_string_utils.h" - -#include "BLT_translation.h" - -#include "RNA_define.h" -#include "RNA_enum_types.h" - -#include "rna_internal.h" - - -#include "WM_types.h" - -const EnumPropertyItem rna_enum_gameproperty_type_items[] = { - {GPROP_BOOL, "BOOL", 0, "Boolean", "Boolean Property"}, - {GPROP_INT, "INT", 0, "Integer", "Integer Property"}, - {GPROP_FLOAT, "FLOAT", 0, "Float", "Floating-Point Property"}, - {GPROP_STRING, "STRING", 0, "String", "String Property"}, - {GPROP_TIME, "TIMER", 0, "Timer", "Timer Property"}, - {0, NULL, 0, NULL, NULL} -}; - - -#ifdef RNA_RUNTIME - -#include "BKE_property.h" - -static StructRNA *rna_GameProperty_refine(struct PointerRNA *ptr) -{ - bProperty *property = (bProperty *)ptr->data; - - switch (property->type) { - case GPROP_BOOL: - return &RNA_GameBooleanProperty; - case GPROP_INT: - return &RNA_GameIntProperty; - case GPROP_FLOAT: - return &RNA_GameFloatProperty; - case GPROP_STRING: - return &RNA_GameStringProperty; - case GPROP_TIME: - return &RNA_GameTimerProperty; - default: - return &RNA_GameProperty; - } -} - -/* for both float and timer */ -static float rna_GameFloatProperty_value_get(PointerRNA *ptr) -{ - bProperty *prop = (bProperty *)(ptr->data); - return *(float *)(&prop->data); -} - -static void rna_GameFloatProperty_value_set(PointerRNA *ptr, float value) -{ - bProperty *prop = (bProperty *)(ptr->data); - CLAMP(value, -10000.0f, 10000.0f); - *(float *)(&prop->data) = value; -} - -static void rna_GameProperty_type_set(PointerRNA *ptr, int value) -{ - bProperty *prop = (bProperty *)(ptr->data); - - if (prop->type != value) { - prop->type = value; - BKE_bproperty_init(prop); - } -} - -static void rna_GameProperty_name_set(PointerRNA *ptr, const char *value) -{ - Object *ob = ptr->id.data; - bProperty *prop = ptr->data; - BLI_strncpy_utf8(prop->name, value, sizeof(prop->name)); - - BLI_uniquename(&ob->prop, prop, DATA_("Property"), '.', offsetof(bProperty, name), sizeof(prop->name)); -} - - -#else - -void RNA_def_gameproperty(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - /* Base Struct for GameProperty */ - srna = RNA_def_struct(brna, "GameProperty", NULL); - RNA_def_struct_ui_text(srna, "Game Property", "Game engine user defined object property"); - RNA_def_struct_sdna(srna, "bProperty"); - RNA_def_struct_refine_func(srna, "rna_GameProperty_refine"); - - prop = RNA_def_property(srna, "name", PROP_STRING, PROP_NONE); - RNA_def_property_ui_text(prop, "Name", "Available as GameObject attributes in the game engine's python API"); - RNA_def_struct_name_property(srna, prop); - RNA_def_property_string_funcs(prop, NULL, NULL, "rna_GameProperty_name_set"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "type", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_items(prop, rna_enum_gameproperty_type_items); - RNA_def_property_ui_text(prop, "Type", ""); - RNA_def_property_enum_funcs(prop, NULL, "rna_GameProperty_type_set", NULL); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "show_debug", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", PROP_DEBUG); - RNA_def_property_ui_text(prop, "Debug", "Print debug information for this property"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* GameBooleanProperty */ - srna = RNA_def_struct(brna, "GameBooleanProperty", "GameProperty"); - RNA_def_struct_ui_text(srna, "Game Boolean Property", "Game engine user defined Boolean property"); - RNA_def_struct_sdna(srna, "bProperty"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "value", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "data", 1); - RNA_def_property_ui_text(prop, "Value", "Property value"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* GameIntProperty */ - srna = RNA_def_struct(brna, "GameIntProperty", "GameProperty"); - RNA_def_struct_ui_text(srna, "Game Integer Property", "Game engine user defined integer number property"); - RNA_def_struct_sdna(srna, "bProperty"); - - prop = RNA_def_property(srna, "value", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "data"); - RNA_def_property_ui_text(prop, "Value", "Property value"); - RNA_def_property_range(prop, -10000, 10000); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* GameFloatProperty */ - srna = RNA_def_struct(brna, "GameFloatProperty", "GameProperty"); - RNA_def_struct_ui_text(srna, "Game Float Property", "Game engine user defined floating point number property"); - RNA_def_struct_sdna(srna, "bProperty"); - - prop = RNA_def_property(srna, "value", PROP_FLOAT, PROP_NONE); - /* RNA_def_property_float_sdna(prop, NULL, "data"); */ - RNA_def_property_ui_text(prop, "Value", "Property value"); - RNA_def_property_range(prop, -10000, 10000); - RNA_def_property_float_funcs(prop, "rna_GameFloatProperty_value_get", "rna_GameFloatProperty_value_set", NULL); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* GameTimerProperty */ - srna = RNA_def_struct(brna, "GameTimerProperty", "GameProperty"); - RNA_def_struct_ui_text(srna, "Game Timer Property", "Game engine user defined timer property"); - RNA_def_struct_sdna(srna, "bProperty"); - - prop = RNA_def_property(srna, "value", PROP_FLOAT, PROP_NONE); - /* RNA_def_property_float_sdna(prop, NULL, "data"); */ - RNA_def_property_ui_text(prop, "Value", "Property value"); - RNA_def_property_range(prop, -10000, 10000); - RNA_def_property_float_funcs(prop, "rna_GameFloatProperty_value_get", "rna_GameFloatProperty_value_set", NULL); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* GameStringProperty */ - srna = RNA_def_struct(brna, "GameStringProperty", "GameProperty"); - RNA_def_struct_ui_text(srna, "Game String Property", "Game engine user defined text string property"); - RNA_def_struct_sdna(srna, "bProperty"); - - prop = RNA_def_property(srna, "value", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "poin"); - RNA_def_property_string_maxlength(prop, MAX_PROPSTRING); - RNA_def_property_ui_text(prop, "Value", "Property value"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -#endif - diff --git a/source/blender/makesrna/intern/rna_scene.c b/source/blender/makesrna/intern/rna_scene.c index 1032acbae67..2e842687831 100644 --- a/source/blender/makesrna/intern/rna_scene.c +++ b/source/blender/makesrna/intern/rna_scene.c @@ -1627,27 +1627,6 @@ static void rna_Scene_sync_mode_set(PointerRNA *ptr, int value) } } -static int rna_GameSettings_auto_start_get(PointerRNA *UNUSED(ptr)) -{ - return (G.fileflags & G_FILE_AUTOPLAY) != 0; -} - -static void rna_GameSettings_auto_start_set(PointerRNA *UNUSED(ptr), int value) -{ - if (value) - G.fileflags |= G_FILE_AUTOPLAY; - else - G.fileflags &= ~G_FILE_AUTOPLAY; -} - -static void rna_GameSettings_exit_key_set(PointerRNA *ptr, int value) -{ - GameData *gm = (GameData *)ptr->data; - - if (ISKEYBOARD(value)) - gm->exitkey = value; -} - static TimeMarker *rna_TimeLine_add(Scene *scene, const char name[], int frame) { TimeMarker *marker = MEM_callocN(sizeof(TimeMarker), "TimeMarker"); @@ -3941,124 +3920,6 @@ void rna_def_freestyle_settings(BlenderRNA *brna) rna_def_freestyle_linesets(brna, prop); } -static void rna_def_scene_game_recast_data(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - static const EnumPropertyItem rna_enum_partitioning_items[] = { - {RC_PARTITION_WATERSHED, "WATERSHED", 0, "Watershed", "Classic Recast partitioning method generating the nicest tessellation"}, - {RC_PARTITION_MONOTONE, "MONOTONE", 0, "Monotone", "Fastest navmesh generation method, may create long thin polygons"}, - {RC_PARTITION_LAYERS, "LAYERS", 0, "Layers", "Reasonably fast method that produces better triangles than monotone partitioning"}, - {0, NULL, 0, NULL, NULL} - }; - - srna = RNA_def_struct(brna, "SceneGameRecastData", NULL); - RNA_def_struct_sdna(srna, "RecastData"); - RNA_def_struct_nested(brna, srna, "Scene"); - RNA_def_struct_ui_text(srna, "Recast Data", "Recast data for a Game data-block"); - - prop = RNA_def_property(srna, "cell_size", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "cellsize"); - RNA_def_property_ui_range(prop, 0.1, 1, 1, 2); - RNA_def_property_float_default(prop, 0.3f); - RNA_def_property_ui_text(prop, "Cell Size", "Rasterized cell size"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "cell_height", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "cellheight"); - RNA_def_property_ui_range(prop, 0.1, 1, 1, 2); - RNA_def_property_float_default(prop, 0.2f); - RNA_def_property_ui_text(prop, "Cell Height", "Rasterized cell height"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "agent_height", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "agentheight"); - RNA_def_property_ui_range(prop, 0.1, 5, 1, 2); - RNA_def_property_float_default(prop, 2.0f); - RNA_def_property_ui_text(prop, "Agent Height", "Minimum height where the agent can still walk"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "agent_radius", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "agentradius"); - RNA_def_property_ui_range(prop, 0.1, 5, 1, 2); - RNA_def_property_float_default(prop, 0.6f); - RNA_def_property_ui_text(prop, "Agent Radius", "Radius of the agent"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "climb_max", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "agentmaxclimb"); - RNA_def_property_ui_range(prop, 0.1, 5, 1, 2); - RNA_def_property_float_default(prop, 0.9f); - RNA_def_property_ui_text(prop, "Max Climb", "Maximum height between grid cells the agent can climb"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "slope_max", PROP_FLOAT, PROP_ANGLE); - RNA_def_property_float_sdna(prop, NULL, "agentmaxslope"); - RNA_def_property_range(prop, 0, M_PI_2); - RNA_def_property_float_default(prop, M_PI_4); - RNA_def_property_ui_text(prop, "Max Slope", "Maximum walkable slope angle"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - - prop = RNA_def_property(srna, "region_min_size", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "regionminsize"); - RNA_def_property_ui_range(prop, 0, 150, 1, 2); - RNA_def_property_float_default(prop, 8.0f); - RNA_def_property_ui_text(prop, "Min Region Size", "Minimum regions size (smaller regions will be deleted)"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "region_merge_size", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "regionmergesize"); - RNA_def_property_ui_range(prop, 0, 150, 1, 2); - RNA_def_property_float_default(prop, 20.0f); - RNA_def_property_ui_text(prop, "Merged Region Size", "Minimum regions size (smaller regions will be merged)"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "partitioning", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_bitflag_sdna(prop, NULL, "partitioning"); - RNA_def_property_enum_items(prop, rna_enum_partitioning_items); - RNA_def_property_enum_default(prop, RC_PARTITION_WATERSHED); - RNA_def_property_ui_text(prop, "Partitioning", "Choose partitioning method"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "edge_max_len", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "edgemaxlen"); - RNA_def_property_ui_range(prop, 0, 50, 1, 2); - RNA_def_property_float_default(prop, 12.0f); - RNA_def_property_ui_text(prop, "Max Edge Length", "Maximum contour edge length"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "edge_max_error", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "edgemaxerror"); - RNA_def_property_ui_range(prop, 0.1, 3.0, 1, 2); - RNA_def_property_float_default(prop, 1.3f); - RNA_def_property_ui_text(prop, "Max Edge Error", "Maximum distance error from contour to cells"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "verts_per_poly", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "vertsperpoly"); - RNA_def_property_ui_range(prop, 3, 12, 1, -1); - RNA_def_property_int_default(prop, 6); - RNA_def_property_ui_text(prop, "Verts Per Poly", "Max number of vertices per polygon"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "sample_dist", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "detailsampledist"); - RNA_def_property_ui_range(prop, 0.0, 16.0, 1, 2); - RNA_def_property_float_default(prop, 6.0f); - RNA_def_property_ui_text(prop, "Sample Distance", "Detail mesh sample spacing"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "sample_max_error", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "detailsamplemaxerror"); - RNA_def_property_ui_range(prop, 0.0, 16.0, 1, 2); - RNA_def_property_float_default(prop, 1.0f); - RNA_def_property_ui_text(prop, "Max Sample Error", "Detail mesh simplification max sample error"); - RNA_def_property_update(prop, NC_SCENE, NULL); -} - - static void rna_def_bake_data(BlenderRNA *brna) { StructRNA *srna; @@ -4222,493 +4083,6 @@ static void rna_def_bake_data(BlenderRNA *brna) RNA_def_property_clear_flag(prop, PROP_EDITABLE); } -static void rna_def_scene_game_data(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - static const EnumPropertyItem aasamples_items[] = { - {0, "SAMPLES_0", 0, "Off", ""}, - {2, "SAMPLES_2", 0, "2x", ""}, - {4, "SAMPLES_4", 0, "4x", ""}, - {8, "SAMPLES_8", 0, "8x", ""}, - {16, "SAMPLES_16", 0, "16x", ""}, - {0, NULL, 0, NULL, NULL} - }; - - static const EnumPropertyItem framing_types_items[] = { - {SCE_GAMEFRAMING_BARS, "LETTERBOX", 0, "Letterbox", - "Show the entire viewport in the display window, using bar horizontally or vertically"}, - {SCE_GAMEFRAMING_EXTEND, "EXTEND", 0, "Extend", - "Show the entire viewport in the display window, viewing more horizontally " - "or vertically"}, - {SCE_GAMEFRAMING_SCALE, "SCALE", 0, "Scale", "Stretch or squeeze the viewport to fill the display window"}, - {0, NULL, 0, NULL, NULL} - }; - - static const EnumPropertyItem dome_modes_items[] = { - {DOME_FISHEYE, "FISHEYE", 0, "Fisheye", ""}, - {DOME_TRUNCATED_FRONT, "TRUNCATED_FRONT", 0, "Front-Truncated", ""}, - {DOME_TRUNCATED_REAR, "TRUNCATED_REAR", 0, "Rear-Truncated", ""}, - {DOME_ENVMAP, "ENVMAP", 0, "Cube Map", ""}, - {DOME_PANORAM_SPH, "PANORAM_SPH", 0, "Spherical Panoramic", ""}, - {0, NULL, 0, NULL, NULL} - }; - - static const EnumPropertyItem stereo_modes_items[] = { - {STEREO_QUADBUFFERED, "QUADBUFFERED", 0, "Quad-Buffer", ""}, - {STEREO_ABOVEBELOW, "ABOVEBELOW", 0, "Above-Below", ""}, - {STEREO_INTERLACED, "INTERLACED", 0, "Interlaced", ""}, - {STEREO_ANAGLYPH, "ANAGLYPH", 0, "Anaglyph", ""}, - {STEREO_SIDEBYSIDE, "SIDEBYSIDE", 0, "Side-by-side", ""}, - {STEREO_VINTERLACE, "VINTERLACE", 0, "Vinterlace", ""}, - {STEREO_3DTVTOPBOTTOM, "3DTVTOPBOTTOM", 0, "3DTV Top-Bottom", ""}, - {0, NULL, 0, NULL, NULL} - }; - - static const EnumPropertyItem stereo_items[] = { - {STEREO_NOSTEREO, "NONE", 0, "None", "Disable Stereo and Dome environments"}, - {STEREO_ENABLED, "STEREO", 0, "Stereo", "Enable Stereo environment"}, - {STEREO_DOME, "DOME", 0, "Dome", "Enable Dome environment"}, - {0, NULL, 0, NULL, NULL} - }; - - static const EnumPropertyItem physics_engine_items[] = { - {WOPHY_NONE, "NONE", 0, "None", "Don't use a physics engine"}, - {WOPHY_BULLET, "BULLET", 0, "Bullet", "Use the Bullet physics engine"}, - {0, NULL, 0, NULL, NULL} - }; - - static const EnumPropertyItem material_items[] = { - {GAME_MAT_MULTITEX, "MULTITEXTURE", 0, "Multitexture", "Multitexture materials"}, - {GAME_MAT_GLSL, "GLSL", 0, "GLSL", "OpenGL shading language shaders"}, - {0, NULL, 0, NULL, NULL} - }; - - static const EnumPropertyItem obstacle_simulation_items[] = { - {OBSTSIMULATION_NONE, "NONE", 0, "None", ""}, - {OBSTSIMULATION_TOI_rays, "RVO_RAYS", 0, "RVO (rays)", ""}, - {OBSTSIMULATION_TOI_cells, "RVO_CELLS", 0, "RVO (cells)", ""}, - {0, NULL, 0, NULL, NULL} - }; - - static const EnumPropertyItem vsync_items[] = { - {VSYNC_OFF, "OFF", 0, "Off", "Disable vsync"}, - {VSYNC_ON, "ON", 0, "On", "Enable vsync"}, - {VSYNC_ADAPTIVE, "ADAPTIVE", 0, "Adaptive", "Enable adaptive vsync (if supported)"}, - {0, NULL, 0, NULL, NULL} - }; - - static const EnumPropertyItem storage_items[] = { - {RAS_STORE_AUTO, "AUTO", 0, "Auto Select", "Choose the best supported mode"}, - {RAS_STORE_VA, "VERTEX_ARRAY", 0, "Vertex Arrays", "Usually the best choice (good performance with display lists)"}, - {RAS_STORE_VBO, "VERTEX_BUFFER_OBJECT", 0, "Vertex Buffer Objects", - "Typically slower than vertex arrays with display lists, requires at least OpenGL 1.4"}, - {0, NULL, 0, NULL, NULL}}; - - srna = RNA_def_struct(brna, "SceneGameData", NULL); - RNA_def_struct_sdna(srna, "GameData"); - RNA_def_struct_nested(brna, srna, "Scene"); - RNA_def_struct_ui_text(srna, "Game Data", "Game data for a Scene data-block"); - - prop = RNA_def_property(srna, "resolution_x", PROP_INT, PROP_PIXEL); - RNA_def_property_int_sdna(prop, NULL, "xplay"); - RNA_def_property_range(prop, 4, 10000); - RNA_def_property_int_default(prop, 640); - RNA_def_property_ui_text(prop, "Resolution X", "Number of horizontal pixels in the screen"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "resolution_y", PROP_INT, PROP_PIXEL); - RNA_def_property_int_sdna(prop, NULL, "yplay"); - RNA_def_property_range(prop, 4, 10000); - RNA_def_property_int_default(prop, 480); - RNA_def_property_ui_text(prop, "Resolution Y", "Number of vertical pixels in the screen"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "vsync", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "vsync"); - RNA_def_property_enum_items(prop, vsync_items); - RNA_def_property_ui_text(prop, "Vsync", "Change vsync settings"); - - prop = RNA_def_property(srna, "samples", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "aasamples"); - RNA_def_property_enum_items(prop, aasamples_items); - RNA_def_property_ui_text(prop, "AA Samples", "The number of AA Samples to use for MSAA"); - - prop = RNA_def_property(srna, "depth", PROP_INT, PROP_UNSIGNED); - RNA_def_property_int_sdna(prop, NULL, "depth"); - RNA_def_property_range(prop, 8, 32); - RNA_def_property_int_default(prop, 32); - RNA_def_property_ui_text(prop, "Bits", "Display bit depth of full screen display"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "exit_key", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "exitkey"); - RNA_def_property_enum_items(prop, rna_enum_event_type_items); - RNA_def_property_translation_context(prop, BLT_I18NCONTEXT_UI_EVENTS); - RNA_def_property_enum_default(prop, ESCKEY); - RNA_def_property_enum_funcs(prop, NULL, "rna_GameSettings_exit_key_set", NULL); - RNA_def_property_ui_text(prop, "Exit Key", "The key that exits the Game Engine"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "raster_storage", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "raster_storage"); - RNA_def_property_enum_items(prop, storage_items); - RNA_def_property_ui_text(prop, "Storage", "Set the storage mode used by the rasterizer"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - /* Do we need it here ? (since we already have it in World */ - prop = RNA_def_property(srna, "frequency", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "freqplay"); - RNA_def_property_range(prop, 4, 2000); - RNA_def_property_int_default(prop, 60); - RNA_def_property_ui_text(prop, "Freq", "Display clock frequency of fullscreen display"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "show_fullscreen", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "playerflag", GAME_PLAYER_FULLSCREEN); - RNA_def_property_ui_text(prop, "Fullscreen", "Start player in a new fullscreen display"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "use_desktop", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "playerflag", GAME_PLAYER_DESKTOP_RESOLUTION); - RNA_def_property_ui_text(prop, "Desktop", "Use the current desktop resolution in fullscreen mode"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - /* Framing */ - prop = RNA_def_property(srna, "frame_type", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "framing.type"); - RNA_def_property_enum_items(prop, framing_types_items); - RNA_def_property_ui_text(prop, "Framing Types", "Select the type of Framing you want"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "frame_color", PROP_FLOAT, PROP_COLOR); - RNA_def_property_float_sdna(prop, NULL, "framing.col"); - RNA_def_property_range(prop, 0.0f, 1.0f); - RNA_def_property_array(prop, 3); - RNA_def_property_ui_text(prop, "Framing Color", "Set color of the bars"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - /* Stereo */ - prop = RNA_def_property(srna, "stereo", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "stereoflag"); - RNA_def_property_enum_items(prop, stereo_items); - RNA_def_property_ui_text(prop, "Stereo Options", ""); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "stereo_mode", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "stereomode"); - RNA_def_property_enum_items(prop, stereo_modes_items); - RNA_def_property_enum_default(prop, STEREO_ANAGLYPH); - RNA_def_property_ui_text(prop, "Stereo Mode", "Stereographic techniques"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "stereo_eye_separation", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "eyeseparation"); - RNA_def_property_range(prop, 0.01, 5.0); - RNA_def_property_float_default(prop, 0.1f); - RNA_def_property_ui_text(prop, "Eye Separation", - "Set the distance between the eyes - the camera focal distance/30 should be fine"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - /* Dome */ - prop = RNA_def_property(srna, "dome_mode", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "dome.mode"); - RNA_def_property_enum_items(prop, dome_modes_items); - RNA_def_property_ui_text(prop, "Dome Mode", "Dome physical configurations"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "dome_tessellation", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "dome.res"); - RNA_def_property_ui_range(prop, 1, 8, 1, 1); - RNA_def_property_int_default(prop, 4); - RNA_def_property_ui_text(prop, "Tessellation", "Tessellation level - check the generated mesh in wireframe mode"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "dome_buffer_resolution", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "dome.resbuf"); - RNA_def_property_ui_range(prop, 0.1, 1.0, 0.1, 2); - RNA_def_property_float_default(prop, 1.0f); - RNA_def_property_ui_text(prop, "Buffer Resolution", "Buffer Resolution - decrease it to increase speed"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "dome_angle", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "dome.angle"); - RNA_def_property_ui_range(prop, 90, 250, 1, 1); - RNA_def_property_int_default(prop, 180); - RNA_def_property_ui_text(prop, "Angle", "Field of View of the Dome - it only works in mode Fisheye and Truncated"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "dome_tilt", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "dome.tilt"); - RNA_def_property_ui_range(prop, -180, 180, 1, 1); - RNA_def_property_ui_text(prop, "Tilt", "Camera rotation in horizontal axis"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "dome_text", PROP_POINTER, PROP_NONE); - RNA_def_property_pointer_sdna(prop, NULL, "dome.warptext"); - RNA_def_property_struct_type(prop, "Text"); - RNA_def_property_flag(prop, PROP_EDITABLE); - RNA_def_property_ui_text(prop, "Warp Data", "Custom Warp Mesh data file"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - /* physics */ - prop = RNA_def_property(srna, "physics_engine", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "physicsEngine"); - RNA_def_property_enum_items(prop, physics_engine_items); - RNA_def_property_enum_default(prop, WOPHY_BULLET); - RNA_def_property_ui_text(prop, "Physics Engine", "Physics engine used for physics simulation in the game engine"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "physics_gravity", PROP_FLOAT, PROP_ACCELERATION); - RNA_def_property_float_sdna(prop, NULL, "gravity"); - RNA_def_property_ui_range(prop, 0.0, 25.0, 1, 2); - RNA_def_property_range(prop, 0.0, 10000.0); - RNA_def_property_float_default(prop, 9.8f); - RNA_def_property_ui_text(prop, "Physics Gravity", - "Gravitational constant used for physics simulation in the game engine"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "occlusion_culling_resolution", PROP_INT, PROP_PIXEL); - RNA_def_property_int_sdna(prop, NULL, "occlusionRes"); - RNA_def_property_range(prop, 128.0, 1024.0); - RNA_def_property_int_default(prop, 128); - RNA_def_property_ui_text(prop, "Occlusion Resolution", - "Size of the occlusion buffer, use higher value for better precision (slower)"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "fps", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "ticrate"); - RNA_def_property_ui_range(prop, 1, 60, 1, 1); - RNA_def_property_range(prop, 1, 10000); - RNA_def_property_int_default(prop, 60); - RNA_def_property_ui_text(prop, "Frames Per Second", - "Nominal number of game frames per second " - "(physics fixed timestep = 1/fps, independently of actual frame rate)"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "logic_step_max", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "maxlogicstep"); - RNA_def_property_range(prop, 1, 10000); - RNA_def_property_ui_range(prop, 1, 50, 1, 1); - RNA_def_property_int_default(prop, 5); - RNA_def_property_ui_text(prop, "Max Logic Steps", - "Maximum number of logic frame per game frame if graphics slows down the game, " - "higher value allows better synchronization with physics"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "physics_step_max", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "maxphystep"); - RNA_def_property_range(prop, 1, 10000); - RNA_def_property_ui_range(prop, 1, 50, 1, 1); - RNA_def_property_int_default(prop, 5); - RNA_def_property_ui_text(prop, "Max Physics Steps", - "Maximum number of physics step per game frame if graphics slows down the game, " - "higher value allows physics to keep up with realtime"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "physics_step_sub", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "physubstep"); - RNA_def_property_range(prop, 1, 50); - RNA_def_property_ui_range(prop, 1, 5, 1, 1); - RNA_def_property_int_default(prop, 1); - RNA_def_property_ui_text(prop, "Physics Sub Steps", - "Number of simulation substep per physic timestep, " - "higher value give better physics precision"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "deactivation_linear_threshold", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "lineardeactthreshold"); - RNA_def_property_ui_range(prop, 0.001, 10000.0, 2, 3); - RNA_def_property_range(prop, 0.001, 10000.0); - RNA_def_property_float_default(prop, 0.8f); - RNA_def_property_ui_text(prop, "Deactivation Linear Threshold", - "Linear velocity that an object must be below before the deactivation timer can start"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "deactivation_angular_threshold", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "angulardeactthreshold"); - RNA_def_property_ui_range(prop, 0.001, 10000.0, 2, 3); - RNA_def_property_range(prop, 0.001, 10000.0); - RNA_def_property_float_default(prop, 1.0f); - RNA_def_property_ui_text(prop, "Deactivation Angular Threshold", - "Angular velocity that an object must be below before the deactivation timer can start"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "deactivation_time", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "deactivationtime"); - RNA_def_property_ui_range(prop, 0.0, 60.0, 1, 1); - RNA_def_property_range(prop, 0.0, 60.0); - RNA_def_property_ui_text(prop, "Deactivation Time", - "Amount of time (in seconds) after which objects with a velocity less than the given " - "threshold will deactivate (0.0 means no deactivation)"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - /* mode */ - /* not used *//* deprecated !!!!!!!!!!!!! */ - prop = RNA_def_property(srna, "use_occlusion_culling", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "mode", WO_DBVT_CULLING); - RNA_def_property_ui_text(prop, "DBVT Culling", - "Use optimized Bullet DBVT tree for view frustum and occlusion culling (more efficient, " - "but it can waste unnecessary CPU if the scene doesn't have occluder objects)"); - - /* not used *//* deprecated !!!!!!!!!!!!! */ - prop = RNA_def_property(srna, "use_activity_culling", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "mode", WO_ACTIVITY_CULLING); - RNA_def_property_ui_text(prop, "Activity Culling", "Activity culling is enabled"); - - /* not used *//* deprecated !!!!!!!!!!!!! */ - prop = RNA_def_property(srna, "activity_culling_box_radius", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "activityBoxRadius"); - RNA_def_property_range(prop, 0.0, 1000.0); - RNA_def_property_ui_text(prop, "Box Radius", - "Radius of the activity bubble, in Manhattan length " - "(objects outside the box are activity-culled)"); - - /* booleans */ - prop = RNA_def_property(srna, "show_debug_properties", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", GAME_SHOW_DEBUG_PROPS); - RNA_def_property_ui_text(prop, "Show Debug Properties", - "Show properties marked for debugging while the game runs"); - - prop = RNA_def_property(srna, "show_framerate_profile", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", GAME_SHOW_FRAMERATE); - RNA_def_property_ui_text(prop, "Show Framerate and Profile", - "Show framerate and profiling information while the game runs"); - - prop = RNA_def_property(srna, "show_physics_visualization", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", GAME_SHOW_PHYSICS); - RNA_def_property_ui_text(prop, "Show Physics Visualization", - "Show a visualization of physics bounds and interactions"); - - prop = RNA_def_property(srna, "show_mouse", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", GAME_SHOW_MOUSE); - RNA_def_property_ui_text(prop, "Show Mouse", "Start player with a visible mouse cursor"); - - prop = RNA_def_property(srna, "use_frame_rate", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", GAME_ENABLE_ALL_FRAMES); - RNA_def_property_ui_text(prop, "Use Frame Rate", - "Respect the frame rate from the Physics panel in the world properties " - "rather than rendering as many frames as possible"); - - prop = RNA_def_property(srna, "use_deprecation_warnings", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", GAME_IGNORE_DEPRECATION_WARNINGS); - RNA_def_property_ui_text(prop, "Deprecation Warnings", - "Print warnings when using deprecated features in the python API"); - - prop = RNA_def_property(srna, "use_animation_record", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", GAME_ENABLE_ANIMATION_RECORD); - RNA_def_property_ui_text(prop, "Record Animation", "Record animation to F-Curves"); - - prop = RNA_def_property(srna, "use_auto_start", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_funcs(prop, "rna_GameSettings_auto_start_get", "rna_GameSettings_auto_start_set"); - RNA_def_property_ui_text(prop, "Auto Start", "Automatically start game at load time"); - - prop = RNA_def_property(srna, "use_restrict_animation_updates", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", GAME_RESTRICT_ANIM_UPDATES); - RNA_def_property_ui_text(prop, "Restrict Animation Updates", - "Restrict the number of animation updates to the animation FPS (this is " - "better for performance, but can cause issues with smooth playback)"); - - /* materials */ - prop = RNA_def_property(srna, "material_mode", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "matmode"); - RNA_def_property_enum_items(prop, material_items); - RNA_def_property_ui_text(prop, "Material Mode", "Material mode to use for rendering"); - RNA_def_property_update(prop, NC_SCENE | NA_EDITED, NULL); - - prop = RNA_def_property(srna, "use_glsl_lights", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", GAME_GLSL_NO_LIGHTS); - RNA_def_property_ui_text(prop, "GLSL Lights", "Use lights for GLSL rendering"); - RNA_def_property_update(prop, NC_SCENE | NA_EDITED, "rna_Scene_glsl_update"); - - prop = RNA_def_property(srna, "use_glsl_shaders", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", GAME_GLSL_NO_SHADERS); - RNA_def_property_ui_text(prop, "GLSL Shaders", "Use shaders for GLSL rendering"); - RNA_def_property_update(prop, NC_SCENE | NA_EDITED, "rna_Scene_glsl_update"); - - prop = RNA_def_property(srna, "use_glsl_shadows", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", GAME_GLSL_NO_SHADOWS); - RNA_def_property_ui_text(prop, "GLSL Shadows", "Use shadows for GLSL rendering"); - RNA_def_property_update(prop, NC_SCENE | NA_EDITED, "rna_Scene_glsl_update"); - - prop = RNA_def_property(srna, "use_glsl_ramps", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", GAME_GLSL_NO_RAMPS); - RNA_def_property_ui_text(prop, "GLSL Ramps", "Use ramps for GLSL rendering"); - RNA_def_property_update(prop, NC_SCENE | NA_EDITED, "rna_Scene_glsl_update"); - - prop = RNA_def_property(srna, "use_glsl_nodes", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", GAME_GLSL_NO_NODES); - RNA_def_property_ui_text(prop, "GLSL Nodes", "Use nodes for GLSL rendering"); - RNA_def_property_update(prop, NC_SCENE | NA_EDITED, "rna_Scene_glsl_update"); - - prop = RNA_def_property(srna, "use_glsl_color_management", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", GAME_GLSL_NO_COLOR_MANAGEMENT); - RNA_def_property_ui_text(prop, "GLSL Color Management", "Use color management for GLSL rendering"); - RNA_def_property_update(prop, NC_SCENE | NA_EDITED, "rna_Scene_glsl_update"); - - prop = RNA_def_property(srna, "use_glsl_extra_textures", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", GAME_GLSL_NO_EXTRA_TEX); - RNA_def_property_ui_text(prop, "GLSL Extra Textures", - "Use extra textures like normal or specular maps for GLSL rendering"); - RNA_def_property_update(prop, NC_SCENE | NA_EDITED, "rna_Scene_glsl_update"); - - prop = RNA_def_property(srna, "use_glsl_environment_lighting", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", GAME_GLSL_NO_ENV_LIGHTING); - RNA_def_property_ui_text(prop, "GLSL Environment Lighting", "Use environment lighting for GLSL rendering"); - RNA_def_property_update(prop, NC_SCENE | NA_EDITED, "rna_Scene_glsl_update"); - - prop = RNA_def_property(srna, "use_material_caching", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", GAME_NO_MATERIAL_CACHING); - RNA_def_property_ui_text(prop, "Use Material Caching", - "Cache materials in the converter (this is faster, but can cause problems with older " - "Singletexture and Multitexture games)"); - - /* obstacle simulation */ - prop = RNA_def_property(srna, "obstacle_simulation", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "obstacleSimulation"); - RNA_def_property_enum_items(prop, obstacle_simulation_items); - RNA_def_property_ui_text(prop, "Obstacle simulation", "Simulation used for obstacle avoidance in the game engine"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "level_height", PROP_FLOAT, PROP_ACCELERATION); - RNA_def_property_float_sdna(prop, NULL, "levelHeight"); - RNA_def_property_range(prop, 0.0f, 200.0f); - RNA_def_property_float_default(prop, 2.0f); - RNA_def_property_ui_text(prop, "Level height", - "Max difference in heights of obstacles to enable their interaction"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "show_obstacle_simulation", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", GAME_SHOW_OBSTACLE_SIMULATION); - RNA_def_property_ui_text(prop, "Visualization", "Enable debug visualization for obstacle simulation"); - - /* Recast Settings */ - prop = RNA_def_property(srna, "recast_data", PROP_POINTER, PROP_NONE); - RNA_def_property_flag(prop, PROP_NEVER_NULL); - RNA_def_property_pointer_sdna(prop, NULL, "recastData"); - RNA_def_property_struct_type(prop, "SceneGameRecastData"); - RNA_def_property_ui_text(prop, "Recast Data", ""); - - /* Nestled Data */ - rna_def_scene_game_recast_data(brna); - - /* LoD */ - prop = RNA_def_property(srna, "use_scene_hysteresis", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "lodflag", SCE_LOD_USE_HYST); - RNA_def_property_ui_text(prop, "Hysteresis", "Use LoD Hysteresis setting for the scene"); - RNA_def_property_update(prop, NC_SCENE, NULL); - - prop = RNA_def_property(srna, "scene_hysteresis_percentage", PROP_INT, PROP_PERCENTAGE); - RNA_def_property_int_sdna(prop, NULL, "scehysteresis"); - RNA_def_property_range(prop, 0, 100); - RNA_def_property_ui_range(prop, 0, 100, 10, 1); - RNA_def_property_int_default(prop, 10); - RNA_def_property_ui_text(prop, "Hysteresis %", - "Minimum distance change required to transition to the previous level of detail"); - RNA_def_property_update(prop, NC_SCENE, NULL); -} - static void rna_def_gpu_dof_fx(BlenderRNA *brna) { StructRNA *srna; @@ -6950,13 +6324,6 @@ void RNA_def_scene(BlenderRNA *brna) RNA_def_property_update(prop, NC_SCENE, NULL); RNA_def_property_float_funcs(prop, NULL, "rna_Scene_volume_set", NULL); - /* Game Settings */ - prop = RNA_def_property(srna, "game_settings", PROP_POINTER, PROP_NONE); - RNA_def_property_flag(prop, PROP_NEVER_NULL); - RNA_def_property_pointer_sdna(prop, NULL, "gm"); - RNA_def_property_struct_type(prop, "SceneGameData"); - RNA_def_property_ui_text(prop, "Game Data", ""); - /* Statistics */ func = RNA_def_function(srna, "statistics", "ED_info_stats_string"); parm = RNA_def_pointer(func, "view_layer", "ViewLayer", "", "Active layer"); @@ -7020,7 +6387,6 @@ void RNA_def_scene(BlenderRNA *brna) rna_def_statvis(brna); rna_def_unit_settings(brna); rna_def_scene_image_format_data(brna); - rna_def_scene_game_data(brna); rna_def_selected_uv_element(brna); rna_def_display_safe_areas(brna); RNA_define_animate_sdna(true); diff --git a/source/blender/makesrna/intern/rna_sensor.c b/source/blender/makesrna/intern/rna_sensor.c deleted file mode 100644 index 735df471721..00000000000 --- a/source/blender/makesrna/intern/rna_sensor.c +++ /dev/null @@ -1,939 +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): Blender Foundation (2008). - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file blender/makesrna/intern/rna_sensor.c - * \ingroup RNA - */ - -#include - -#include "DNA_constraint_types.h" -#include "DNA_object_types.h" -#include "DNA_sensor_types.h" - -#include "BLI_utildefines.h" -#include "BLI_math.h" -#include "BLI_string_utils.h" - -#include "BLT_translation.h" - -#include "RNA_define.h" -#include "RNA_enum_types.h" -#include "RNA_access.h" - -#include "rna_internal.h" - -#include "WM_types.h" - -/* Always keep in alphabetical order */ -static const EnumPropertyItem sensor_type_items[] = { - {SENS_ACTUATOR, "ACTUATOR", 0, "Actuator", ""}, - {SENS_ALWAYS, "ALWAYS", 0, "Always", ""}, - {SENS_ARMATURE, "ARMATURE", 0, "Armature", ""}, - {SENS_COLLISION, "COLLISION", 0, "Collision", ""}, - {SENS_DELAY, "DELAY", 0, "Delay", ""}, - {SENS_JOYSTICK, "JOYSTICK", 0, "Joystick", ""}, - {SENS_KEYBOARD, "KEYBOARD", 0, "Keyboard", ""}, - {SENS_MESSAGE, "MESSAGE", 0, "Message", ""}, - {SENS_MOUSE, "MOUSE", 0, "Mouse", ""}, - {SENS_NEAR, "NEAR", 0, "Near", ""}, - {SENS_PROPERTY, "PROPERTY", 0, "Property", ""}, - {SENS_RADAR, "RADAR", 0, "Radar", ""}, - {SENS_RANDOM, "RANDOM", 0, "Random", ""}, - {SENS_RAY, "RAY", 0, "Ray", ""}, - {0, NULL, 0, NULL, NULL} -}; - -#ifdef RNA_RUNTIME - -#include "BKE_sca.h" -#include "DNA_controller_types.h" - -static StructRNA *rna_Sensor_refine(struct PointerRNA *ptr) -{ - bSensor *sensor = (bSensor *)ptr->data; - - switch (sensor->type) { - case SENS_ALWAYS: - return &RNA_AlwaysSensor; - case SENS_NEAR: - return &RNA_NearSensor; - case SENS_KEYBOARD: - return &RNA_KeyboardSensor; - case SENS_PROPERTY: - return &RNA_PropertySensor; - case SENS_ARMATURE: - return &RNA_ArmatureSensor; - case SENS_MOUSE: - return &RNA_MouseSensor; - case SENS_COLLISION: - return &RNA_CollisionSensor; - case SENS_RADAR: - return &RNA_RadarSensor; - case SENS_RANDOM: - return &RNA_RandomSensor; - case SENS_RAY: - return &RNA_RaySensor; - case SENS_MESSAGE: - return &RNA_MessageSensor; - case SENS_JOYSTICK: - return &RNA_JoystickSensor; - case SENS_ACTUATOR: - return &RNA_ActuatorSensor; - case SENS_DELAY: - return &RNA_DelaySensor; - default: - return &RNA_Sensor; - } -} - -static void rna_Sensor_name_set(PointerRNA *ptr, const char *value) -{ - Object *ob = ptr->id.data; - bSensor *sens = ptr->data; - BLI_strncpy_utf8(sens->name, value, sizeof(sens->name)); - BLI_uniquename(&ob->sensors, sens, DATA_("Sensor"), '.', offsetof(bSensor, name), sizeof(sens->name)); -} - -static void rna_Sensor_type_set(struct PointerRNA *ptr, int value) -{ - bSensor *sens = (bSensor *)ptr->data; - if (value != sens->type) { - sens->type = value; - init_sensor(sens); - } -} - -/* Always keep in alphabetical order */ - -static void rna_Sensor_controllers_begin(CollectionPropertyIterator *iter, PointerRNA *ptr) -{ - bSensor *sens = (bSensor *)ptr->data; - rna_iterator_array_begin(iter, sens->links, sizeof(bController *), (int)sens->totlinks, 0, NULL); -} - -static int rna_Sensor_controllers_length(PointerRNA *ptr) -{ - bSensor *sens = (bSensor *)ptr->data; - return (int) sens->totlinks; -} - -const EnumPropertyItem *rna_Sensor_type_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free) -{ - EnumPropertyItem *item = NULL; - Object *ob = NULL; - int totitem = 0; - - if (ptr->type == &RNA_Sensor || RNA_struct_is_a(ptr->type, &RNA_Sensor)) { - ob = (Object *)ptr->id.data; - } - else { - /* can't use ob from ptr->id.data because that enum is also used by operators */ - ob = CTX_data_active_object(C); - } - - RNA_enum_items_add_value(&item, &totitem, sensor_type_items, SENS_ACTUATOR); - RNA_enum_items_add_value(&item, &totitem, sensor_type_items, SENS_ALWAYS); - - if (ob != NULL) { - if (ob->type == OB_ARMATURE) { - RNA_enum_items_add_value(&item, &totitem, sensor_type_items, SENS_ARMATURE); - } - } - RNA_enum_items_add_value(&item, &totitem, sensor_type_items, SENS_COLLISION); - RNA_enum_items_add_value(&item, &totitem, sensor_type_items, SENS_DELAY); - RNA_enum_items_add_value(&item, &totitem, sensor_type_items, SENS_JOYSTICK); - RNA_enum_items_add_value(&item, &totitem, sensor_type_items, SENS_KEYBOARD); - RNA_enum_items_add_value(&item, &totitem, sensor_type_items, SENS_MESSAGE); - RNA_enum_items_add_value(&item, &totitem, sensor_type_items, SENS_MOUSE); - RNA_enum_items_add_value(&item, &totitem, sensor_type_items, SENS_NEAR); - RNA_enum_items_add_value(&item, &totitem, sensor_type_items, SENS_PROPERTY); - RNA_enum_items_add_value(&item, &totitem, sensor_type_items, SENS_RADAR); - RNA_enum_items_add_value(&item, &totitem, sensor_type_items, SENS_RANDOM); - RNA_enum_items_add_value(&item, &totitem, sensor_type_items, SENS_RAY); - RNA_enum_items_add_value(&item, &totitem, sensor_type_items, SENS_TOUCH); - - RNA_enum_item_end(&item, &totitem); - *r_free = true; - - return item; -} - -static void rna_Sensor_keyboard_key_set(struct PointerRNA *ptr, int value) -{ - bSensor *sens = (bSensor *)ptr->data; - bKeyboardSensor *ks = (bKeyboardSensor *)sens->data; - - if (ISKEYBOARD(value)) - ks->key = value; - else - ks->key = 0; -} - -static void rna_Sensor_keyboard_modifier_set(struct PointerRNA *ptr, int value) -{ - bSensor *sens = (bSensor *)ptr->data; - bKeyboardSensor *ks = (bKeyboardSensor *)sens->data; - - if (ISKEYBOARD(value)) - ks->qual = value; - else - ks->qual = 0; -} - -static void rna_Sensor_keyboard_modifier2_set(struct PointerRNA *ptr, int value) -{ - bSensor *sens = (bSensor *)ptr->data; - bKeyboardSensor *ks = (bKeyboardSensor *)sens->data; - - if (ISKEYBOARD(value)) - ks->qual2 = value; - else - ks->qual2 = 0; -} - -static void rna_Sensor_tap_set(struct PointerRNA *ptr, int value) -{ - bSensor *sens = (bSensor *)ptr->data; - - sens->tap = value; - if (sens->tap == 1) - sens->level = 0; -} - -static void rna_Sensor_level_set(struct PointerRNA *ptr, int value) -{ - bSensor *sens = (bSensor *)ptr->data; - - sens->level = value; - if (sens->level == 1) - sens->tap = 0; -} - -static void rna_Sensor_Armature_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *ptr) -{ - bSensor *sens = (bSensor *)ptr->data; - bArmatureSensor *as = sens->data; - Object *ob = (Object *)ptr->id.data; - - char *posechannel = as->posechannel; - char *constraint = as->constraint; - - /* check that bone exist in the active object */ - if (ob->type == OB_ARMATURE && ob->pose) { - bPoseChannel *pchan; - bPose *pose = ob->pose; - for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) { - if (STREQ(pchan->name, posechannel)) { - /* found it, now look for constraint channel */ - bConstraint *con; - for (con = pchan->constraints.first; con; con = con->next) { - if (STREQ(con->name, constraint)) { - /* found it, all ok */ - return; - } - } - /* didn't find constraint, make empty */ - constraint[0] = 0; - return; - } - } - } - /* didn't find any */ - posechannel[0] = 0; - constraint[0] = 0; -} -#else - -static void rna_def_sensor(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - srna = RNA_def_struct(brna, "Sensor", NULL); - RNA_def_struct_ui_text(srna, "Sensor", "Game engine logic brick to detect events"); - RNA_def_struct_sdna(srna, "bSensor"); - RNA_def_struct_refine_func(srna, "rna_Sensor_refine"); - - prop = RNA_def_property(srna, "name", PROP_STRING, PROP_NONE); - RNA_def_property_ui_text(prop, "Name", "Sensor name"); - RNA_def_property_string_funcs(prop, NULL, NULL, "rna_Sensor_name_set"); - RNA_def_struct_name_property(srna, prop); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "type", PROP_ENUM, PROP_NONE); - RNA_def_property_clear_flag(prop, PROP_ANIMATABLE); - RNA_def_property_enum_items(prop, sensor_type_items); - RNA_def_property_enum_funcs(prop, NULL, "rna_Sensor_type_set", "rna_Sensor_type_itemf"); - RNA_def_property_ui_text(prop, "Type", ""); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "pin", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", SENS_PIN); - RNA_def_property_ui_text(prop, "Pinned", "Display when not linked to a visible states controller"); - RNA_def_property_ui_icon(prop, ICON_UNPINNED, 1); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "active", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", SENS_DEACTIVATE); - RNA_def_property_ui_text(prop, "Active", "Set active state of the sensor"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "show_expanded", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", SENS_SHOW); - RNA_def_property_ui_text(prop, "Expanded", "Set sensor expanded in the user interface"); - RNA_def_property_ui_icon(prop, ICON_TRIA_RIGHT, 1); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "invert", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_ui_text(prop, "Invert Output", "Invert the level(output) of this sensor"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_level", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "level", 1); - RNA_def_property_ui_text(prop, "Level", - "Level detector, trigger controllers of new states " - "(only applicable upon logic state transition)"); - RNA_def_property_boolean_funcs(prop, NULL, "rna_Sensor_level_set"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_pulse_true_level", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "pulse", SENS_PULSE_REPEAT); - RNA_def_property_ui_text(prop, "Pulse True Level", "Activate TRUE level triggering (pulse mode)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_pulse_false_level", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "pulse", SENS_NEG_PULSE_MODE); - RNA_def_property_ui_text(prop, "Pulse False Level", "Activate FALSE level triggering (pulse mode)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "tick_skip", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "freq"); - RNA_def_property_ui_text(prop, "Skip", - "Number of logic ticks skipped between 2 active pulses " - "(0 = pulse every logic tick, 1 = skip 1 logic tick between pulses, etc.)"); - RNA_def_property_range(prop, 0, 10000); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_tap", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "tap", 1); - RNA_def_property_boolean_funcs(prop, NULL, "rna_Sensor_tap_set"); - RNA_def_property_ui_text(prop, "Tap", - "Trigger controllers only for an instant, even while the sensor remains true"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "controllers", PROP_COLLECTION, PROP_NONE); - RNA_def_property_collection_sdna(prop, NULL, "links", NULL); - RNA_def_property_struct_type(prop, "Controller"); - RNA_def_property_ui_text(prop, "Controllers", "The list containing the controllers connected to the sensor"); - RNA_def_property_collection_funcs(prop, "rna_Sensor_controllers_begin", "rna_iterator_array_next", - "rna_iterator_array_end", "rna_iterator_array_dereference_get", - "rna_Sensor_controllers_length", NULL, NULL, NULL); - - - RNA_api_sensor(srna); -} - -static void rna_def_always_sensor(BlenderRNA *brna) -{ - StructRNA *srna; - srna = RNA_def_struct(brna, "AlwaysSensor", "Sensor"); - RNA_def_struct_ui_text(srna, "Always Sensor", "Sensor to generate continuous pulses"); -} - -static void rna_def_near_sensor(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - srna = RNA_def_struct(brna, "NearSensor", "Sensor"); - RNA_def_struct_ui_text(srna, "Near Sensor", "Sensor to detect nearby objects"); - RNA_def_struct_sdna_from(srna, "bNearSensor", "data"); - - prop = RNA_def_property(srna, "property", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "name"); - RNA_def_property_ui_text(prop, "Property", "Only look for objects with this property (blank = all objects)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "distance", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "dist"); - RNA_def_property_ui_text(prop, "Distance", "Trigger distance"); - RNA_def_property_range(prop, 0.0f, 10000.0f); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "reset_distance", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "resetdist"); - RNA_def_property_ui_text(prop, "Reset Distance", "The distance where the sensor forgets the actor"); - RNA_def_property_range(prop, 0.0f, 10000.0f); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -static void rna_def_mouse_sensor(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - static const EnumPropertyItem mouse_event_items[] = { - {BL_SENS_MOUSE_LEFT_BUTTON, "LEFTCLICK", 0, "Left Button", ""}, - {BL_SENS_MOUSE_MIDDLE_BUTTON, "MIDDLECLICK", 0, "Middle Button", ""}, - {BL_SENS_MOUSE_RIGHT_BUTTON, "RIGHTCLICK", 0, "Right Button", ""}, - {BL_SENS_MOUSE_WHEEL_UP, "WHEELUP", 0, "Wheel Up", ""}, - {BL_SENS_MOUSE_WHEEL_DOWN, "WHEELDOWN", 0, "Wheel Down", ""}, - {BL_SENS_MOUSE_MOVEMENT, "MOVEMENT", 0, "Movement", ""}, - {BL_SENS_MOUSE_MOUSEOVER, "MOUSEOVER", 0, "Mouse Over", ""}, - {BL_SENS_MOUSE_MOUSEOVER_ANY, "MOUSEOVERANY", 0, "Mouse Over Any", ""}, - {0, NULL, 0, NULL, NULL} - }; - - static const EnumPropertyItem prop_mouse_type_items[] = { - {SENS_COLLISION_PROPERTY, "PROPERTY", ICON_LOGIC, "Property", "Use a property for ray intersections"}, - {SENS_COLLISION_MATERIAL, "MATERIAL", ICON_MATERIAL_DATA, "Material", "Use a material for ray intersections"}, - {0, NULL, 0, NULL, NULL} - }; - - srna = RNA_def_struct(brna, "MouseSensor", "Sensor"); - RNA_def_struct_ui_text(srna, "Mouse Sensor", "Sensor to detect mouse events"); - RNA_def_struct_sdna_from(srna, "bMouseSensor", "data"); - - prop = RNA_def_property(srna, "mouse_event", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "type"); - RNA_def_property_enum_items(prop, mouse_event_items); - RNA_def_property_ui_text(prop, "Mouse Event", "Type of event this mouse sensor should trigger on"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_pulse", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", SENS_MOUSE_FOCUS_PULSE); - RNA_def_property_ui_text(prop, "Pulse", "Moving the mouse over a different object generates a pulse"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_material", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_bitflag_sdna(prop, NULL, "mode"); - RNA_def_property_enum_items(prop, prop_mouse_type_items); - RNA_def_property_ui_text(prop, "M/P", "Toggle collision on material or property"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "property", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "propname"); - RNA_def_property_ui_text(prop, "Property", "Only look for objects with this property (blank = all objects)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "material", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "matname"); - RNA_def_property_ui_text(prop, "Material", "Only look for objects with this material (blank = all objects)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_x_ray", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", SENS_RAY_XRAY); - RNA_def_property_ui_text(prop, "X-Ray", "Toggle X-Ray option (see through objects that don't have the property)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -static void rna_def_keyboard_sensor(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - srna = RNA_def_struct(brna, "KeyboardSensor", "Sensor"); - RNA_def_struct_ui_text(srna, "Keyboard Sensor", "Sensor to detect keyboard events"); - RNA_def_struct_sdna_from(srna, "bKeyboardSensor", "data"); - - prop = RNA_def_property(srna, "key", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "key"); - RNA_def_property_enum_items(prop, rna_enum_event_type_items); - RNA_def_property_translation_context(prop, BLT_I18NCONTEXT_UI_EVENTS); - RNA_def_property_enum_funcs(prop, NULL, "rna_Sensor_keyboard_key_set", NULL); - RNA_def_property_ui_text(prop, "Key", ""); - RNA_def_property_translation_context(prop, BLT_I18NCONTEXT_ID_WINDOWMANAGER); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "modifier_key_1", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "qual"); - RNA_def_property_enum_items(prop, rna_enum_event_type_items); - RNA_def_property_translation_context(prop, BLT_I18NCONTEXT_UI_EVENTS); - RNA_def_property_enum_funcs(prop, NULL, "rna_Sensor_keyboard_modifier_set", NULL); - RNA_def_property_ui_text(prop, "Modifier Key", "Modifier key code"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "modifier_key_2", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "qual2"); - RNA_def_property_enum_items(prop, rna_enum_event_type_items); - RNA_def_property_translation_context(prop, BLT_I18NCONTEXT_UI_EVENTS); - RNA_def_property_enum_funcs(prop, NULL, "rna_Sensor_keyboard_modifier2_set", NULL); - RNA_def_property_ui_text(prop, "Second Modifier Key", "Modifier key code"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "target", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "targetName"); - RNA_def_property_ui_text(prop, "Target", "Property that receives the keystrokes in case a string is logged"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "log", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "toggleName"); - RNA_def_property_ui_text(prop, "Log Toggle", "Property that indicates whether to log keystrokes as a string"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_all_keys", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "type", 1); - RNA_def_property_ui_text(prop, "All Keys", "Trigger this sensor on any keystroke"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -static void rna_def_property_sensor(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - static const EnumPropertyItem prop_type_items[] = { - {SENS_PROP_EQUAL, "PROPEQUAL", 0, "Equal", ""}, - {SENS_PROP_NEQUAL, "PROPNEQUAL", 0, "Not Equal", ""}, - {SENS_PROP_INTERVAL, "PROPINTERVAL", 0, "Interval", ""}, - {SENS_PROP_CHANGED, "PROPCHANGED", 0, "Changed", ""}, - /* {SENS_PROP_EXPRESSION, "PROPEXPRESSION", 0, "Expression", ""}, NOT_USED_IN_UI */ - {SENS_PROP_LESSTHAN, "PROPLESSTHAN", 0, "Less Than", ""}, - {SENS_PROP_GREATERTHAN, "PROPGREATERTHAN", 0, "Greater Than", ""}, - {0, NULL, 0, NULL, NULL} - }; - - srna = RNA_def_struct(brna, "PropertySensor", "Sensor"); - RNA_def_struct_ui_text(srna, "Property Sensor", "Sensor to detect values and changes in values of properties"); - RNA_def_struct_sdna_from(srna, "bPropertySensor", "data"); - - prop = RNA_def_property(srna, "evaluation_type", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "type"); - RNA_def_property_enum_items(prop, prop_type_items); - RNA_def_property_ui_text(prop, "Evaluation Type", "Type of property evaluation"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "property", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "name"); - RNA_def_property_ui_text(prop, "Property", ""); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "value", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "value"); - RNA_def_property_ui_text(prop, "Value", "Check for this value in types in Equal, Not Equal, Less Than and Greater Than types"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "value_min", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "value"); - RNA_def_property_ui_text(prop, "Minimum Value", "Minimum value in Interval type"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "value_max", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "maxvalue"); - RNA_def_property_ui_text(prop, "Maximum Value", "Maximum value in Interval type"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -static void rna_def_armature_sensor(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - static const EnumPropertyItem prop_type_items[] = { - {SENS_ARM_STATE_CHANGED, "STATECHG", 0, "State Changed", ""}, - {SENS_ARM_LIN_ERROR_BELOW, "LINERRORBELOW", 0, "Lin error below", ""}, - {SENS_ARM_LIN_ERROR_ABOVE, "LINERRORABOVE", 0, "Lin error above", ""}, - {SENS_ARM_ROT_ERROR_BELOW, "ROTERRORBELOW", 0, "Rot error below", ""}, - {SENS_ARM_ROT_ERROR_ABOVE, "ROTERRORABOVE", 0, "Rot error above", ""}, - {0, NULL, 0, NULL, NULL} - }; - - srna = RNA_def_struct(brna, "ArmatureSensor", "Sensor"); - RNA_def_struct_ui_text(srna, "Armature Sensor", "Sensor to detect values and changes in values of IK solver"); - RNA_def_struct_sdna_from(srna, "bArmatureSensor", "data"); - - prop = RNA_def_property(srna, "test_type", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "type"); - RNA_def_property_enum_items(prop, prop_type_items); - RNA_def_property_ui_text(prop, "Test", "Type of value and test"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "bone", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "posechannel"); - RNA_def_property_ui_text(prop, "Bone Name", "Identify the bone to check value from"); - RNA_def_property_update(prop, NC_LOGIC, "rna_Sensor_Armature_update"); - - prop = RNA_def_property(srna, "constraint", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "constraint"); - RNA_def_property_ui_text(prop, "Constraint Name", "Identify the bone constraint to check value from"); - RNA_def_property_update(prop, NC_LOGIC, "rna_Sensor_Armature_update"); - - prop = RNA_def_property(srna, "value", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "value"); - RNA_def_property_ui_text(prop, "Compare Value", "Value to be used in comparison"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -static void rna_def_actuator_sensor(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - srna = RNA_def_struct(brna, "ActuatorSensor", "Sensor"); - RNA_def_struct_ui_text(srna, "Actuator Sensor", "Sensor to detect state modifications of actuators"); - RNA_def_struct_sdna_from(srna, "bActuatorSensor", "data"); - - /* XXX if eventually have Logics using RNA 100%, we could use the actuator data-block isntead of its name */ - prop = RNA_def_property(srna, "actuator", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "name"); - RNA_def_property_ui_text(prop, "Actuator", "Actuator name, actuator active state modifications will be detected"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -static void rna_def_delay_sensor(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - srna = RNA_def_struct(brna, "DelaySensor", "Sensor"); - RNA_def_struct_ui_text(srna, "Delay Sensor", "Sensor to send delayed events"); - RNA_def_struct_sdna_from(srna, "bDelaySensor", "data"); - - prop = RNA_def_property(srna, "delay", PROP_INT, PROP_NONE); - RNA_def_property_ui_text(prop, "Delay", - "Delay in number of logic tics before the positive trigger (default 60 per second)"); - RNA_def_property_range(prop, 0, 5000); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "duration", PROP_INT, PROP_NONE); - RNA_def_property_ui_text(prop, "Duration", - "If >0, delay in number of logic tics before the negative trigger following " - "the positive trigger"); - RNA_def_property_range(prop, 0, 5000); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_repeat", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", SENS_DELAY_REPEAT); - RNA_def_property_ui_text(prop, "Repeat", - "Toggle repeat option (if selected, the sensor restarts after Delay+Duration " - "logic tics)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -static void rna_def_collision_sensor(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - srna = RNA_def_struct(brna, "CollisionSensor", "Sensor"); - RNA_def_struct_ui_text(srna, "Collision Sensor", - "Sensor to detect objects colliding with the current object, with more settings than " - "the Touch sensor"); - RNA_def_struct_sdna_from(srna, "bCollisionSensor", "data"); - - prop = RNA_def_property(srna, "use_pulse", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "mode", SENS_COLLISION_PULSE); - RNA_def_property_ui_text(prop, "Pulse", "Change to the set of colliding objects generates pulse"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_material", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "mode", SENS_COLLISION_MATERIAL); - RNA_def_property_ui_text(prop, "M/P", "Toggle collision on material or property"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "property", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "name"); - RNA_def_property_ui_text(prop, "Property", "Only look for objects with this property (blank = all objects)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /*XXX to make a setFunction to create a lookup with all materials in Blend File (not only this object mat.) */ - prop = RNA_def_property(srna, "material", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "materialName"); - RNA_def_property_ui_text(prop, "Material", "Only look for objects with this material (blank = all objects)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - -#if 0 - /* XXX either use a data-block look up to store the string name (material) - * or to do a doversion and use a material pointer. */ - prop = RNA_def_property(srna, "material", PROP_POINTER, PROP_NONE); - RNA_def_property_struct_type(prop, "Material"); - RNA_def_property_flag(prop, PROP_EDITABLE); - RNA_def_property_pointer_sdna(prop, NULL, "ma"); - RNA_def_property_ui_text(prop, "Material", "Only look for objects with this material (blank = all objects)"); -#endif -} - -static void rna_def_radar_sensor(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - static const EnumPropertyItem axis_items[] = { - {SENS_RADAR_X_AXIS, "XAXIS", 0, "+X axis", ""}, - {SENS_RADAR_Y_AXIS, "YAXIS", 0, "+Y axis", ""}, - {SENS_RADAR_Z_AXIS, "ZAXIS", 0, "+Z axis", ""}, - {SENS_RADAR_NEG_X_AXIS, "NEGXAXIS", 0, "-X axis", ""}, - {SENS_RADAR_NEG_Y_AXIS, "NEGYAXIS", 0, "-Y axis", ""}, - {SENS_RADAR_NEG_Z_AXIS, "NEGZAXIS", 0, "-Z axis", ""}, - {0, NULL, 0, NULL, NULL} - }; - - srna = RNA_def_struct(brna, "RadarSensor", "Sensor"); - RNA_def_struct_ui_text(srna, "Radar Sensor", - "Sensor to detect objects in a cone shaped radar emanating from the current object"); - RNA_def_struct_sdna_from(srna, "bRadarSensor", "data"); - - prop = RNA_def_property(srna, "property", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "name"); - RNA_def_property_ui_text(prop, "Property", "Only look for objects with this property (blank = all objects)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "axis", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_items(prop, axis_items); - RNA_def_property_ui_text(prop, "Axis", "Along which axis the radar cone is cast"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "angle", PROP_FLOAT, PROP_ANGLE); - RNA_def_property_range(prop, 0.0, DEG2RADF(179.9f)); - RNA_def_property_ui_text(prop, "Angle", "Opening angle of the radar cone"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "distance", PROP_FLOAT, PROP_NONE); - RNA_def_property_float_sdna(prop, NULL, "range"); - RNA_def_property_range(prop, 0.0, 10000.0); - RNA_def_property_ui_text(prop, "Distance", "Depth of the radar cone"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -static void rna_def_random_sensor(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - srna = RNA_def_struct(brna, "RandomSensor", "Sensor"); - RNA_def_struct_ui_text(srna, "Random Sensor", "Sensor to send random events"); - RNA_def_struct_sdna_from(srna, "bRandomSensor", "data"); - - prop = RNA_def_property(srna, "seed", PROP_INT, PROP_NONE); - RNA_def_property_range(prop, 0, 1000); - RNA_def_property_ui_text(prop, "Seed", "Initial seed of the generator (choose 0 for not random)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -static void rna_def_ray_sensor(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - static const EnumPropertyItem axis_items[] = { - {SENS_RAY_X_AXIS, "XAXIS", 0, "+X axis", ""}, - {SENS_RAY_Y_AXIS, "YAXIS", 0, "+Y axis", ""}, - {SENS_RAY_Z_AXIS, "ZAXIS", 0, "+Z axis", ""}, - {SENS_RAY_NEG_X_AXIS, "NEGXAXIS", 0, "-X axis", ""}, - {SENS_RAY_NEG_Y_AXIS, "NEGYAXIS", 0, "-Y axis", ""}, - {SENS_RAY_NEG_Z_AXIS, "NEGZAXIS", 0, "-Z axis", ""}, - {0, NULL, 0, NULL, NULL} - }; - - static const EnumPropertyItem prop_ray_type_items[] = { - {SENS_COLLISION_PROPERTY, "PROPERTY", ICON_LOGIC, "Property", "Use a property for ray intersections"}, - {SENS_COLLISION_MATERIAL, "MATERIAL", ICON_MATERIAL_DATA, "Material", "Use a material for ray intersections"}, - {0, NULL, 0, NULL, NULL} - }; - - srna = RNA_def_struct(brna, "RaySensor", "Sensor"); - RNA_def_struct_ui_text(srna, "Ray Sensor", - "Sensor to detect intersections with a ray emanating from the current object"); - RNA_def_struct_sdna_from(srna, "bRaySensor", "data"); - - prop = RNA_def_property(srna, "ray_type", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_bitflag_sdna(prop, NULL, "mode"); - RNA_def_property_enum_items(prop, prop_ray_type_items); - RNA_def_property_ui_text(prop, "Ray Type", "Toggle collision on material or property"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "property", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "propname"); - RNA_def_property_ui_text(prop, "Property", "Only look for objects with this property (blank = all objects)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "material", PROP_STRING, PROP_NONE); - RNA_def_property_string_sdna(prop, NULL, "matname"); - RNA_def_property_ui_text(prop, "Material", "Only look for objects with this material (blank = all objects)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - -#if 0 - /* XXX either use a data-block look up to store the string name (material) - * or to do a doversion and use a material pointer. */ - prop = RNA_def_property(srna, "material", PROP_POINTER, PROP_NONE); - RNA_def_property_struct_type(prop, "Material"); - RNA_def_property_flag(prop, PROP_EDITABLE); - RNA_def_property_pointer_sdna(prop, NULL, "ma"); - RNA_def_property_ui_text(prop, "Material", "Only look for objects with this material (blank = all objects)"); -#endif - - prop = RNA_def_property(srna, "use_x_ray", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "mode", SENS_RAY_XRAY); - RNA_def_property_ui_text(prop, "X-Ray Mode", - "Toggle X-Ray option (see through objects that don't have the property)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "range", PROP_FLOAT, PROP_NONE); - RNA_def_property_range(prop, 0.01, 10000.0); - RNA_def_property_ui_text(prop, "Range", "Sense objects no farther than this distance"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "axis", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "axisflag"); - RNA_def_property_enum_items(prop, axis_items); - RNA_def_property_ui_text(prop, "Axis", "Along which axis the ray is cast"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -static void rna_def_message_sensor(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - srna = RNA_def_struct(brna, "MessageSensor", "Sensor"); - RNA_def_struct_ui_text(srna, "Message Sensor", "Sensor to detect incoming messages"); - RNA_def_struct_sdna_from(srna, "bMessageSensor", "data"); - - prop = RNA_def_property(srna, "subject", PROP_STRING, PROP_NONE); - RNA_def_property_ui_text(prop, "Subject", - "Optional subject filter: only accept messages with this subject, " - "or empty to accept all"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -static void rna_def_joystick_sensor(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - static const EnumPropertyItem event_type_joystick_items[] = { - {SENS_JOY_BUTTON, "BUTTON", 0, "Button", ""}, - {SENS_JOY_AXIS, "AXIS", 0, "Axis", ""}, - {SENS_JOY_HAT, "HAT", 0, "Hat", ""}, - {SENS_JOY_AXIS_SINGLE, "AXIS_SINGLE", 0, "Single Axis", ""}, - {0, NULL, 0, NULL, NULL} - }; - - static const EnumPropertyItem axis_direction_items[] = { - {SENS_JOY_X_AXIS, "RIGHTAXIS", 0, "Right Axis", ""}, - {SENS_JOY_Y_AXIS, "UPAXIS", 0, "Up Axis", ""}, - {SENS_JOY_NEG_X_AXIS, "LEFTAXIS", 0, "Left Axis", ""}, - {SENS_JOY_NEG_Y_AXIS, "DOWNAXIS", 0, "Down Axis", ""}, - {0, NULL, 0, NULL, NULL} - }; - - static const EnumPropertyItem hat_direction_items[] = { - {SENS_JOY_HAT_UP, "UP", 0, "Up", ""}, - {SENS_JOY_HAT_DOWN, "DOWN", 0, "Down", ""}, - {SENS_JOY_HAT_LEFT, "LEFT", 0, "Left", ""}, - {SENS_JOY_HAT_RIGHT, "RIGHT", 0, "Right", ""}, - - {SENS_JOY_HAT_UP_RIGHT, "UPRIGHT", 0, "Up/Right", ""}, - {SENS_JOY_HAT_DOWN_LEFT, "DOWNLEFT", 0, "Down/Left", ""}, - {SENS_JOY_HAT_UP_LEFT, "UPLEFT", 0, "Up/Left", ""}, - {SENS_JOY_HAT_DOWN_RIGHT, "DOWNRIGHT", 0, "Down/Right", ""}, - {0, NULL, 0, NULL, NULL} - }; - - srna = RNA_def_struct(brna, "JoystickSensor", "Sensor"); - RNA_def_struct_ui_text(srna, "Joystick Sensor", "Sensor to detect joystick events"); - RNA_def_struct_sdna_from(srna, "bJoystickSensor", "data"); - - prop = RNA_def_property(srna, "joystick_index", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "joyindex"); - RNA_def_property_ui_text(prop, "Index", "Which joystick to use"); - RNA_def_property_range(prop, 0, SENS_JOY_MAXINDEX - 1); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "event_type", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "type"); - RNA_def_property_enum_items(prop, event_type_joystick_items); - RNA_def_property_translation_context(prop, BLT_I18NCONTEXT_UI_EVENTS); - RNA_def_property_ui_text(prop, "Event Type", "The type of event this joystick sensor is triggered on"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "use_all_events", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "flag", SENS_JOY_ANY_EVENT); - RNA_def_property_ui_text(prop, "All Events", - "Triggered by all events on this joystick's current type (axis/button/hat)"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* Button */ - prop = RNA_def_property(srna, "button_number", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "button"); - RNA_def_property_ui_text(prop, "Button Number", "Which button to use"); - RNA_def_property_range(prop, 0, 18); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* Axis */ - prop = RNA_def_property(srna, "axis_number", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "axis"); - RNA_def_property_ui_text(prop, "Axis Number", "Which axis pair to use, 1 is usually the main direction input"); - RNA_def_property_range(prop, 1, 8); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "axis_threshold", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "precision"); - RNA_def_property_ui_text(prop, "Axis Threshold", "Precision of the axis"); - RNA_def_property_range(prop, 0, 32768); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "axis_direction", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "axisf"); - RNA_def_property_enum_items(prop, axis_direction_items); - RNA_def_property_ui_text(prop, "Axis Direction", "The direction of the axis"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* Single Axis */ - prop = RNA_def_property(srna, "single_axis_number", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "axis_single"); - RNA_def_property_ui_text(prop, "Axis Number", "Single axis (vertical/horizontal/other) to detect"); - RNA_def_property_range(prop, 1, 16); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* Hat */ - prop = RNA_def_property(srna, "hat_number", PROP_INT, PROP_NONE); - RNA_def_property_int_sdna(prop, NULL, "hat"); - RNA_def_property_ui_text(prop, "Hat Number", "Which hat to use"); - RNA_def_property_range(prop, 1, 2); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "hat_direction", PROP_ENUM, PROP_NONE); - RNA_def_property_enum_sdna(prop, NULL, "hatf"); - RNA_def_property_enum_items(prop, hat_direction_items); - RNA_def_property_ui_text(prop, "Hat Direction", "Hat direction"); - RNA_def_property_update(prop, NC_LOGIC, NULL); -} - -void RNA_def_sensor(BlenderRNA *brna) -{ - rna_def_sensor(brna); - - rna_def_always_sensor(brna); - rna_def_near_sensor(brna); - rna_def_mouse_sensor(brna); - rna_def_keyboard_sensor(brna); - rna_def_property_sensor(brna); - rna_def_armature_sensor(brna); - rna_def_actuator_sensor(brna); - rna_def_delay_sensor(brna); - rna_def_collision_sensor(brna); - rna_def_radar_sensor(brna); - rna_def_random_sensor(brna); - rna_def_ray_sensor(brna); - rna_def_message_sensor(brna); - rna_def_joystick_sensor(brna); -} - -#endif diff --git a/source/blender/makesrna/intern/rna_sensor_api.c b/source/blender/makesrna/intern/rna_sensor_api.c deleted file mode 100644 index b0c4109b1df..00000000000 --- a/source/blender/makesrna/intern/rna_sensor_api.c +++ /dev/null @@ -1,79 +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) 2010 Blender Foundation. - * All rights reserved. - * - * - * Contributor(s): - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file blender/makesrna/intern/rna_sensor_api.c - * \ingroup RNA - */ - -#include -#include - -#include "BLI_utildefines.h" - -#include "RNA_define.h" - -#include "rna_internal.h" /* own include */ - -#include "WM_types.h" - -#ifdef RNA_RUNTIME - -#include "BKE_sca.h" -#include "DNA_sensor_types.h" -#include "DNA_controller_types.h" - -static void rna_Sensor_link(bSensor *sens, bController *cont) -{ - link_logicbricks((void **)&cont, (void ***)&(sens->links), &sens->totlinks, sizeof(bController *)); -} - -static void rna_Sensor_unlink(bSensor *sens, bController *cont) -{ - unlink_logicbricks((void **)&cont, (void ***)&(sens->links), &sens->totlinks); -} - -#else - -void RNA_api_sensor(StructRNA *srna) -{ - FunctionRNA *func; - PropertyRNA *parm; - - func = RNA_def_function(srna, "link", "rna_Sensor_link"); - RNA_def_function_ui_description(func, "Link the sensor to a controller"); - parm = RNA_def_pointer(func, "controller", "Controller", "", "Controller to link to"); - RNA_def_parameter_flags(parm, 0, PARM_REQUIRED); - RNA_def_property_update(parm, NC_LOGIC, NULL); - - func = RNA_def_function(srna, "unlink", "rna_Sensor_unlink"); - RNA_def_function_ui_description(func, "Unlink the sensor from a controller"); - parm = RNA_def_pointer(func, "controller", "Controller", "", "Controller to unlink from"); - RNA_def_parameter_flags(parm, 0, PARM_REQUIRED); - RNA_def_property_update(parm, NC_LOGIC, NULL); -} - -#endif - diff --git a/source/blender/makesrna/intern/rna_sound.c b/source/blender/makesrna/intern/rna_sound.c index 6aacede5816..0c1391fd2f7 100644 --- a/source/blender/makesrna/intern/rna_sound.c +++ b/source/blender/makesrna/intern/rna_sound.c @@ -32,7 +32,6 @@ #include "rna_internal.h" #include "DNA_sound_types.h" -#include "DNA_property_types.h" #ifdef RNA_RUNTIME diff --git a/source/blender/makesrna/intern/rna_space.c b/source/blender/makesrna/intern/rna_space.c index a12b4553486..1252091f84b 100644 --- a/source/blender/makesrna/intern/rna_space.c +++ b/source/blender/makesrna/intern/rna_space.c @@ -83,7 +83,6 @@ const EnumPropertyItem rna_enum_space_type_items[] = { /* Scripting */ {0, "", ICON_NONE, "Scripting", ""}, {SPACE_TEXT, "TEXT_EDITOR", ICON_TEXT, "Text Editor", "Edit scripts and in-file documentation"}, - {SPACE_LOGIC, "LOGIC_EDITOR", ICON_LOGIC, "Logic Editor", "Game logic editing"}, {SPACE_CONSOLE, "CONSOLE", ICON_CONSOLE, "Python Console", "Interactive programmatic console for " "advanced editing and script development"}, {SPACE_INFO, "INFO", ICON_INFO, "Info", "Main menu bar and list of error messages " @@ -329,8 +328,6 @@ static StructRNA *rna_Space_refine(struct PointerRNA *ptr) return &RNA_SpaceTimeline; case SPACE_NODE: return &RNA_SpaceNodeEditor; - case SPACE_LOGIC: - return &RNA_SpaceLogicEditor; case SPACE_CONSOLE: return &RNA_SpaceConsole; case SPACE_USERPREF: @@ -4350,75 +4347,6 @@ static void rna_def_space_node(BlenderRNA *brna) RNA_api_space_node(srna); } -static void rna_def_space_logic(BlenderRNA *brna) -{ - StructRNA *srna; - PropertyRNA *prop; - - srna = RNA_def_struct(brna, "SpaceLogicEditor", "Space"); - RNA_def_struct_sdna(srna, "SpaceLogic"); - RNA_def_struct_ui_text(srna, "Space Logic Editor", "Logic editor space data"); - - /* sensors */ - prop = RNA_def_property(srna, "show_sensors_selected_objects", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "scaflag", BUTS_SENS_SEL); - RNA_def_property_ui_text(prop, "Show Selected Object", "Show sensors of all selected objects"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "show_sensors_active_object", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "scaflag", BUTS_SENS_ACT); - RNA_def_property_ui_text(prop, "Show Active Object", "Show sensors of active object"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "show_sensors_linked_controller", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "scaflag", BUTS_SENS_LINK); - RNA_def_property_ui_text(prop, "Show Linked to Controller", "Show linked objects to the controller"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "show_sensors_active_states", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "scaflag", BUTS_SENS_STATE); - RNA_def_property_ui_text(prop, "Show Active States", "Show only sensors connected to active states"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* controllers */ - prop = RNA_def_property(srna, "show_controllers_selected_objects", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "scaflag", BUTS_CONT_SEL); - RNA_def_property_ui_text(prop, "Show Selected Object", "Show controllers of all selected objects"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "show_controllers_active_object", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "scaflag", BUTS_CONT_ACT); - RNA_def_property_ui_text(prop, "Show Active Object", "Show controllers of active object"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "show_controllers_linked_controller", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "scaflag", BUTS_CONT_LINK); - RNA_def_property_ui_text(prop, "Show Linked to Controller", "Show linked objects to sensor/actuator"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - /* actuators */ - prop = RNA_def_property(srna, "show_actuators_selected_objects", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "scaflag", BUTS_ACT_SEL); - RNA_def_property_ui_text(prop, "Show Selected Object", "Show actuators of all selected objects"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "show_actuators_active_object", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "scaflag", BUTS_ACT_ACT); - RNA_def_property_ui_text(prop, "Show Active Object", "Show actuators of active object"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "show_actuators_linked_controller", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "scaflag", BUTS_ACT_LINK); - RNA_def_property_ui_text(prop, "Show Linked to Actuator", "Show linked objects to the actuator"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - - prop = RNA_def_property(srna, "show_actuators_active_states", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_sdna(prop, NULL, "scaflag", BUTS_ACT_STATE); - RNA_def_property_ui_text(prop, "Show Active States", "Show only actuators connected to active states"); - RNA_def_property_update(prop, NC_LOGIC, NULL); - -} - static void rna_def_space_clip(BlenderRNA *brna) { StructRNA *srna; @@ -4703,7 +4631,6 @@ void RNA_def_space(BlenderRNA *brna) rna_def_space_userpref(brna); rna_def_node_tree_path(brna); rna_def_space_node(brna); - rna_def_space_logic(brna); rna_def_space_clip(brna); } diff --git a/source/blender/makesrna/intern/rna_userdef.c b/source/blender/makesrna/intern/rna_userdef.c index 88330ad2a8f..fe69b91e833 100644 --- a/source/blender/makesrna/intern/rna_userdef.c +++ b/source/blender/makesrna/intern/rna_userdef.c @@ -204,12 +204,6 @@ static void rna_userdef_load_ui_update(Main *UNUSED(bmain), Scene *UNUSED(scene) else G.fileflags &= ~G_FILE_NO_UI; } -static void rna_userdef_mipmap_update(Main *bmain, Scene *scene, PointerRNA *ptr) -{ - GPU_set_mipmap(!(U.gameflags & USER_DISABLE_MIPMAP)); - rna_userdef_update(bmain, scene, ptr); -} - static void rna_userdef_anisotropic_update(Main *bmain, Scene *scene, PointerRNA *ptr) { GPU_set_anisotropic(U.anisotropic_filter); @@ -2282,23 +2276,6 @@ static void rna_def_userdef_theme_space_node(BlenderRNA *brna) RNA_def_property_update(prop, 0, "rna_userdef_update"); } -static void rna_def_userdef_theme_space_logic(BlenderRNA *brna) -{ - StructRNA *srna; -// PropertyRNA *prop; - - /* space_logic */ - - srna = RNA_def_struct(brna, "ThemeLogicEditor", NULL); - RNA_def_struct_sdna(srna, "ThemeSpace"); - RNA_def_struct_clear_flag(srna, STRUCT_UNDO); - RNA_def_struct_ui_text(srna, "Theme Logic Editor", "Theme settings for the Logic Editor"); - - rna_def_userdef_theme_spaces_main(srna); - -} - - static void rna_def_userdef_theme_space_buts(BlenderRNA *brna) { StructRNA *srna; @@ -3002,7 +2979,6 @@ static void rna_def_userdef_themes(BlenderRNA *brna) {7, "SEQUENCE_EDITOR", ICON_SEQUENCE, "Video Sequence Editor", ""}, {8, "TEXT_EDITOR", ICON_TEXT, "Text Editor", ""}, {9, "NODE_EDITOR", ICON_NODETREE, "Node Editor", ""}, - {10, "LOGIC_EDITOR", ICON_LOGIC, "Logic Editor", ""}, {11, "PROPERTIES", ICON_BUTS, "Properties", ""}, {12, "OUTLINER", ICON_OOPS, "Outliner", ""}, {14, "USER_PREFERENCES", ICON_PREFERENCES, "User Preferences", ""}, @@ -3102,12 +3078,6 @@ static void rna_def_userdef_themes(BlenderRNA *brna) RNA_def_property_struct_type(prop, "ThemeNodeEditor"); RNA_def_property_ui_text(prop, "Node Editor", ""); - prop = RNA_def_property(srna, "logic_editor", PROP_POINTER, PROP_NONE); - RNA_def_property_flag(prop, PROP_NEVER_NULL); - RNA_def_property_pointer_sdna(prop, NULL, "tlogic"); - RNA_def_property_struct_type(prop, "ThemeLogicEditor"); - RNA_def_property_ui_text(prop, "Logic Editor", ""); - prop = RNA_def_property(srna, "outliner", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_pointer_sdna(prop, NULL, "toops"); @@ -3232,7 +3202,6 @@ static void rna_def_userdef_dothemes(BlenderRNA *brna) rna_def_userdef_theme_space_info(brna); rna_def_userdef_theme_space_userpref(brna); rna_def_userdef_theme_space_console(brna); - rna_def_userdef_theme_space_logic(brna); rna_def_userdef_theme_space_clip(brna); rna_def_userdef_theme_colorset(brna); rna_def_userdef_themes(brna); @@ -4116,13 +4085,6 @@ static void rna_def_userdef_system(BlenderRNA *brna) RNA_def_property_range(prop, 0.0f, 1.0f); RNA_def_property_ui_text(prop, "Clip Alpha", "Clip alpha below this threshold in the 3D textured view"); RNA_def_property_update(prop, 0, "rna_userdef_update"); - - prop = RNA_def_property(srna, "use_mipmaps", PROP_BOOLEAN, PROP_NONE); - RNA_def_property_boolean_negative_sdna(prop, NULL, "gameflags", USER_DISABLE_MIPMAP); - RNA_def_property_ui_text(prop, "Mipmaps", - "Scale textures for the 3D View (looks nicer but uses more memory and slows image " - "reloading)"); - RNA_def_property_update(prop, 0, "rna_userdef_mipmap_update"); prop = RNA_def_property(srna, "use_16bit_textures", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "use_16bit_textures", 1); diff --git a/source/blender/nodes/shader/node_shader_tree.c b/source/blender/nodes/shader/node_shader_tree.c index fd30df4293e..c90be35b648 100644 --- a/source/blender/nodes/shader/node_shader_tree.c +++ b/source/blender/nodes/shader/node_shader_tree.c @@ -75,7 +75,6 @@ static int shader_tree_poll(const bContext *C, bNodeTreeType *UNUSED(treetype)) /* allow empty engine string too, this is from older versions that didn't have registerable engines yet */ return (engine_id[0] == '\0' || STREQ(engine_id, RE_engine_id_BLENDER_RENDER) || - STREQ(engine_id, RE_engine_id_BLENDER_GAME) || STREQ(engine_id, RE_engine_id_CYCLES) || !BKE_viewrender_use_shading_nodes_custom(view_render)); } diff --git a/source/blender/python/generic/bpy_internal_import.c b/source/blender/python/generic/bpy_internal_import.c index ffac09efdde..750d0c20301 100644 --- a/source/blender/python/generic/bpy_internal_import.c +++ b/source/blender/python/generic/bpy_internal_import.c @@ -116,16 +116,6 @@ void bpy_import_main_set(struct Main *maggie) bpy_import_main = maggie; } -void bpy_import_main_extra_add(struct Main *maggie) -{ - BLI_addhead(&bpy_import_main_list, maggie); -} - -void bpy_import_main_extra_remove(struct Main *maggie) -{ - BLI_remlink_safe(&bpy_import_main_list, maggie); -} - /* returns a dummy filename for a textblock so we can tell what file a text block comes from */ void bpy_text_filename_get(char *fn, size_t fn_len, Text *text) { diff --git a/source/blender/python/generic/bpy_internal_import.h b/source/blender/python/generic/bpy_internal_import.h index 905e045d657..f11571fb933 100644 --- a/source/blender/python/generic/bpy_internal_import.h +++ b/source/blender/python/generic/bpy_internal_import.h @@ -51,12 +51,7 @@ PyObject *bpy_text_reimport(PyObject *module, int *found); void bpy_text_filename_get(char *fn, size_t fn_len, struct Text *text); -/* The game engine has its own Main struct, if this is set search this rather than G.main */ struct Main *bpy_import_main_get(void); void bpy_import_main_set(struct Main *maggie); -/* This is used for importing text from dynamically loaded libraries in the game engine */ -void bpy_import_main_extra_add(struct Main *maggie); -void bpy_import_main_extra_remove(struct Main *maggie); - #endif /* __BPY_INTERNAL_IMPORT_H__ */ diff --git a/source/blender/python/generic/py_capi_utils.h b/source/blender/python/generic/py_capi_utils.h index fe7a046d99c..9f3c10bfd67 100644 --- a/source/blender/python/generic/py_capi_utils.h +++ b/source/blender/python/generic/py_capi_utils.h @@ -76,7 +76,7 @@ PyObject * PyC_UnicodeFromByteAndSize(const char *str, Py_ssize_t size); const char * PyC_UnicodeAsByte(PyObject *py_str, PyObject **coerce); /* coerce must be NULL */ const char * PyC_UnicodeAsByteAndSize(PyObject *py_str, Py_ssize_t *size, PyObject **coerce); -/* name namespace function for bpy & bge */ +/* name namespace function for bpy */ PyObject * PyC_DefaultNameSpace(const char *filename); void PyC_RunQuicky(const char *filepath, int n, ...); diff --git a/source/blender/python/intern/CMakeLists.txt b/source/blender/python/intern/CMakeLists.txt index f9098529772..b745563508a 100644 --- a/source/blender/python/intern/CMakeLists.txt +++ b/source/blender/python/intern/CMakeLists.txt @@ -180,10 +180,6 @@ if(WITH_FREESTYLE) add_definitions(-DWITH_FREESTYLE) endif() -if(WITH_GAMEENGINE) - add_definitions(-DWITH_GAMEENGINE) -endif() - if(WITH_IMAGE_CINEON) add_definitions(-DWITH_CINEON) endif() @@ -306,10 +302,6 @@ if(WITH_OPENSUBDIV) ) endif() -if(WITH_PLAYER) - add_definitions(-DWITH_PLAYER) -endif() - add_definitions(${GL_DEFINITIONS}) blender_add_lib(bf_python "${SRC}" "${INC}" "${INC_SYS}") diff --git a/source/blender/python/intern/bpy_app_build_options.c b/source/blender/python/intern/bpy_app_build_options.c index d5c325e4317..6e3f8da31f9 100644 --- a/source/blender/python/intern/bpy_app_build_options.c +++ b/source/blender/python/intern/bpy_app_build_options.c @@ -42,7 +42,6 @@ static PyStructSequence_Field app_builtopts_info_fields[] = { {(char *)"cycles", NULL}, {(char *)"cycles_osl", NULL}, {(char *)"freestyle", NULL}, - {(char *)"gameengine", NULL}, {(char *)"image_cineon", NULL}, {(char *)"image_dds", NULL}, {(char *)"image_frameserver", NULL}, @@ -64,7 +63,6 @@ static PyStructSequence_Field app_builtopts_info_fields[] = { {(char *)"mod_smoke", NULL}, {(char *)"collada", NULL}, {(char *)"opencolorio", NULL}, - {(char *)"player", NULL}, {(char *)"openmp", NULL}, {(char *)"openvdb", NULL}, {(char *)"alembic", NULL}, @@ -140,12 +138,6 @@ static PyObject *make_builtopts_info(void) SetObjIncref(Py_False); #endif -#ifdef WITH_GAMEENGINE - SetObjIncref(Py_True); -#else - SetObjIncref(Py_False); -#endif - #ifdef WITH_CINEON SetObjIncref(Py_True); #else @@ -272,12 +264,6 @@ static PyObject *make_builtopts_info(void) SetObjIncref(Py_False); #endif -#ifdef WITH_PLAYER - SetObjIncref(Py_True); -#else - SetObjIncref(Py_False); -#endif - #ifdef _OPENMP SetObjIncref(Py_True); #else diff --git a/source/blender/python/intern/bpy_app_handlers.c b/source/blender/python/intern/bpy_app_handlers.c index 5a309339e17..948a78d5794 100644 --- a/source/blender/python/intern/bpy_app_handlers.c +++ b/source/blender/python/intern/bpy_app_handlers.c @@ -59,8 +59,6 @@ static PyStructSequence_Field app_cb_info_fields[] = { {(char *)"load_post", (char *)"on loading a new blend file (after)"}, {(char *)"save_pre", (char *)"on saving a blend file (before)"}, {(char *)"save_post", (char *)"on saving a blend file (after)"}, - {(char *)"game_pre", (char *)"on starting the game engine"}, - {(char *)"game_post", (char *)"on ending the game engine"}, {(char *)"version_update", (char *)"on ending the versioning code"}, /* sets the permanent tag */ diff --git a/source/blender/python/intern/bpy_rna_callback.c b/source/blender/python/intern/bpy_rna_callback.c index 01a25137a98..0e2efe152c3 100644 --- a/source/blender/python/intern/bpy_rna_callback.c +++ b/source/blender/python/intern/bpy_rna_callback.c @@ -170,7 +170,6 @@ static eSpace_Type rna_Space_refine_reverse(StructRNA *srna) if (srna == &RNA_SpaceNLA) return SPACE_NLA; if (srna == &RNA_SpaceTimeline) return SPACE_TIME; if (srna == &RNA_SpaceNodeEditor) return SPACE_NODE; - if (srna == &RNA_SpaceLogicEditor) return SPACE_LOGIC; if (srna == &RNA_SpaceConsole) return SPACE_CONSOLE; if (srna == &RNA_SpaceUserPreferences) return SPACE_USERPREF; if (srna == &RNA_SpaceClipEditor) return SPACE_CLIP; diff --git a/source/blender/python/mathutils/mathutils.h b/source/blender/python/mathutils/mathutils.h index ec927a9e316..01d2350d7fd 100644 --- a/source/blender/python/mathutils/mathutils.h +++ b/source/blender/python/mathutils/mathutils.h @@ -62,7 +62,7 @@ enum { float *_data; /* array of data (alias), wrapped status depends on wrapped status */ \ PyObject *cb_user; /* if this vector references another object, otherwise NULL, \ * *Note* this owns its reference */ \ - unsigned char cb_type; /* which user funcs do we adhere to, RNA, GameObject, etc */ \ + unsigned char cb_type; /* which user funcs do we adhere to, RNA, etc */ \ unsigned char cb_subtype; /* subtype: location, rotation... \ * to avoid defining many new functions for every attribute of the same type */ \ unsigned char flag /* wrapped data type? */ \ diff --git a/source/blender/render/CMakeLists.txt b/source/blender/render/CMakeLists.txt index 5cbc907d9c6..c5042bf3f83 100644 --- a/source/blender/render/CMakeLists.txt +++ b/source/blender/render/CMakeLists.txt @@ -149,10 +149,6 @@ if(WITH_FREESTYLE) add_definitions(-DWITH_FREESTYLE) endif() -if(WITH_GAMEENGINE) - add_definitions(-DWITH_GAMEENGINE) -endif() - if(WITH_INTERNATIONAL) add_definitions(-DWITH_INTERNATIONAL) endif() diff --git a/source/blender/render/extern/include/RE_engine.h b/source/blender/render/extern/include/RE_engine.h index 8e9d005df9c..64d87876a2e 100644 --- a/source/blender/render/extern/include/RE_engine.h +++ b/source/blender/render/extern/include/RE_engine.h @@ -60,7 +60,7 @@ struct ViewLayer; /* RenderEngineType.flag */ #define RE_INTERNAL 1 -#define RE_GAME 2 +/* #define RE_FLAG_DEPRECATED 2 */ #define RE_USE_PREVIEW 4 #define RE_USE_POSTPROCESS 8 #define RE_USE_SHADING_NODES 16 diff --git a/source/blender/render/intern/source/external_engine.c b/source/blender/render/intern/source/external_engine.c index 245a49ad5ae..824d37b360f 100644 --- a/source/blender/render/intern/source/external_engine.c +++ b/source/blender/render/intern/source/external_engine.c @@ -80,25 +80,11 @@ static RenderEngineType internal_render_type = { {NULL, NULL, NULL} }; -#ifdef WITH_GAMEENGINE - -static RenderEngineType internal_game_type = { - NULL, NULL, - "BLENDER_GAME", N_("Blender Game"), RE_INTERNAL | RE_GAME | RE_USE_LEGACY_PIPELINE, - NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - {NULL, NULL, NULL} -}; - -#endif - ListBase R_engines = {NULL, NULL}; void RE_engines_init(void) { RE_engines_register(NULL, &internal_render_type); -#ifdef WITH_GAMEENGINE - RE_engines_register(NULL, &internal_game_type); -#endif DRW_engines_register(); } diff --git a/source/blender/render/intern/source/pipeline.c b/source/blender/render/intern/source/pipeline.c index c42f85ef017..8bc6f025d11 100644 --- a/source/blender/render/intern/source/pipeline.c +++ b/source/blender/render/intern/source/pipeline.c @@ -670,9 +670,7 @@ static int check_mode_full_sample(RenderData *rd, ViewRender *view_render) const char *engine_id = view_render->engine_id; int scemode = rd->scemode; - if (!STREQ(engine_id, RE_engine_id_BLENDER_RENDER) && - !STREQ(engine_id, RE_engine_id_BLENDER_GAME)) - { + if (!STREQ(engine_id, RE_engine_id_BLENDER_RENDER)) { scemode &= ~R_FULL_SAMPLE; } diff --git a/source/blender/windowmanager/CMakeLists.txt b/source/blender/windowmanager/CMakeLists.txt index da61a201ef6..d74cf15d78b 100644 --- a/source/blender/windowmanager/CMakeLists.txt +++ b/source/blender/windowmanager/CMakeLists.txt @@ -42,7 +42,6 @@ set(INC ../makesrna ../nodes ../render/extern/include - ../../gameengine/BlenderRoutines ../../../intern/clog ../../../intern/ghost ../../../intern/guardedalloc @@ -143,10 +142,6 @@ if(WITH_PYTHON) add_definitions(-DWITH_PYTHON) endif() -if(WITH_GAMEENGINE) - add_definitions(-DWITH_GAMEENGINE) -endif() - if(WITH_BUILDINFO) add_definitions(-DWITH_BUILDINFO) endif() diff --git a/source/blender/windowmanager/WM_api.h b/source/blender/windowmanager/WM_api.h index 377d274a712..7869973f1ec 100644 --- a/source/blender/windowmanager/WM_api.h +++ b/source/blender/windowmanager/WM_api.h @@ -91,7 +91,6 @@ void WM_exit (struct bContext *C) ATTR_NORETURN; void WM_main (struct bContext *C) ATTR_NORETURN; -bool WM_init_game (struct bContext *C); void WM_init_splash (struct bContext *C); diff --git a/source/blender/windowmanager/intern/wm_files.c b/source/blender/windowmanager/intern/wm_files.c index 9dcb83244ca..ef8888c9f87 100644 --- a/source/blender/windowmanager/intern/wm_files.c +++ b/source/blender/windowmanager/intern/wm_files.c @@ -881,8 +881,6 @@ int wm_homefile_read( /* start with save preference untitled.blend */ G.save_over = 0; - /* disable auto-play in startup.blend... */ - G.fileflags &= ~G_FILE_AUTOPLAY; wm_file_read_post(C, true, use_userdef); @@ -1192,7 +1190,6 @@ static int wm_file_write(bContext *C, const char *filepath, int fileflags, Repor } SET_FLAG_FROM_TEST(G.fileflags, fileflags & G_FILE_COMPRESS, G_FILE_COMPRESS); - SET_FLAG_FROM_TEST(G.fileflags, fileflags & G_FILE_AUTOPLAY, G_FILE_AUTOPLAY); /* prevent background mode scripts from clobbering history */ if (do_history) { @@ -1300,7 +1297,7 @@ void wm_autosave_timer(const bContext *C, wmWindowManager *wm, wmTimer *UNUSED(w } else { /* save as regular blend file */ - int fileflags = G.fileflags & ~(G_FILE_COMPRESS | G_FILE_AUTOPLAY | G_FILE_HISTORY); + int fileflags = G.fileflags & ~(G_FILE_COMPRESS | G_FILE_HISTORY); ED_editors_flush_edits(C, false); @@ -1427,7 +1424,7 @@ static int wm_homefile_write_exec(bContext *C, wmOperator *op) ED_editors_flush_edits(C, false); /* force save as regular blend file */ - fileflags = G.fileflags & ~(G_FILE_COMPRESS | G_FILE_AUTOPLAY | G_FILE_HISTORY); + fileflags = G.fileflags & ~(G_FILE_COMPRESS | G_FILE_HISTORY); if (BLO_write_file(CTX_data_main(C), filepath, fileflags | G_FILE_USERPREFS, op->reports, NULL) == 0) { printf("fail\n"); diff --git a/source/blender/windowmanager/intern/wm_init_exit.c b/source/blender/windowmanager/intern/wm_init_exit.c index 4c7c2cc96e4..2af478b9470 100644 --- a/source/blender/windowmanager/intern/wm_init_exit.c +++ b/source/blender/windowmanager/intern/wm_init_exit.c @@ -86,9 +86,6 @@ #include "BPY_extern.h" #endif -#ifdef WITH_GAMEENGINE -# include "BL_System.h" -#endif #include "GHOST_Path-api.h" #include "GHOST_C-api.h" @@ -193,7 +190,7 @@ void WM_init(bContext *C, int argc, const char **argv) ED_file_init(); /* for fsmenu */ ED_node_init_butfuncs(); - BLF_init(); /* Please update source/gamengine/GamePlayer/GPG_ghost.cpp if you change this */ + BLF_init(); BLT_lang_init(); /* reports cant be initialized before the wm, @@ -218,7 +215,7 @@ void WM_init(bContext *C, int argc, const char **argv) GPU_init(); - GPU_set_mipmap(!(U.gameflags & USER_DISABLE_MIPMAP)); + GPU_set_mipmap(true); GPU_set_linear_mipmap(true); GPU_set_anisotropic(U.anisotropic_filter); GPU_set_gpu_mipmapping(U.use_gpu_mipmap); @@ -324,96 +321,6 @@ void WM_init_splash(bContext *C) } } -bool WM_init_game(bContext *C) -{ - wmWindowManager *wm = CTX_wm_manager(C); - wmWindow *win; - - ScrArea *sa; - ARegion *ar = NULL; - - Scene *scene = CTX_data_scene(C); - - if (!scene) { - /* XXX, this should not be needed. */ - Main *bmain = CTX_data_main(C); - scene = bmain->scene.first; - } - - win = wm->windows.first; - - /* first to get a valid window */ - if (win) - CTX_wm_window_set(C, win); - - sa = BKE_screen_find_big_area(CTX_wm_screen(C), SPACE_VIEW3D, 0); - ar = BKE_area_find_region_type(sa, RGN_TYPE_WINDOW); - - /* if we have a valid 3D view */ - if (sa && ar) { - ARegion *arhide; - - CTX_wm_area_set(C, sa); - CTX_wm_region_set(C, ar); - - /* disable quad view */ - if (ar->alignment == RGN_ALIGN_QSPLIT) - WM_operator_name_call(C, "SCREEN_OT_region_quadview", WM_OP_EXEC_DEFAULT, NULL); - - /* toolbox, properties panel and header are hidden */ - for (arhide = sa->regionbase.first; arhide; arhide = arhide->next) { - if (arhide->regiontype != RGN_TYPE_WINDOW) { - if (!(arhide->flag & RGN_FLAG_HIDDEN)) { - ED_region_toggle_hidden(C, arhide); - } - } - } - - /* full screen the area */ - if (!sa->full) { - ED_screen_state_toggle(C, win, sa, SCREENMAXIMIZED); - } - - /* Fullscreen */ - if ((scene->gm.playerflag & GAME_PLAYER_FULLSCREEN)) { - WM_operator_name_call(C, "WM_OT_window_fullscreen_toggle", WM_OP_EXEC_DEFAULT, NULL); - wm_get_screensize(&ar->winrct.xmax, &ar->winrct.ymax); - ar->winx = ar->winrct.xmax + 1; - ar->winy = ar->winrct.ymax + 1; - } - else { - GHOST_RectangleHandle rect = GHOST_GetClientBounds(win->ghostwin); - ar->winrct.ymax = GHOST_GetHeightRectangle(rect); - ar->winrct.xmax = GHOST_GetWidthRectangle(rect); - ar->winx = ar->winrct.xmax + 1; - ar->winy = ar->winrct.ymax + 1; - GHOST_DisposeRectangle(rect); - } - - WM_operator_name_call(C, "VIEW3D_OT_game_start", WM_OP_EXEC_DEFAULT, NULL); - - BKE_sound_exit(); - - return true; - } - else { - ReportTimerInfo *rti; - - BKE_report(&wm->reports, RPT_ERROR, "No valid 3D View found, game auto start is not possible"); - - /* After adding the report to the global list, reset the report timer. */ - WM_event_remove_timer(wm, NULL, wm->reports.reporttimer); - - /* Records time since last report was added */ - wm->reports.reporttimer = WM_event_add_timer(wm, CTX_wm_window(C), TIMER, 0.02); - - rti = MEM_callocN(sizeof(ReportTimerInfo), "ReportTimerInfo"); - wm->reports.reporttimer->customdata = rti; - - return false; - } -} - /* free strings of open recent files */ static void free_openrecent(void) { @@ -491,7 +398,7 @@ void WM_exit_ext(bContext *C, const bool do_python) /* save the undo state as quit.blend */ char filename[FILE_MAX]; bool has_edited; - int fileflags = G.fileflags & ~(G_FILE_COMPRESS | G_FILE_AUTOPLAY | G_FILE_HISTORY); + int fileflags = G.fileflags & ~(G_FILE_COMPRESS | G_FILE_HISTORY); BLI_make_file_string("/", filename, BKE_tempdir_base(), BLENDER_QUIT_FILE); @@ -625,9 +532,6 @@ void WM_exit_ext(bContext *C, const bool do_python) wm_ghost_exit(); CTX_free(C); -#ifdef WITH_GAMEENGINE - SYS_DeleteSystem(SYS_GetSystem()); -#endif GHOST_DisposeSystemPaths(); diff --git a/source/blenderplayer/CMakeLists.txt b/source/blenderplayer/CMakeLists.txt deleted file mode 100644 index 60abf0806d3..00000000000 --- a/source/blenderplayer/CMakeLists.txt +++ /dev/null @@ -1,274 +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 ***** - -# message(STATUS "Configuring blenderplayer") - -setup_libdirs() - -if(WIN32 AND NOT UNIX) - string(SUBSTRING ${BLENDER_VERSION} 0 1 bver1) - string(SUBSTRING ${BLENDER_VERSION} 2 1 bver2) - string(SUBSTRING ${BLENDER_VERSION} 3 1 bver3) - add_definitions( - -DBLEN_VER_RC_STR=${BLENDER_VERSION} - -DBLEN_VER_RC_1=${bver1} - -DBLEN_VER_RC_2=${bver2} - -DBLEN_VER_RC_3=${bver3} - -DBLEN_VER_RC_4=0 - ) - - add_executable( - blenderplayer ${EXETYPE} - bad_level_call_stubs/stubs.c - ${CMAKE_SOURCE_DIR}/release/windows/icons/winblender.rc) - WINDOWS_SIGN_TARGET(blenderplayer) - install(TARGETS blenderplayer - COMPONENT Blenderplayer - DESTINATION ".") - -add_cc_flags_custom_test(blenderplayer) - -elseif(APPLE) - add_executable(blenderplayer ${EXETYPE} bad_level_call_stubs/stubs.c) - # setup Info.plist - execute_process(COMMAND date "+%Y-%m-%d" OUTPUT_VARIABLE BLENDER_DATE OUTPUT_STRIP_TRAILING_WHITESPACE) - set(PLAYER_SOURCEDIR ${CMAKE_SOURCE_DIR}/release/darwin/blenderplayer.app) - set(PLAYER_SOURCEINFO ${PLAYER_SOURCEDIR}/Contents/Info.plist) - set_target_properties(blenderplayer PROPERTIES - MACOSX_BUNDLE_INFO_PLIST ${PLAYER_SOURCEINFO} - MACOSX_BUNDLE_SHORT_VERSION_STRING "${BLENDER_VERSION}${BLENDER_VERSION_CHAR}" - MACOSX_BUNDLE_LONG_VERSION_STRING "${BLENDER_VERSION}${BLENDER_VERSION_CHAR} ${BLENDER_DATE}") - -else() - add_executable(blenderplayer bad_level_call_stubs/stubs.c) - - if(NOT WITH_INSTALL_PORTABLE) - install( - TARGETS blenderplayer - DESTINATION bin - ) - else() - install( - TARGETS blenderplayer - DESTINATION "." - ) - endif() -endif() - -add_dependencies(blenderplayer makesdna) - -get_property(BLENDER_LINK_LIBS GLOBAL PROPERTY BLENDER_LINK_LIBS) - -list(APPEND BLENDER_LINK_LIBS - ge_player_common - ge_player_ghost - blenkernel_blc -) - -if(WITH_AUDASPACE AND NOT WITH_SYSTEM_AUDASPACE) - list(APPEND BLENDER_LINK_LIBS - audaspace - audaspace-py) -endif() - -if(CMAKE_SYSTEM_NAME MATCHES "Linux") - list(APPEND BLENDER_LINK_LIBS extern_binreloc) -endif() - -# if(UNIX) - # Sort libraries - set(BLENDER_SORTED_LIBS - ge_player_ghost - ge_player_common - bf_intern_string - bf_intern_ghost - bf_rna - bf_blenkernel - bf_depsgraph - bf_physics - bf_intern_rigidbody - bf_blenloader - ge_blen_routines - bf_editor_datafiles - ge_converter - ge_logic_ketsji - ge_phys_bullet - ge_phys_dummy - ge_logic - ge_rasterizer - ge_oglrasterizer - ge_logic_expressions - ge_scenegraph - bf_ikplugin - bf_intern_itasc - bf_intern_iksolver - bf_intern_smoke - bf_modifiers - bf_intern_moto - bf_nodes - bf_gpu - bf_intern_gawain - bf_imbuf - bf_avi - ge_logic_network - ge_logic_ngnetwork - ge_logic_loopbacknetwork - extern_bullet - bf_intern_guardedalloc - bf_intern_memutil - bf_python_ext - bf_python_mathutils - bf_python_bmesh - bf_intern_utfconv - bf_imbuf_cineon - bf_imbuf_openexr - bf_imbuf_openimageio - extern_openjpeg - bf_imbuf_dds - bf_dna - ge_videotex - bf_blenfont - bf_blentranslation - bf_intern_audaspace - audaspace - audaspace-py - blenkernel_blc - bf_bmesh - bf_blenlib - bf_intern_utfconv - extern_binreloc - extern_minilzo - bf_intern_ghost # duplicate for linking - bf_blenkernel # duplicate for linking - bf_intern_mikktspace - extern_recastnavigation - bf_intern_opencolorio - bf_intern_glew_mx - bf_intern_eigen - extern_rangetree - extern_wcwidth - bf_intern_libmv - extern_sdlew - ) - - if(NOT WITH_SYSTEM_GLOG) - list(APPEND BLENDER_SORTED_LIBS extern_glog) - endif() - - if(NOT WITH_SYSTEM_GFLAGS) - list(APPEND BLENDER_SORTED_LIBS extern_gflags) - endif() - - if(WITH_MOD_CLOTH_ELTOPO) - list(APPEND BLENDER_SORTED_LIBS extern_eltopo) - endif() - - if(NOT WITH_SYSTEM_GLEW) - list(APPEND BLENDER_SORTED_LIBS ${BLENDER_GLEW_LIBRARIES}) - endif() - - if(WITH_LZMA) - list(APPEND BLENDER_SORTED_LIBS extern_lzma) - endif() - - if(WITH_LIBMV) - list(APPEND BLENDER_SORTED_LIBS extern_ceres) - endif() - - if(WITH_GHOST_XDND) - list(APPEND BLENDER_SORTED_LIBS extern_xdnd) - endif() - - if(WITH_CXX_GUARDEDALLOC) - list(APPEND BLENDER_SORTED_LIBS bf_intern_guardedalloc_cpp) - endif() - - if(WITH_INTERNATIONAL) - list(APPEND BLENDER_SORTED_LIBS bf_intern_locale) - endif() - - if(WITH_GAMEENGINE_DECKLINK) - list(APPEND BLENDER_SORTED_LIBS bf_intern_decklink) - endif() - - if(WIN32) - list(APPEND BLENDER_SORTED_LIBS bf_intern_gpudirect) - endif() - - if(WITH_OPENSUBDIV) - list(APPEND BLENDER_SORTED_LIBS bf_intern_opensubdiv) - endif() - - if(WITH_OPENVDB) - list(APPEND BLENDER_SORTED_LIBS bf_intern_openvdb) - endif() - - if(WITH_ALEMBIC) - list(APPEND BLENDER_SORTED_LIBS bf_alembic) - endif() - - foreach(SORTLIB ${BLENDER_SORTED_LIBS}) - set(REMLIB ${SORTLIB}) - foreach(SEARCHLIB ${BLENDER_LINK_LIBS}) - if(${SEARCHLIB} STREQUAL ${SORTLIB}) - set(REMLIB "") - endif() - endforeach() - if(REMLIB) - # message(STATUS "Removing library ${REMLIB} from blenderplayer linking because: not configured") - list(APPEND REM_MSG ${REMLIB}) - list(REMOVE_ITEM BLENDER_SORTED_LIBS ${REMLIB}) - endif() - endforeach() - if(REM_MSG) - list(SORT REM_MSG) - message(STATUS "Player Skipping: (${REM_MSG})") - endif() - target_link_libraries(blenderplayer ${BLENDER_SORTED_LIBS}) - - unset(SEARCHLIB) - unset(SORTLIB) - unset(REMLIB) - unset(REM_MSG) - -# else() -# target_link_libraries(blenderplayer ${BLENDER_LINK_LIBS}) -# endif() - -if(WITH_PLAYER) - add_subdirectory(bad_level_call_stubs) -endif() - -setup_liblinks(blenderplayer) - -# We put CLEW and CUEW here because OPENSUBDIV_LIBRARIES dpeends on them.. -if(WITH_CYCLES OR WITH_COMPOSITOR OR WITH_OPENSUBDIV) - target_link_libraries(blenderplayer "extern_clew") - if(WITH_CUDA_DYNLOAD) - target_link_libraries(blenderplayer "extern_cuew") - else() - target_link_libraries(${target} ${CUDA_CUDA_LIBRARY}) - endif() -endif() diff --git a/source/blenderplayer/bad_level_call_stubs/CMakeLists.txt b/source/blenderplayer/bad_level_call_stubs/CMakeLists.txt deleted file mode 100644 index 0a50c0876fb..00000000000 --- a/source/blenderplayer/bad_level_call_stubs/CMakeLists.txt +++ /dev/null @@ -1,79 +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 ***** - -# this warning on generated files gets annoying -remove_strict_flags() - -set(INC - . - .. - ../../blender/blenlib - ../../blender/blenkernel - ../../blender/blenloader - ../../blender/depsgraph - ../../blender/makesdna - ../../blender/makesrna - ../../../intern/glew-mx - ../../../intern/guardedalloc -) - -set(INC_SYS - ${GLEW_INCLUDE_PATH} -) - -set(SRC - stubs.c -) - -if(WITH_BUILDINFO) - list(APPEND SRC - ../../creator/buildinfo.c - ) - add_definitions(-DBUILD_DATE="\"\"" - -DBUILD_TIME="\"\"" - -DBUILD_COMMIT_TIMESTAMP=0 - -DBUILD_COMMIT_DATE="\"\"" - -DBUILD_COMMIT_TIME="\"\"" - -DBUILD_HASH="\"\"" - -DBUILD_PLATFORM="\"\"" - -DBUILD_BRANCH="\"\"" - -DBUILD_TYPE="\"\"" - ) -endif() - -if(WITH_GAMEENGINE) - add_definitions(-DWITH_GAMEENGINE) -endif() - -if(WITH_FREESTYLE) - add_definitions(-DWITH_FREESTYLE) -endif() - -if(WITH_INPUT_NDOF) - add_definitions(-DWITH_INPUT_NDOF) -endif() - -blender_add_lib_nolist(blenkernel_blc "${SRC}" "${INC}" "${INC_SYS}") diff --git a/source/blenderplayer/bad_level_call_stubs/stubs.c b/source/blenderplayer/bad_level_call_stubs/stubs.c deleted file mode 100644 index 1ab9f9fac98..00000000000 --- a/source/blenderplayer/bad_level_call_stubs/stubs.c +++ /dev/null @@ -1,871 +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 ***** - * BKE_bad_level_calls function stubs - */ - -/** \file blenderplayer/bad_level_call_stubs/stubs.c - * \ingroup blc - */ - -#ifdef WITH_GAMEENGINE - -#define ASSERT_STUBS 0 -#if ASSERT_STUBS -# include -# define STUB_ASSERT(x) (assert(x)) -#else -# define STUB_ASSERT(x) -#endif - - -struct ARegion; -struct ARegionType; -struct bFaceMap; -struct BMEditMesh; -struct Base; -struct bContext; -struct BoundBox; -struct Brush; -struct CSG_FaceIteratorDescriptor; -struct CSG_VertexIteratorDescriptor; -struct ChannelDriver; -struct ColorBand; -struct Context; -struct Curve; -struct CurveMapping; -struct DerivedMesh; -struct EditBone; -struct EnvMap; -struct FCurve; -struct Heap; -struct HeapNode; -struct ID; -struct ImBuf; -struct Image; -struct ImageUser; -struct KeyingSet; -struct KeyingSetInfo; -struct MCol; -struct MTex; -struct Main; -struct Mask; -struct Material; -struct MenuType; -struct Mesh; -struct MetaBall; -struct Lattice; -struct ModifierData; -struct MovieClip; -struct MultiresModifierData; -struct HookModifierData; -struct NodeBlurData; -struct Nurb; -struct Object; -struct PBVHNode; -struct PyObject; -struct Render; -struct RenderEngine; -struct RenderEngineType; -struct RenderLayer; -struct RenderResult; -struct Scene; -struct Scene; -struct ScrArea; -struct SculptSession; -struct ShadeInput; -struct ShadeResult; -struct SpaceButs; -struct SpaceClip; -struct SpaceImage; -struct SpaceNode; -struct Tex; -struct TexResult; -struct Text; -struct ToolSettings; -struct View2D; -struct View3D; -struct bAction; -struct bArmature; -struct bConstraint; -struct bConstraintOb; -struct bConstraintTarget; -struct bContextDataResult; -struct bGPDlayer; -struct bFaceMap; -struct bNode; -struct bNodeType; -struct bNodeSocket; -struct bNodeSocketType; -struct bNodeTree; -struct bNodeTreeType; -struct bPoseChannel; -struct bPythonConstraint; -struct bTheme; -struct uiLayout; -struct wmEvent; -struct wmKeyConfig; -struct wmKeyMap; -struct wmOperator; -struct wmOperatorType; -struct wmWindow; -struct wmWindowManager; -struct wmManipulatorGroupType; -struct wmManipulatorMap; - - -/* -------------------------------------------------------------------- */ -/* Declarations */ - -/* may cause troubles... enable for now so args match for certain */ -#if 1 -#if defined(__GNUC__) -# pragma GCC diagnostic error "-Wmissing-prototypes" -# pragma GCC diagnostic ignored "-Wunused-parameter" -#endif - -#include /* FILE */ - -#include "../../intern/dualcon/dualcon.h" -#include "../../intern/elbeem/extern/elbeem.h" -#include "../blender/blenkernel/BKE_modifier.h" -#include "../blender/blenkernel/BKE_paint.h" -#include "../blender/compositor/COM_compositor.h" -#include "../blender/editors/include/ED_armature.h" -#include "../blender/editors/include/ED_anim_api.h" -#include "../blender/editors/include/ED_buttons.h" -#include "../blender/editors/include/ED_clip.h" -#include "../blender/editors/include/ED_curve.h" -#include "../blender/editors/include/ED_fileselect.h" -#include "../blender/editors/include/ED_gpencil.h" -#include "../blender/editors/include/ED_image.h" -#include "../blender/editors/include/ED_info.h" -#include "../blender/editors/include/ED_keyframes_edit.h" -#include "../blender/editors/include/ED_keyframing.h" -#include "../blender/editors/include/ED_lattice.h" -#include "../blender/editors/include/ED_manipulator_library.h" -#include "../blender/editors/include/ED_mball.h" -#include "../blender/editors/include/ED_mesh.h" -#include "../blender/editors/include/ED_node.h" -#include "../blender/editors/include/ED_object.h" -#include "../blender/editors/include/ED_particle.h" -#include "../blender/editors/include/ED_render.h" -#include "../blender/editors/include/ED_scene.h" -#include "../blender/editors/include/ED_screen.h" -#include "../blender/editors/include/ED_space_api.h" -#include "../blender/editors/include/ED_text.h" -#include "../blender/editors/include/ED_transform.h" -#include "../blender/editors/include/ED_transform_snap_object_context.h" -#include "../blender/editors/include/ED_uvedit.h" -#include "../blender/editors/include/ED_view3d.h" -#include "../blender/editors/include/UI_interface.h" -#include "../blender/editors/include/UI_interface_icons.h" -#include "../blender/editors/include/UI_resources.h" -#include "../blender/editors/include/UI_view2d.h" -#include "../blender/freestyle/FRS_freestyle.h" -#include "../blender/gpu/GPU_immediate.h" -#include "../blender/gpu/GPU_matrix.h" -#include "../blender/python/BPY_extern.h" -#include "../blender/python/intern/bpy_manipulator_wrap.h" -#include "../blender/render/extern/include/RE_engine.h" -#include "../blender/render/extern/include/RE_pipeline.h" -#include "../blender/render/extern/include/RE_render_ext.h" -#include "../blender/render/extern/include/RE_shader_ext.h" -#include "../blender/draw/DRW_engine.h" -#include "../blender/windowmanager/WM_api.h" -#include "../blender/windowmanager/WM_types.h" -#include "../blender/windowmanager/WM_message.h" - - -/* -------------------------------------------------------------------- */ -/* Externs - * (ideally we wouldn't have _any_ but we can't include all directly) - */ - -/* bpy_operator_wrap.h */ -extern void macro_wrapper(struct wmOperatorType *ot, void *userdata); -extern void operator_wrapper(struct wmManipulatorGroupType *wgt, void *userdata); - -/* bpy_widgetgroup_wrap.h */ -extern void widgetgroup_wrapper(struct wmOperatorType *ot, void *userdata); - -/* bpy_rna.h */ -extern bool pyrna_id_FromPyObject(struct PyObject *obj, struct ID **id); -extern const char *BPY_app_translations_py_pgettext(const char *msgctxt, const char *msgid); -extern const char *BPY_app_translations_py_pgettext(const char *msgctxt, const char *msgid); -extern struct PyObject *pyrna_id_CreatePyObject(struct ID *id); -extern bool pyrna_id_CheckPyObject(struct PyObject *obj); -/* bpy_interface.c */ -bool BPY_string_is_keyword(const char *str) { return false; } - -#endif -/* end declarations */ - - -/* -------------------------------------------------------------------- */ -/* Return Macro's */ - -#include /* memset */ -#define RET_NULL {STUB_ASSERT(0); return (void *) NULL;} -#define RET_ZERO {STUB_ASSERT(0); return 0;} -#define RET_MINUSONE {STUB_ASSERT(0); return -1;} -#define RET_STRUCT(t) {struct t v; STUB_ASSERT(0); memset(&v, 0, sizeof(v)); return v;} -#define RET_ARG(arg) {STUB_ASSERT(0); return arg; } -#define RET_NONE {STUB_ASSERT(0);} - -/* -------------------------------------------------------------------- */ -/* Stubs */ - -void DRW_deferred_shader_remove(struct GPUMaterial *mat) RET_NONE - -/*new render funcs */ -void EDBM_selectmode_set(struct BMEditMesh *em) RET_NONE -void EDBM_mesh_load(struct Object *ob) RET_NONE -void EDBM_mesh_make(struct Object *ob, const int select_mode, const bool use_key_index) RET_NONE -void EDBM_mesh_normals_update(struct BMEditMesh *em) RET_NONE -void *g_system; -bool EDBM_uv_check(struct BMEditMesh *em) RET_ZERO - -float *RE_RenderLayerGetPass(volatile struct RenderLayer *rl, const char *name, const char *viewname) RET_NULL -float RE_filter_value(int type, float x) RET_ZERO -struct RenderLayer *RE_GetRenderLayer(struct RenderResult *rr, const char *name) RET_NULL -void RE_texture_rng_init() RET_NONE -void RE_texture_rng_exit() RET_NONE - -bool RE_layers_have_name(struct RenderResult *result) RET_ZERO -const char *RE_engine_active_view_get(struct RenderEngine *engine) RET_NULL -void RE_engine_active_view_set(struct RenderEngine *engine, const char *viewname) RET_NONE -void RE_engine_get_camera_model_matrix(struct RenderEngine *engine, struct Object *camera, int use_spherical_stereo, float *r_modelmat) RET_NONE -float RE_engine_get_camera_shift_x(struct RenderEngine *engine, struct Object *camera, int use_spherical_stereo) RET_ZERO -int RE_engine_get_spherical_stereo(struct RenderEngine *engine, struct Object *camera) RET_ZERO -void RE_SetActiveRenderView(struct Render *re, const char *viewname) RET_NONE - -struct RenderPass *RE_pass_find_by_name(volatile struct RenderLayer *rl, const char *name, const char *viewname) RET_NULL -struct RenderPass *RE_pass_find_by_type(volatile struct RenderLayer *rl, int passtype, const char *viewname) RET_NULL -bool RE_HasCombinedLayer(RenderResult *res) RET_ZERO - -/* imagetexture.c stub */ -void ibuf_sample(struct ImBuf *ibuf, float fx, float fy, float dx, float dy, float *result) RET_NONE - -/* Freestyle */ -bool ED_texture_context_check_linestyle(const struct bContext *C) RET_ZERO -void FRS_free_view_map_cache(void) RET_NONE - -/* texture.c */ -int multitex_ext(struct Tex *tex, float texvec[3], float dxt[3], float dyt[3], int osatex, struct TexResult *texres, const short thread, struct ImagePool *pool, bool scene_color_manage, const bool skip_load_image) RET_ZERO -int multitex_ext_safe(struct Tex *tex, float texvec[3], struct TexResult *texres, struct ImagePool *pool, bool scene_color_manage, const bool skip_load_image) RET_ZERO -int multitex_nodes(struct Tex *tex, float texvec[3], float dxt[3], float dyt[3], int osatex, struct TexResult *texres, const short thread, short which_output, struct ShadeInput *shi, struct MTex *mtex, struct ImagePool *pool) RET_ZERO - -struct Material *RE_sample_material_init(struct Depsgraph *depsgraph, struct Material *orig_mat, struct Scene *scene) RET_NULL -void RE_sample_material_free(struct Material *mat) RET_NONE -void RE_sample_material_color( - struct Material *mat, float color[3], float *alpha, const float volume_co[3], const float surface_co[3], - int tri_index, struct DerivedMesh *orcoDm, struct Object *ob) RET_NONE -/* nodes */ -struct Render *RE_GetRender(const char *name) RET_NULL -struct Render *RE_GetSceneRender(const struct Scene *scene) RET_NULL -struct Object *RE_GetCamera(struct Render *re) RET_NULL -float RE_lamp_get_data(struct ShadeInput *shi, struct Object *lamp_obj, float col[4], float lv[3], float *dist, float shadow[4]) RET_ZERO -const float (*RE_object_instance_get_matrix(struct ObjectInstanceRen *obi, int matrix_id))[4] RET_NULL -const float (*RE_render_current_get_matrix(int matrix_id))[4] RET_NULL -float RE_object_instance_get_object_pass_index(struct ObjectInstanceRen *obi) RET_ZERO -float RE_object_instance_get_random_id(struct ObjectInstanceRen *obi) RET_ZERO - -/* blenkernel */ -bool BKE_paint_proj_mesh_data_check(struct Scene *scene, struct Object *ob, bool *uvs, bool *mat, bool *tex, bool *stencil) RET_ZERO - -/* render */ -void RE_FreeRenderResult(struct RenderResult *res) RET_NONE -void RE_FreeAllRenderResults(void) RET_NONE -struct RenderResult *RE_MultilayerConvert(void *exrhandle, const char *colorspace, bool predivide, int rectx, int recty) RET_NULL -struct Scene *RE_GetScene(struct Render *re) RET_NULL -void RE_Database_Free(struct Render *re) RET_NONE -void RE_FreeRender(struct Render *re) RET_NONE -void RE_DataBase_GetView(struct Render *re, float mat[4][4]) RET_NONE -int externtex( - const struct MTex *mtex, const float vec[3], float *tin, float *tr, float *tg, float *tb, float *ta, - const int thread, struct ImagePool *pool, const bool skip_load_image, const bool texnode_preview) RET_ZERO -float texture_value_blend(float tex, float out, float fact, float facg, int blendtype) RET_ZERO -void texture_rgb_blend(float in[3], const float tex[3], const float out[3], float fact, float facg, int blendtype) RET_NONE -double elbeemEstimateMemreq(int res, float sx, float sy, float sz, int refine, char *retstr) RET_ZERO -struct Render *RE_NewRender(const char *name) RET_NULL -struct Render *RE_NewSceneRender(const struct Scene *scene) RET_NULL -void RE_SwapResult(struct Render *re, struct RenderResult **rr) RET_NONE -void RE_BlenderFrame(struct Render *re, struct Main *bmain, struct Scene *scene, struct ViewLayer *view_layer, struct Object *camera_override, unsigned int lay_override, int frame, const bool write_still) RET_NONE -bool RE_WriteEnvmapResult(struct ReportList *reports, struct Scene *scene, struct EnvMap *env, const char *relpath, const char imtype, float layout[12]) RET_ZERO - -/* rna */ -float *ED_view3d_cursor3d_get(struct Scene *scene, struct View3D *v3d) RET_NULL -void WM_menutype_free(void) RET_NONE -void WM_menutype_freelink(struct MenuType *mt) RET_NONE -bool WM_menutype_add(struct MenuType *mt) RET_ZERO -int WM_operator_props_dialog_popup(struct bContext *C, struct wmOperator *op, int width, int height) RET_ZERO -int WM_operator_confirm(struct bContext *C, struct wmOperator *op, const struct wmEvent *event) RET_ZERO -struct MenuType *WM_menutype_find(const char *idname, bool quiet) RET_NULL -void WM_operator_stack_clear(struct wmWindowManager *wm) RET_NONE -void WM_operator_handlers_clear(wmWindowManager *wm, struct wmOperatorType *ot) RET_NONE -bool WM_operator_is_repeat(const struct bContext *C, const struct wmOperator *op) RET_ZERO; -void WM_windows_scene_data_sync(const struct ListBase *win_lb, struct Scene *scene) RET_NONE -struct Scene *WM_windows_scene_get_from_screen(const struct wmWindowManager *wm, const struct bScreen *screen) RET_NULL -struct WorkSpace *WM_windows_workspace_get_from_screen(const struct wmWindowManager *wm, const struct bScreen *screen) RET_NULL -struct bScreen *WM_window_get_active_screen(const struct wmWindow *win) RET_NULL -struct Scene *WM_window_get_active_scene(const struct wmWindow *win) RET_NULL -struct WorkSpace *WM_window_get_active_workspace(const wmWindow *win) RET_NULL - -struct ViewLayer *WM_window_get_active_view_layer_ex(const struct wmWindow *win, struct Scene **r_scene) RET_NULL -struct ViewLayer *WM_window_get_active_view_layer(const struct wmWindow *win) RET_NULL - -void WM_window_change_active_scene(struct Main *bmain, struct bContext *C, struct wmWindow *win, struct Scene *scene_new) RET_NONE -bool WM_window_is_temp_screen(const struct wmWindow *win) RET_ZERO - -void WM_autosave_init(wmWindowManager *wm) RET_NONE -void WM_jobs_kill_all_except(struct wmWindowManager *wm, void *owner) RET_NONE - -void WM_lib_reload(struct Library *lib, struct bContext *C, struct ReportList *reports) RET_NONE - -void WM_msg_publish_rna(struct wmMsgBus *mbus, PointerRNA *ptr, PropertyRNA *prop) RET_NONE - - -char *WM_clipboard_text_get(bool selection, int *r_len) RET_NULL -char *WM_clipboard_text_get_firstline(bool selection, int *r_len) RET_NULL -void WM_clipboard_text_set(const char *buf, bool selection) RET_NONE - -void WM_cursor_set(struct wmWindow *win, int curor) RET_NONE -void WM_cursor_modal_set(struct wmWindow *win, int curor) RET_NONE -void WM_cursor_modal_restore(struct wmWindow *win) RET_NONE -void WM_cursor_time(struct wmWindow *win, int nr) RET_NONE -void WM_cursor_warp(struct wmWindow *win, int x, int y) RET_NONE - -struct wmJob *WM_jobs_get(struct wmWindowManager *wm, struct wmWindow *win, void *owner, const char *name, int flag, int job_type) RET_NULL -void WM_jobs_customdata_set(struct wmJob *job, void *customdata, void (*free)(void *)) RET_NONE -void WM_jobs_timer(struct wmJob *job, double timestep, unsigned int note, unsigned int endnote) RET_NONE - -void WM_jobs_callbacks(struct wmJob *job, - void (*startjob)(void *, short *, short *, float *), - void (*initjob)(void *), - void (*update)(void *), - void (*endjob)(void *)) RET_NONE - -void WM_jobs_start(struct wmWindowManager *wm, struct wmJob *job) RET_NONE -void WM_report(ReportType type, const char *message) RET_NONE - -void BPY_RNA_manipulatorgroup_wrapper(struct wmManipulatorGroupType *wgt, void *userdata) RET_NONE -void BPY_RNA_manipulator_wrapper(struct wmManipulatorType *wgt, void *userdata) RET_NONE - -struct PointerRNA *WM_manipulator_operator_set(struct wmManipulator *mpr, int part_index, struct wmOperatorType *ot, struct IDProperty *properties) RET_NULL -const struct wmManipulatorPropertyType *WM_manipulatortype_target_property_find(const struct wmManipulatorType *wt, const char *idname) RET_NULL -const struct wmManipulatorType *WM_manipulatortype_find(const char *idname, bool quiet) RET_NULL -struct wmManipulator *WM_manipulator_new_ptr(const struct wmManipulatorType *wt, struct wmManipulatorGroup *mgroup, struct PointerRNA *properties) RET_NULL -struct wmManipulatorGroupType *WM_manipulatorgrouptype_append_ptr(void (*mnpfunc)(struct wmManipulatorGroupType *, void *), void *userdata) RET_NULL -struct wmManipulatorGroupType *WM_manipulatorgrouptype_find(const char *idname, bool quiet) RET_NULL -void WM_manipulator_unlink(ListBase *manipulatorlist, struct wmManipulatorMap *mmap, struct wmManipulator *mpr, struct bContext *C) RET_NONE -void WM_manipulator_group_type_add_ptr(struct wmManipulatorGroupType *wgt) RET_NONE -void WM_manipulator_group_type_add_ptr_ex(struct wmManipulatorGroupType *wgt, struct wmManipulatorMapType *mmap_type) RET_NONE -void WM_manipulator_group_type_remove_ptr(struct Main *bmain, struct wmManipulatorGroupType *wgt) RET_NONE -void WM_manipulator_name_set(struct wmManipulatorGroup *mgroup, struct wmManipulator *mpr, const char *name) RET_NONE -bool WM_manipulator_select_set(struct wmManipulatorMap *mmap, struct wmManipulator *mpr, bool select) RET_ZERO -void WM_manipulator_target_property_def_rna_ptr(struct wmManipulator *mpr, const struct wmManipulatorPropertyType *mpr_prop_type, struct PointerRNA *ptr, struct PropertyRNA *prop, int index) RET_NONE -void WM_manipulatorgrouptype_free_ptr(struct wmManipulatorGroupType *wt) RET_NONE -void WM_manipulatormaptype_group_unlink(struct bContext *C, struct Main *bmain, struct wmManipulatorMapType *mmap_type, const struct wmManipulatorGroupType *wgt) RET_NONE -void WM_manipulatortype_append_ptr(void (*mnpfunc)(struct wmManipulatorType *, void *), void *userdata) RET_NONE -void WM_manipulatortype_remove_ptr(struct bContext *C, struct Main *bmain, struct wmManipulatorType *wt) RET_NONE - -void ED_manipulator_draw_preset_box(const struct wmManipulator *mpr, float mat[4][4], int select_id) RET_NONE -void ED_manipulator_draw_preset_arrow(const struct wmManipulator *mpr, float mat[4][4], int axis, int select_id) RET_NONE -void ED_manipulator_draw_preset_circle(const struct wmManipulator *mpr, float mat[4][4], int axis, int select_id) RET_NONE -void ED_manipulator_draw_preset_facemap(const struct bContext *C, const struct wmManipulator *mpr, struct Scene *scene, struct Object *ob, const int facemap, int select_id) RET_NONE - -struct wmManipulatorMapType *WM_manipulatormaptype_find(const struct wmManipulatorMapType_Params *wmap_params) RET_NULL -struct wmManipulatorMapType *WM_manipulatormaptype_ensure(const struct wmManipulatorMapType_Params *wmap_params) RET_NULL -struct wmManipulatorMap *WM_manipulatormap_new_from_type(const struct wmManipulatorMapType_Params *wmap_params) RET_NULL -void WM_manipulatormaptype_group_init_runtime( - const struct Main *bmain, struct wmManipulatorMapType *mmap_type, struct wmManipulatorGroupType *wgt) RET_NONE -const struct ListBase *WM_manipulatormap_group_list(struct wmManipulatorMap *mmap) RET_NULL -void WM_manipulator_calc_matrix_final(const struct wmManipulator *mpr, float r_mat[4][4]) RET_NONE -struct wmManipulatorProperty *WM_manipulator_target_property_find(struct wmManipulator *mpr, const char *idname) RET_NULL -bool WM_manipulator_target_property_is_valid(const struct wmManipulatorProperty *mpr_prop) RET_ZERO - -#ifdef WITH_INPUT_NDOF - void WM_ndof_deadzone_set(float deadzone) RET_NONE -#endif - -void WM_uilisttype_init(void) RET_NONE -struct uiListType *WM_uilisttype_find(const char *idname, bool quiet) RET_NULL -bool WM_uilisttype_add(struct uiListType *ult) RET_ZERO -void WM_uilisttype_freelink(struct uiListType *ult) RET_NONE -void WM_uilisttype_free(void) RET_NONE - -struct wmKeyMapItem *WM_keymap_item_find_id(struct wmKeyMap *keymap, int id) RET_NULL -int WM_enum_search_invoke(struct bContext *C, struct wmOperator *op, const struct wmEvent *event) RET_ZERO -void WM_event_add_notifier(const struct bContext *C, unsigned int type, void *reference) RET_NONE -void WM_main_add_notifier(unsigned int type, void *reference) RET_NONE -void ED_armature_bone_rename(struct bArmature *arm, const char *oldnamep, const char *newnamep) RET_NONE -void ED_armature_transform(struct bArmature *arm, float mat[4][4], const bool do_props) RET_NONE -struct wmEventHandler *WM_event_add_modal_handler(struct bContext *C, struct wmOperator *op) RET_NULL -struct wmTimer *WM_event_add_timer(struct wmWindowManager *wm, struct wmWindow *win, int event_type, double timestep) RET_NULL -void WM_event_remove_timer(struct wmWindowManager *wm, struct wmWindow *win, struct wmTimer *timer) RET_NONE -float WM_event_tablet_data(const struct wmEvent *event, int *pen_flip, float tilt[2]) RET_ZERO -bool WM_event_is_tablet(const struct wmEvent *event) RET_ZERO -void ED_armature_ebone_remove(struct bArmature *arm, struct EditBone *exBone) RET_NONE -void object_test_constraints(struct Object *owner) RET_NONE -void ED_armature_ebone_to_mat4(struct EditBone *ebone, float mat[4][4]) RET_NONE -void ED_armature_ebone_from_mat4(EditBone *ebone, float mat[4][4]) RET_NONE -void ED_object_parent(struct Object *ob, struct Object *par, const int type, const char *substr) RET_NONE -void ED_object_constraint_set_active(struct Object *ob, struct bConstraint *con) RET_NONE -void ED_object_facemap_face_add(struct Object *ob, struct bFaceMap *fmap, int facenum) RET_NONE -void ED_object_facemap_face_remove(struct Object *ob, struct bFaceMap *fmap, int facenum) RET_NONE -void ED_node_composit_default(const struct bContext *C, struct Scene *scene) RET_NONE -void *ED_region_draw_cb_activate(struct ARegionType *art, void(*draw)(const struct bContext *, struct ARegion *, void *), void *custumdata, int type) RET_ZERO /* XXX this one looks weird */ -void *ED_region_draw_cb_customdata(void *handle) RET_ZERO /* XXX This one looks wrong also */ -void ED_region_draw_cb_exit(struct ARegionType *art, void *handle) RET_NONE -void ED_area_headerprint(struct ScrArea *sa, const char *str) RET_NONE -void ED_gpencil_parent_location(struct bGPDlayer *gpl, float diff_mat[4][4]) RET_NONE -void UI_view2d_region_to_view(struct View2D *v2d, float x, float y, float *viewx, float *viewy) RET_NONE -bool UI_view2d_view_to_region_clip(struct View2D *v2d, float x, float y, int *regionx, int *regiony) RET_ZERO -void UI_view2d_view_to_region(struct View2D *v2d, float x, float y, int *regionx, int *region_y) RET_NONE -void UI_view2d_sync(struct bScreen *screen, struct ScrArea *sa, struct View2D *v2dcur, int flag) RET_NONE - -struct EditBone *ED_armature_ebone_get_mirrored(const struct ListBase *edbo, EditBone *ebo) RET_NULL -struct EditBone *ED_armature_ebone_add(struct bArmature *arm, const char *name) RET_NULL -struct ListBase *get_active_constraints (struct Object *ob) RET_NULL -struct ListBase *get_constraint_lb(struct Object *ob, struct bConstraint *con, struct bPoseChannel **r_pchan) RET_NULL - -bool ED_space_image_show_uvedit(struct SpaceImage *sima, struct Object *obedit) RET_ZERO -bool ED_space_image_show_render(struct SpaceImage *sima) RET_ZERO -bool ED_space_image_show_paint(struct SpaceImage *sima) RET_ZERO -void ED_space_image_paint_update(struct wmWindowManager *wm, struct Scene *scene) RET_NONE -void ED_space_image_set(struct SpaceImage *sima, struct Scene *scene, struct Object *obedit, struct Image *ima) RET_NONE -void ED_space_image_uv_sculpt_update(struct wmWindowManager *wm, struct Scene *scene) RET_NONE -void ED_space_image_scopes_update(const struct bContext *C, struct SpaceImage *sima, struct ImBuf *ibuf, bool use_view_settings) RET_NONE - -void ED_uvedit_get_aspect(struct Scene *scene, struct Object *ob, struct BMesh *em, float *aspx, float *aspy) RET_NONE - -struct MovieClip *ED_space_clip_get_clip(struct SpaceClip *sc) RET_NULL -void ED_space_clip_set_clip(struct bContext *C, struct bScreen *screen, struct SpaceClip *sc, struct MovieClip *clip) RET_NONE -void ED_space_clip_set_mask(struct bContext *C, struct SpaceClip *sc, struct Mask *mask) RET_NONE -void ED_space_image_set_mask(struct bContext *C, struct SpaceImage *sima, struct Mask *mask) RET_NONE - -void ED_area_tag_redraw_regiontype(struct ScrArea *sa, int regiontype) RET_NONE -void ED_render_engine_changed(struct Main *bmain) RET_NONE - -void ED_file_read_bookmarks(void) RET_NONE -void ED_file_change_dir(struct bContext *C) RET_NONE -void ED_preview_kill_jobs(struct wmWindowManager *wm, struct Main *bmain) RET_NONE -struct FSMenu *ED_fsmenu_get(void) RET_NULL -struct FSMenuEntry *ED_fsmenu_get_category(struct FSMenu *fsmenu, FSMenuCategory category) RET_NULL -int ED_fsmenu_get_nentries(struct FSMenu *fsmenu, FSMenuCategory category) RET_ZERO -struct FSMenuEntry *ED_fsmenu_get_entry(struct FSMenu *fsmenu, FSMenuCategory category, int index) RET_NULL -char *ED_fsmenu_entry_get_path(struct FSMenuEntry *fsentry) RET_NULL -void ED_fsmenu_entry_set_path(struct FSMenuEntry *fsentry, const char *name) RET_NONE -char *ED_fsmenu_entry_get_name(struct FSMenuEntry *fsentry) RET_NULL -void ED_fsmenu_entry_set_name(struct FSMenuEntry *fsentry, const char *name) RET_NONE - -struct PTCacheEdit *PE_get_current(struct Scene *scene, struct Object *ob) RET_NULL -void PE_current_changed(struct Depsgraph *depsgraph, struct Scene *scene, struct Object *ob) RET_NONE -struct PTCacheEdit *PE_create_current(struct Depsgraph *depsgraph, struct Scene *scene, struct Object *ob) RET_NULL -void PE_update_object( struct Depsgraph *depsgraph, struct Scene *scene, struct Object *ob, int useflag) RET_NONE - -/* rna keymap */ -struct wmKeyMap *WM_keymap_active(struct wmWindowManager *wm, struct wmKeyMap *keymap) RET_NULL -struct wmKeyMap *WM_keymap_find(struct wmKeyConfig *keyconf, const char *idname, int spaceid, int regionid) RET_NULL -struct wmKeyMapItem *WM_keymap_add_item(struct wmKeyMap *keymap, const char *idname, int type, int val, int modifier, int keymodifier) RET_NULL -struct wmKeyMap *WM_keymap_list_find(ListBase *lb, const char *idname, int spaceid, int regionid) RET_NULL -struct wmKeyConfig *WM_keyconfig_new(struct wmWindowManager *wm, const char *idname) RET_NULL -struct wmKeyConfig *WM_keyconfig_new_user(struct wmWindowManager *wm, const char *idname) RET_NULL -bool WM_keyconfig_remove(struct wmWindowManager *wm, struct wmKeyConfig *keyconf) RET_ZERO -bool WM_keymap_remove(struct wmKeyConfig *keyconfig, struct wmKeyMap *keymap) RET_ZERO -void WM_keyconfig_set_active(struct wmWindowManager *wm, const char *idname) RET_NONE -bool WM_keymap_remove_item(struct wmKeyMap *keymap, struct wmKeyMapItem *kmi) RET_ZERO -void WM_keymap_restore_to_default(struct wmKeyMap *keymap, struct bContext *C) RET_NONE -void WM_keymap_restore_item_to_default(struct bContext *C, struct wmKeyMap *keymap, struct wmKeyMapItem *kmi) RET_NONE -void WM_keymap_properties_reset(struct wmKeyMapItem *kmi, struct IDProperty *properties) RET_NONE -void WM_keyconfig_update_tag(struct wmKeyMap *keymap, struct wmKeyMapItem *kmi) RET_NONE -int WM_keymap_item_compare(struct wmKeyMapItem *k1, struct wmKeyMapItem *k2) RET_ZERO -int WM_keymap_map_type_get(struct wmKeyMapItem *kmi) RET_ZERO - - -/* rna editors */ - -struct FCurve *verify_fcurve(struct bAction *act, const char group[], struct PointerRNA *ptr, const char rna_path[], const int array_index, short add) RET_NULL -int insert_vert_fcurve(struct FCurve *fcu, float x, float y, char keytype, short flag) RET_ZERO -void delete_fcurve_key(struct FCurve *fcu, int index, bool do_recalc) RET_NONE -struct KeyingSetInfo *ANIM_keyingset_info_find_name (const char name[]) RET_NULL -struct KeyingSet *ANIM_scene_get_active_keyingset (struct Scene *scene) RET_NULL -int ANIM_scene_get_keyingset_index(struct Scene *scene, struct KeyingSet *ks) RET_ZERO -void ANIM_id_update(struct Scene *scene, struct ID *id) RET_NONE -struct ListBase builtin_keyingsets; -void ANIM_keyingset_info_register(struct KeyingSetInfo *ksi) RET_NONE -void ANIM_keyingset_info_unregister(struct Main *bmain, KeyingSetInfo *ksi) RET_NONE -short ANIM_validate_keyingset(struct bContext *C, struct ListBase *dsources, struct KeyingSet *ks) RET_ZERO -int ANIM_add_driver(struct ReportList *reports, struct ID *id, const char rna_path[], int array_index, short flag, int type) RET_ZERO -bool ANIM_remove_driver(struct ReportList *reports, struct ID *id, const char rna_path[], int array_index, short flag) RET_ZERO -void ED_space_image_release_buffer(struct SpaceImage *sima, struct ImBuf *ibuf, void *lock) RET_NONE -struct ImBuf *ED_space_image_acquire_buffer(struct SpaceImage *sima, void **r_lock) RET_NULL -void ED_space_image_get_zoom(struct SpaceImage *sima, struct ARegion *ar, float *zoomx, float *zoomy) RET_NONE -const char *ED_info_stats_string(struct Scene *scene, struct ViewLayer *view_layer) RET_NULL -void ED_area_tag_redraw(struct ScrArea *sa) RET_NONE -void ED_area_tag_refresh(struct ScrArea *sa) RET_NONE -void ED_area_newspace(struct bContext *C, struct ScrArea *sa, int type, const bool skip_ar_exit) RET_NONE -void ED_region_tag_redraw(struct ARegion *ar) RET_NONE -void WM_event_add_fileselect(struct bContext *C, struct wmOperator *op) RET_NONE -void WM_cursor_wait(bool val) RET_NONE -void ED_node_texture_default(const struct bContext *C, struct Tex *tex) RET_NONE -void ED_node_tag_update_id(struct ID *id) RET_NONE -void ED_node_tag_update_nodetree(struct Main *bmain, struct bNodeTree *ntree, struct bNode *node) RET_NONE -void ED_node_tree_update(const struct bContext *C) RET_NONE -void ED_node_set_tree_type(struct SpaceNode *snode, struct bNodeTreeType *typeinfo) RET_NONE -void ED_init_custom_node_type(struct bNodeType *ntype) RET_NONE -void ED_init_custom_node_socket_type(struct bNodeSocketType *stype) RET_NONE -void ED_init_standard_node_socket_type(struct bNodeSocketType *stype) RET_NONE -void ED_init_node_socket_type_virtual(struct bNodeSocketType *stype) RET_NONE -int ED_node_tree_path_length(struct SpaceNode *snode) RET_ZERO -void ED_node_tree_path_get(struct SpaceNode *snode, char *value) RET_NONE -void ED_node_tree_path_get_fixedbuf(struct SpaceNode *snode, char *value, int max_length) RET_NONE -void ED_node_tree_start(struct SpaceNode *snode, struct bNodeTree *ntree, struct ID *id, struct ID *from) RET_NONE -void ED_node_tree_push(struct SpaceNode *snode, struct bNodeTree *ntree, struct bNode *gnode) RET_NONE -void ED_node_tree_pop(struct SpaceNode *snode) RET_NONE -int ED_view3d_view_layer_set(int lay, const int *values, int *active) RET_ZERO -void ED_view3d_quadview_update(struct ScrArea *sa, struct ARegion *ar, bool do_clip) RET_NONE -void ED_view3d_from_m4(float mat[4][4], float ofs[3], float quat[4], float *dist) RET_NONE -void ED_view3d_update_viewmat(struct Depsgraph *depsgraph, struct Scene *scene, struct View3D *v3d, struct ARegion *ar, float viewmat[4][4], float winmat[4][4], const struct rcti *rect) RET_NONE -float ED_view3d_grid_scale(struct Scene *scene, struct View3D *v3d, const char **grid_unit) RET_ZERO -void ED_view3d_shade_update(struct Main *bmain, struct View3D *v3d, struct ScrArea *sa) RET_NONE -void ED_node_shader_default(const struct bContext *C, struct ID *id) RET_NONE -void ED_screen_animation_timer_update(struct bScreen *screen, int redraws, int refresh) RET_NONE -struct bScreen *ED_screen_animation_playing(const struct wmWindowManager *wm) RET_NULL -struct Scene *ED_screen_scene_find(const struct bScreen *screen, const struct wmWindowManager *wm) RET_NULL -struct Scene *ED_screen_scene_find_with_window(const struct bScreen *screen, const struct wmWindowManager *wm, struct wmWindow **r_window) RET_NULL -struct wmWindow *ED_screen_window_find(const struct bScreen *screen, const struct wmWindowManager *wm) RET_NULL; -bool ED_scene_view_layer_delete(struct Main *bmain, Scene *scene, ViewLayer *layer, ReportList *reports) RET_ZERO -void ED_object_base_select(struct Base *base, eObjectSelect_Mode mode) RET_NONE -void ED_object_base_activate(struct bContext *C, struct Base *base) RET_NONE -bool ED_object_modifier_remove(struct ReportList *reports, struct Main *bmain, struct Object *ob, struct ModifierData *md) RET_ZERO -struct ModifierData *ED_object_modifier_add(struct ReportList *reports, struct Main *bmain, struct Scene *scene, struct Object *ob, const char *name, int type) RET_ZERO -void ED_object_modifier_clear(struct Main *bmain, struct Object *ob) RET_NONE -void ED_object_editmode_enter(struct bContext *C, int flag) RET_NONE -void ED_object_editmode_exit(struct bContext *C, int flag) RET_NONE -void ED_object_editmode_exit_ex(struct bContext *C, struct Scene *scene, struct Object *obedit, int flag) RET_NONE -bool ED_object_editmode_load(struct Object *obedit) RET_ZERO -void ED_object_check_force_modifiers(struct Main *bmain, struct Scene *scene, struct Object *object) RET_NONE -bool uiLayoutGetActive(struct uiLayout *layout) RET_ZERO -int uiLayoutGetOperatorContext(struct uiLayout *layout) RET_ZERO -int uiLayoutGetAlignment(struct uiLayout *layout) RET_ZERO -bool uiLayoutGetEnabled(struct uiLayout *layout) RET_ZERO -float uiLayoutGetScaleX(struct uiLayout *layout) RET_ZERO -float uiLayoutGetScaleY(struct uiLayout *layout) RET_ZERO -void uiLayoutSetActive(struct uiLayout *layout, bool active) RET_NONE -void uiLayoutSetOperatorContext(struct uiLayout *layout, int opcontext) RET_NONE -void uiLayoutSetEnabled(uiLayout *layout, bool enabled) RET_NONE -void uiLayoutSetAlignment(uiLayout *layout, char alignment) RET_NONE -void uiLayoutSetScaleX(struct uiLayout *layout, float scale) RET_NONE -void uiLayoutSetScaleY(struct uiLayout *layout, float scale) RET_NONE -void uiTemplateIconView(struct uiLayout *layout, struct PointerRNA *ptr, const char *propname, int show_labels, float icon_scale) RET_NONE -void ED_object_base_free_and_unlink(struct Main *bmain, struct Scene *scene, struct Object *base) RET_NONE -void ED_mesh_update(struct Mesh *mesh, struct bContext *C, int calc_edges, int calc_tessface) RET_NONE -void ED_mesh_vertices_add(struct Mesh *mesh, struct ReportList *reports, int count) RET_NONE -void ED_mesh_edges_add(struct Mesh *mesh, struct ReportList *reports, int count) RET_NONE -void ED_mesh_tessfaces_add(struct Mesh *mesh, struct ReportList *reports, int count) RET_NONE -void ED_mesh_loops_add(struct Mesh *mesh, struct ReportList *reports, int count) RET_NONE -void ED_mesh_polys_add(struct Mesh *mesh, struct ReportList *reports, int count) RET_NONE -void ED_mesh_vertices_remove(struct Mesh *mesh, struct ReportList *reports, int count) RET_NONE -void ED_mesh_edges_remove(struct Mesh *mesh, struct ReportList *reports, int count) RET_NONE -void ED_mesh_faces_remove(struct Mesh *mesh, struct ReportList *reports, int count) RET_NONE -int ED_mesh_color_add(struct Mesh *me, const char *name, const bool active_set) RET_MINUSONE -int ED_mesh_uv_texture_add(struct Mesh *me, const char *name, const bool active_set) RET_MINUSONE -bool ED_mesh_color_remove_named(struct Mesh *me, const char *name) RET_ZERO -bool ED_mesh_uv_texture_remove_named(struct Mesh *me, const char *name) RET_ZERO -void ED_object_constraint_dependency_update(struct Main *bmain, struct Object *ob) RET_NONE -void ED_object_constraint_dependency_tag_update(struct Main *bmain, struct Object *ob, struct bConstraint *con) RET_NONE -void ED_object_constraint_update(struct Object *ob) RET_NONE -void ED_object_constraint_tag_update(struct Object *ob, struct bConstraint *con) RET_NONE -void ED_vgroup_vert_add(struct Object *ob, struct bDeformGroup *dg, int vertnum, float weight, int assignmode) RET_NONE -void ED_vgroup_vert_remove(struct Object *ob, struct bDeformGroup *dg, int vertnum) RET_NONE -float ED_vgroup_vert_weight(struct Object *ob, struct bDeformGroup *dg, int vertnum) RET_ZERO -int ED_mesh_mirror_topo_table(struct Object *ob, struct DerivedMesh *dm, char mode) RET_ZERO -int ED_mesh_mirror_spatial_table(struct Object *ob, struct BMEditMesh *em, struct DerivedMesh *dm, const float co[3], char mode) RET_ZERO - -float ED_armature_ebone_roll_to_vector(const EditBone *bone, const float new_up_axis[3], const bool axis_only) RET_ZERO -void ED_space_image_get_size(struct SpaceImage *sima, int *width, int *height) RET_NONE -bool ED_space_image_check_show_maskedit(struct SpaceImage *sima, struct ViewLayer *view_layer) RET_ZERO - -bool ED_texture_context_check_world(const struct bContext *C) RET_ZERO -bool ED_texture_context_check_material(const struct bContext *C) RET_ZERO -bool ED_texture_context_check_lamp(const struct bContext *C) RET_ZERO -bool ED_texture_context_check_particles(const struct bContext *C) RET_ZERO -bool ED_texture_context_check_others(const struct bContext *C) RET_ZERO - -bool ED_text_region_location_from_cursor(SpaceText *st, ARegion *ar, const int cursor_co[2], int r_pixel_co[2]) RET_ZERO - -SnapObjectContext *ED_transform_snap_object_context_create( - struct Main *bmain, struct Scene *scene, int flag) RET_NULL -SnapObjectContext *ED_transform_snap_object_context_create_view3d( - struct Main *bmain, struct Scene *scene, int flag, - const struct ARegion *ar, const struct View3D *v3d) RET_NULL -void ED_transform_snap_object_context_destroy(SnapObjectContext *sctx) RET_NONE -bool ED_transform_snap_object_project_ray_ex( - struct SnapObjectContext *sctx, - const struct SnapObjectParams *params, - const float ray_start[3], const float ray_normal[3], float *ray_depth, - /* return args */ - float r_loc[3], float r_no[3], int *r_index, - struct Object **r_ob, float r_obmat[4][4]) RET_ZERO -void BIF_selectTransformOrientationValue(struct View3D *v3d, int orientation) RET_NONE - -void ED_curve_editnurb_load(struct Object *obedit) RET_NONE -void ED_curve_editnurb_make(struct Object *obedit) RET_NONE - -void uiItemR(uiLayout *layout, struct PointerRNA *ptr, const char *propname, int flag, const char *name, int icon) RET_NONE - -void uiItemFullO(uiLayout *layout, const char *idname, const char *name, int icon, struct IDProperty *properties, int context, int flag, struct PointerRNA *r_opptr) RET_NONE -void uiItemFullO_ptr(struct uiLayout *layout, struct wmOperatorType *ot, const char *name, int icon, struct IDProperty *properties, int context, int flag, struct PointerRNA *r_opptr) RET_NONE -void uiItemFullOMenuHold_ptr( uiLayout *layout, struct wmOperatorType *ot, const char *name, int icon, struct IDProperty *properties, int context, int flag, const char *menu_id, /* extra menu arg. */ PointerRNA *r_opptr) RET_NONE -struct uiLayout *uiLayoutRow(uiLayout *layout, int align) RET_NULL -struct uiLayout *uiLayoutColumn(uiLayout *layout, int align) RET_NULL -struct uiLayout *uiLayoutColumnFlow(uiLayout *layout, int number, int align) RET_NULL -struct uiLayout *uiLayoutBox(struct uiLayout *layout) RET_NULL -struct uiLayout *uiLayoutSplit(uiLayout *layout, float percentage, int align) RET_NULL -bool uiLayoutGetRedAlert(struct uiLayout *layout) RET_ZERO -void uiLayoutSetRedAlert(uiLayout *layout, bool redalert) RET_NONE -void uiItemsEnumR(uiLayout *layout, struct PointerRNA *ptr, const char *propname) RET_NONE -void uiItemMenuEnumR_prop(uiLayout *layout, struct PointerRNA *ptr, PropertyRNA *prop, const char *name, int icon) RET_NONE -void uiItemMenuEnumR(uiLayout *layout, struct PointerRNA *ptr, const char *propname, const char *name, int icon) RET_NONE -void uiItemEnumR_string(uiLayout *layout, struct PointerRNA *ptr, const char *propname, const char *value, const char *name, int icon) RET_NONE -void uiItemPointerR(uiLayout *layout, struct PointerRNA *ptr, const char *propname, struct PointerRNA *searchptr, const char *searchpropname, const char *name, int icon) RET_NONE -void uiItemsEnumO(uiLayout *layout, const char *opname, const char *propname) RET_NONE -void uiItemEnumO_string(uiLayout *layout, const char *name, int icon, const char *opname, const char *propname, const char *value) RET_NONE -void uiItemMenuEnumO(uiLayout *layout, struct bContext *C, const char *opname, const char *propname, const char *name, int icon) RET_NONE -void uiItemMenuEnumO_ptr(uiLayout *layout, struct bContext *C, struct wmOperatorType *ot, const char *propname, const char *name, int icon) RET_NONE -void uiItemBooleanO(uiLayout *layout, const char *name, int icon, const char *opname, const char *propname, int value) RET_NONE -void uiItemIntO(uiLayout *layout, const char *name, int icon, const char *opname, const char *propname, int value) RET_NONE -void uiItemFloatO(uiLayout *layout, const char *name, int icon, const char *opname, const char *propname, float value) RET_NONE -void uiItemStringO(uiLayout *layout, const char *name, int icon, const char *opname, const char *propname, const char *value) RET_NONE -void uiItemL(struct uiLayout *layout, const char *name, int icon) RET_NONE -void uiItemM(uiLayout *layout, struct bContext *C, const char *menuname, const char *name, int icon) RET_NONE -void uiItemS(struct uiLayout *layout) RET_NONE -void uiItemFullR(uiLayout *layout, struct PointerRNA *ptr, struct PropertyRNA *prop, int index, int value, int flag, const char *name, int icon) RET_NONE -void uiLayoutSetContextPointer(uiLayout *layout, const char *name, struct PointerRNA *ptr) RET_NONE -const char *uiLayoutIntrospect(uiLayout *layout) RET_NULL -void UI_reinit_font(void) RET_NONE -int UI_rnaptr_icon_get(struct bContext *C, struct PointerRNA *ptr, int rnaicon, const bool big) RET_ZERO -struct bTheme *UI_GetTheme(void) RET_NULL -void UI_GetThemeColor3fv(int colorid, float col[4]) RET_NONE -void UI_GetThemeColor4fv(int colorid, float col[4]) RET_NONE -void UI_GetThemeColorShade4fv(int colorid, int offset, float col[4]) RET_NONE -void UI_GetThemeColorShadeAlpha4fv(int colorid, int coloffset, int alphaoffset, float col[4]) RET_NONE -void UI_GetThemeColorBlendShade3fv(int colorid1, int colorid2, float fac, int offset, float col[3]) RET_NONE -void UI_GetThemeColorBlendShade4fv(int colorid1, int colorid2, float fac, int offset, float col[4]) RET_NONE -void UI_GetThemeColorBlend3ubv(int colorid1, int colorid2, float fac, unsigned char col[3]) RET_NONE -void UI_GetThemeColorShadeAlpha4ubv(int colorid, int coloffset, int alphaoffset, unsigned char col[4]) RET_NONE -void UI_widgetbase_draw_cache_flush(void) RET_NONE - -/* rna template */ -void uiTemplateAnyID(uiLayout *layout, struct PointerRNA *ptr, const char *propname, const char *proptypename, const char *text) RET_NONE -void uiTemplatePathBuilder(uiLayout *layout, struct PointerRNA *ptr, const char *propname, struct PointerRNA *root_ptr, const char *text) RET_NONE -void uiTemplateHeader(struct uiLayout *layout, struct bContext *C) RET_NONE -void uiTemplateID(uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, const char *propname, const char *newop, const char *openop, const char *unlinkop, int filter) RET_NONE -struct uiLayout *uiTemplateModifier(uiLayout *layout, struct bContext *C, struct PointerRNA *ptr) RET_NULL -struct uiLayout *uiTemplateConstraint(struct uiLayout *layout, struct PointerRNA *ptr) RET_NULL -void uiTemplatePreview(struct uiLayout *layout, struct bContext *C, struct ID *id, int show_buttons, struct ID *parent, - struct MTex *slot, const char *preview_id) RET_NONE -void uiTemplateIDPreview(uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, const char *propname, const char *newop, const char *openop, const char *unlinkop, int rows, int cols, int filter) RET_NONE -void uiTemplateSearch( - uiLayout *layout, struct bContext *C, - PointerRNA *ptr, const char *propname, - PointerRNA *searchptr, const char *searchpropname, - const char *newop, const char *unlinkop) RET_NONE -void uiTemplateSearchPreview( - uiLayout *layout, struct bContext *C, - PointerRNA *ptr, const char *propname, - PointerRNA *searchptr, const char *searchpropname, - const char *newop, const char *unlinkop, - const int rows, const int cols) RET_NONE -void uiTemplateCurveMapping(uiLayout *layout, struct PointerRNA *ptr, const char *propname, int type, int levels, int brush, int neg_slope) RET_NONE -void uiTemplateColorRamp(uiLayout *layout, struct PointerRNA *ptr, const char *propname, int expand) RET_NONE -void uiTemplateLayers(uiLayout *layout, struct PointerRNA *ptr, const char *propname, PointerRNA *used_ptr, const char *used_propname, int active_layer) RET_NONE -void uiTemplateImageLayers(struct uiLayout *layout, struct bContext *C, struct Image *ima, struct ImageUser *iuser) RET_NONE -void uiTemplateList(struct uiLayout *layout, struct bContext *C, const char *listtype_name, const char *list_id, - PointerRNA *dataptr, const char *propname, PointerRNA *active_dataptr, const char *active_propname, - const char *item_dyntip_propname, int rows, int maxrows, int layout_type, int columns) RET_NONE -void uiTemplateRunningJobs(struct uiLayout *layout, struct bContext *C) RET_NONE -void uiTemplateOperatorSearch(struct uiLayout *layout) RET_NONE -void uiTemplateHeader3D(struct uiLayout *layout, struct bContext *C) RET_NONE -void uiTemplateEditModeSelection(struct uiLayout *layout, struct bContext *C) RET_NONE -void uiTemplateImage(uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, const char *propname, struct PointerRNA *userptr, int compact, int multiview) RET_NONE -void uiTemplateColorPicker(uiLayout *layout, struct PointerRNA *ptr, const char *propname, int value_slider, int lock, int lock_luminosity, int cubic) RET_NONE -void uiTemplateHistogram(uiLayout *layout, struct PointerRNA *ptr, const char *propname) RET_NONE -void uiTemplateReportsBanner(uiLayout *layout, struct bContext *C) RET_NONE -void uiTemplateWaveform(uiLayout *layout, struct PointerRNA *ptr, const char *propname) RET_NONE -void uiTemplateVectorscope(uiLayout *layout, struct PointerRNA *ptr, const char *propname) RET_NONE -void uiTemplateNodeLink(struct uiLayout *layout, struct bNodeTree *ntree, struct bNode *node, struct bNodeSocket *input) RET_NONE -void uiTemplateNodeView(struct uiLayout *layout, struct bContext *C, struct bNodeTree *ntree, struct bNode *node, struct bNodeSocket *input) RET_NONE -void uiTemplateTextureUser(struct uiLayout *layout, struct bContext *C) RET_NONE -void uiTemplateTextureShow(struct uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop) RET_NONE -void uiTemplateKeymapItemProperties(struct uiLayout *layout, struct PointerRNA *ptr) RET_NONE -void uiTemplateOverrideProperty(struct uiLayout *layout, struct PointerRNA *collection_props_ptr, struct PointerRNA *scene_props_ptr, const char *propname, const char *name, const char *text_ctxt, int translate, int icon, const char *custom_template) RET_NONE -void uiTemplateMovieClip(struct uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, const char *propname, int compact) RET_NONE -void uiTemplateMovieclipInformation(struct uiLayout *layout, struct PointerRNA *ptr, const char *propname, struct PointerRNA *userptr) RET_NONE -void uiTemplateTrack(struct uiLayout *layout, struct PointerRNA *ptr, const char *propname) RET_NONE -void uiTemplateMarker(struct uiLayout *layout, struct PointerRNA *ptr, const char *propname, PointerRNA *userptr, PointerRNA *trackptr, int compact) RET_NONE -void uiTemplateImageSettings(uiLayout *layout, struct PointerRNA *imfptr, int color_management) RET_NONE -void uiTemplateColorspaceSettings(struct uiLayout *layout, struct PointerRNA *ptr, const char *propname) RET_NONE -void uiTemplateColormanagedViewSettings(struct uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, const char *propname) RET_NONE -void uiTemplateComponentMenu(struct uiLayout *layout, struct PointerRNA *ptr, const char *propname, const char *name) RET_NONE -void uiTemplateNodeSocket(struct uiLayout *layout, struct bContext *C, float *color) RET_NONE -void uiTemplatePalette(struct uiLayout *layout, struct PointerRNA *ptr, const char *propname, int color) RET_NONE -void uiTemplateImageStereo3d(struct uiLayout *layout, struct PointerRNA *stereo3d_format_ptr) RET_NONE -void uiTemplateCacheFile(uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, const char *propname) RET_NONE - -/* rna render */ -struct RenderResult *RE_engine_begin_result(RenderEngine *engine, int x, int y, int w, int h, const char *layername, const char *viewname) RET_NULL -struct RenderResult *RE_AcquireResultRead(struct Render *re) RET_NULL -struct RenderResult *RE_AcquireResultWrite(struct Render *re) RET_NULL -struct RenderResult *RE_engine_get_result(struct RenderEngine *re) RET_NULL -struct RenderStats *RE_GetStats(struct Render *re) RET_NULL -struct RenderData *RE_engine_get_render_data(struct Render *re) RET_NULL -void RE_engine_update_result(struct RenderEngine *engine, struct RenderResult *result) RET_NONE -void RE_engine_update_progress(struct RenderEngine *engine, float progress) RET_NONE -void RE_engine_set_error_message(RenderEngine *engine, const char *msg) RET_NONE -void RE_engine_add_pass(RenderEngine *engine, const char *name, int channels, const char *chan_id, const char *layername) RET_NONE -void RE_engine_end_result(RenderEngine *engine, struct RenderResult *result, int cancel, int highlight, int merge_results) RET_NONE -void RE_engine_update_stats(RenderEngine *engine, const char *stats, const char *info) RET_NONE -void RE_layer_load_from_file(struct RenderLayer *layer, struct ReportList *reports, const char *filename, int x, int y) RET_NONE -void RE_result_load_from_file(struct RenderResult *result, struct ReportList *reports, const char *filename) RET_NONE -void RE_AcquireResultImage(struct Render *re, struct RenderResult *rr, const int view_id) RET_NONE -void RE_ReleaseResult(struct Render *re) RET_NONE -void RE_ReleaseResultImage(struct Render *re) RET_NONE -int RE_engine_test_break(struct RenderEngine *engine) RET_ZERO -void RE_engines_init() RET_NONE -void RE_engines_exit() RET_NONE -void RE_engines_register(struct Main *bmain, RenderEngineType *render_type) RET_NONE -void RE_engine_report(struct RenderEngine *engine, int type, const char *msg) RET_NONE -ListBase R_engines = {NULL, NULL}; -void RE_engine_free(struct RenderEngine *engine) RET_NONE -struct RenderEngineType *RE_engines_find(const char *idname) RET_NULL -void RE_engine_update_memory_stats(struct RenderEngine *engine, float mem_used, float mem_peak) RET_NONE -struct RenderEngine *RE_engine_create(struct RenderEngineType *type) RET_NULL -void RE_engine_frame_set(struct RenderEngine *engine, int frame, float subframe) RET_NONE -void RE_FreePersistentData(void) RET_NONE -void RE_point_density_cache(struct Depsgraph *depsgraph, struct PointDensity *pd) RET_NONE -void RE_point_density_minmax(struct Depsgraph *depsgraph, struct PointDensity *pd, float r_min[3], float r_max[3]) RET_NONE -void RE_point_density_sample(struct Depsgraph *depsgraph, struct PointDensity *pd, const int resolution, float *values) RET_NONE -void RE_point_density_free(struct PointDensity *pd) RET_NONE -void RE_instance_get_particle_info(struct ObjectInstanceRen *obi, float *index, float *random, float *age, float *lifetime, float co[3], float *size, float vel[3], float angvel[3]) RET_NONE -void RE_FreeAllPersistentData(void) RET_NONE -float RE_fresnel_dielectric(float incoming[3], float normal[3], float eta) RET_ZERO -void RE_engine_register_pass(struct RenderEngine *engine, struct Scene *scene, struct ViewLayer *view_layer, const char *name, int channels, const char *chanid, int type) RET_NONE - -/* Draw */ -void OBJECT_collection_settings_create(struct IDProperty *properties) RET_NONE -void EDIT_MESH_collection_settings_create(struct IDProperty *properties) RET_NONE -void EDIT_ARMATURE_collection_settings_create(struct IDProperty *properties) RET_NONE -void PAINT_WEIGHT_collection_settings_create(struct IDProperty *properties) RET_NONE -void PAINT_VERTEX_collection_settings_create(struct IDProperty *properties) RET_NONE - -/* python */ -struct wmOperatorType *WM_operatortype_find(const char *idname, bool quiet) RET_NULL -void WM_operatortype_iter(struct GHashIterator *ghi) RET_NONE -struct wmOperatorTypeMacro *WM_operatortype_macro_define(struct wmOperatorType *ot, const char *idname) RET_NULL -int WM_operator_call_py(struct bContext *C, struct wmOperatorType *ot, short context, struct PointerRNA *properties, struct ReportList *reports, const bool is_undo) RET_ZERO -void WM_operatortype_remove_ptr(struct wmOperatorType *ot) RET_NONE -bool WM_operatortype_remove(const char *idname) RET_ZERO -int WM_operator_poll(struct bContext *C, struct wmOperatorType *ot) RET_ZERO -int WM_operator_poll_context(struct bContext *C, struct wmOperatorType *ot, short context) RET_ZERO -int WM_operator_props_popup(struct bContext *C, struct wmOperator *op, const struct wmEvent *event) RET_ZERO -void WM_operator_properties_free(struct PointerRNA *ptr) RET_NONE -void WM_operator_properties_create(struct PointerRNA *ptr, const char *opstring) RET_NONE -void WM_operator_properties_create_ptr(struct PointerRNA *ptr, struct wmOperatorType *ot) RET_NONE -void WM_operator_properties_sanitize(struct PointerRNA *ptr, const bool no_context) RET_NONE -void WM_operatortype_append_ptr(void (*opfunc)(struct wmOperatorType *, void *), void *userdata) RET_NONE -void WM_operatortype_append_macro_ptr(void (*opfunc)(struct wmOperatorType *, void *), void *userdata) RET_NONE -void WM_operator_bl_idname(char *to, const char *from) RET_NONE -void WM_operator_py_idname(char *to, const char *from) RET_NONE -bool WM_operator_py_idname_ok_or_report(struct ReportList *reports, const char *classname, const char *idname) RET_ZERO -int WM_operator_ui_popup(struct bContext *C, struct wmOperator *op, int width, int height) RET_ZERO -void update_autoflags_fcurve(struct FCurve *fcu, struct bContext *C, struct ReportList *reports, struct PointerRNA *ptr) RET_NONE -short insert_keyframe(struct ReportList *reports, struct ID *id, struct bAction *act, const char group[], const char rna_path[], int array_index, float cfra, char keytype, short flag) RET_ZERO -short delete_keyframe(struct ReportList *reports, struct ID *id, struct bAction *act, const char group[], const char rna_path[], int array_index, float cfra, short flag) RET_ZERO -struct bAction *verify_adt_action(struct ID *id, short add) RET_NULL -char *WM_operator_pystring_ex(struct bContext *C, struct wmOperator *op, const bool all_args, const bool macro_args, struct wmOperatorType *ot, struct PointerRNA *opptr) RET_NULL -char *WM_operator_pystring(struct bContext *C, struct wmOperator *op, const bool all_args, const bool macro_args) RET_NULL -struct wmKeyMapItem *WM_modalkeymap_add_item(struct wmKeyMap *km, int type, int val, int modifier, int keymodifier, int value) RET_NULL -struct wmKeyMapItem *WM_modalkeymap_add_item_str(struct wmKeyMap *km, int type, int val, int modifier, int keymodifier, const char *value) RET_NULL -struct wmKeyMap *WM_modalkeymap_add(struct wmKeyConfig *keyconf, const char *idname, const struct EnumPropertyItem *items) RET_NULL -struct uiPopupMenu *UI_popup_menu_begin(struct bContext *C, const char *title, int icon) RET_NULL -void UI_popup_menu_end(struct bContext *C, struct uiPopupMenu *head) RET_NONE -struct uiLayout *UI_popup_menu_layout(struct uiPopupMenu *head) RET_NULL -struct uiLayout *UI_pie_menu_layout(struct uiPieMenu *pie) RET_NULL -int UI_pie_menu_invoke(struct bContext *C, const char *idname, const struct wmEvent *event) RET_ZERO -struct uiPieMenu *UI_pie_menu_begin(struct bContext *C, const char *title, int icon, const struct wmEvent *event) RET_NULL -void UI_pie_menu_end(struct bContext *C, uiPieMenu *pie) RET_NONE -struct uiLayout *uiLayoutRadial(struct uiLayout *layout) RET_NULL -int UI_pie_menu_invoke_from_operator_enum(struct bContext *C, const char *title, const char *opname, - const char *propname, const struct wmEvent *event) RET_ZERO - -void ED_mesh_calc_tessface(struct Mesh *mesh, bool free_mpoly) RET_NONE - -/* bpy/python internal api */ -extern void BPY_RNA_operator_wrapper(struct wmOperatorType *ot, void *userdata); -extern void BPY_RNA_operator_macro_wrapper(struct wmOperatorType *ot, void *userdata); -void BPY_RNA_operator_wrapper(struct wmOperatorType *ot, void *userdata) RET_NONE -void BPY_RNA_operator_macro_wrapper(struct wmOperatorType *ot, void *userdata) RET_NONE -void BPY_text_free_code(struct Text *text) RET_NONE -void BPY_id_release(struct ID *id) RET_NONE -void BPY_DECREF_RNA_INVALIDATE(void *pyob_ptr) RET_NONE -int BPY_context_member_get(struct bContext *C, const char *member, struct bContextDataResult *result) RET_ZERO -void BPY_pyconstraint_target(struct bPythonConstraint *con, struct bConstraintTarget *ct) RET_NONE -float BPY_driver_exec(PathResolvedRNA *anim_rna, struct ChannelDriver *driver, const float evaltime) RET_ZERO /* might need this one! */ -void BPY_DECREF(void *pyob_ptr) RET_NONE -void BPY_pyconstraint_exec(struct bPythonConstraint *con, struct bConstraintOb *cob, struct ListBase *targets) RET_NONE -bool pyrna_id_FromPyObject(struct PyObject *obj, struct ID **id) RET_ZERO -struct PyObject *pyrna_id_CreatePyObject(struct ID *id) RET_NULL -bool pyrna_id_CheckPyObject(struct PyObject *obj) RET_ZERO -void BPY_context_update(struct bContext *C) RET_NONE -const char *BPY_app_translations_py_pgettext(const char *msgctxt, const char *msgid) RET_ARG(msgid) - -/* intern/dualcon */ - -void *dualcon(const DualConInput *input_mesh, - /* callbacks for output */ - DualConAllocOutput alloc_output, - DualConAddVert add_vert, - DualConAddQuad add_quad, - - DualConFlags flags, - DualConMode mode, - float threshold, - float hermite_num, - float scale, - int depth) RET_ZERO - -/* compositor */ -void COM_execute(RenderData *rd, Scene *scene, bNodeTree *editingtree, int rendering, - const ColorManagedViewSettings *viewSettings, const ColorManagedDisplaySettings *displaySettings, - const char *viewName) RET_NONE - -/*multiview*/ -bool RE_RenderResult_is_stereo(RenderResult *res) RET_ZERO -void uiTemplateImageViews(uiLayout *layout, struct PointerRNA *imfptr) RET_NONE - -#endif // WITH_GAMEENGINE diff --git a/source/creator/CMakeLists.txt b/source/creator/CMakeLists.txt index 1adef28f2c8..c5d1a55dfd6 100644 --- a/source/creator/CMakeLists.txt +++ b/source/creator/CMakeLists.txt @@ -76,12 +76,6 @@ if(WITH_HEADLESS) add_definitions(-DWITH_HEADLESS) endif() -if(WITH_GAMEENGINE) - blender_include_dirs(../gameengine/BlenderRoutines) - - add_definitions(-DWITH_GAMEENGINE) -endif() - if(WITH_SDL) if(WITH_SDL_DYNLOAD) add_definitions(-DWITH_SDL_DYNLOAD) @@ -930,53 +924,6 @@ elseif(APPLE) ) unset(_py_inc_suffix) endif() - - # install blenderplayer bundle - copy of blender.app above. re-using macros et al - # note we are using OSX Bundle as base and copying Blender dummy bundle on top of it - if(WITH_GAMEENGINE AND WITH_PLAYER) - set(OSX_APP_PLAYER_SOURCEDIR ${CMAKE_SOURCE_DIR}/release/darwin/blenderplayer.app) - set(PLAYER_SOURCEINFO ${OSX_APP_PLAYER_SOURCEDIR}/Contents/Info.plist) - set(PLAYER_TARGETDIR_VER blenderplayer.app/Contents/Resources/${BLENDER_VERSION}) - - - # important to make a clean install each time else old scripts get loaded. - install( - CODE - "file(REMOVE_RECURSE ${PLAYER_TARGETDIR_VER})" - ) - - # Give the bundle actual creation/modification date - execute_process(COMMAND SetFile -d ${SETFILE_DATE} -m ${SETFILE_DATE} - ${EXECUTABLE_OUTPUT_PATH}/blenderplayer.app) - - install( - FILES ${OSX_APP_PLAYER_SOURCEDIR}/Contents/PkgInfo - DESTINATION blenderplayer.app/Contents - ) - - install_dir( - ${OSX_APP_PLAYER_SOURCEDIR}/Contents/Resources - blenderplayer.app/Contents/ - ) - - if(WITH_OPENMP AND CMAKE_C_COMPILER_ID MATCHES "Clang" AND NOT ${CMAKE_C_COMPILER_VERSION} VERSION_LESS '3.4') - install( - FILES ${LIBDIR}/openmp/lib/libiomp5.dylib - DESTINATION blenderplayer.app/Contents/Resources/lib/ - ) - endif() - - - # python - if(WITH_PYTHON AND NOT WITH_PYTHON_FRAMEWORK) - # Copy the python libs into the install directory - install_dir( - ${PYTHON_LIBPATH} - ${PLAYER_TARGETDIR_VER}/python/lib - ) - endif() - - endif() endif() diff --git a/source/creator/creator.c b/source/creator/creator.c index 2aa60c3e2a7..d3fecad2e03 100644 --- a/source/creator/creator.c +++ b/source/creator/creator.c @@ -85,13 +85,6 @@ # include "FRS_freestyle.h" #endif -/* for passing information between creator and gameengine */ -#ifdef WITH_GAMEENGINE -# include "BL_System.h" -#else /* dummy */ -# define SYS_SystemHandle int -#endif - #include #ifdef __FreeBSD__ @@ -226,7 +219,6 @@ int main( ) { bContext *C; - SYS_SystemHandle syshandle; #ifndef WITH_PYTHON_MODULE bArgs *ba; @@ -381,12 +373,6 @@ int main( BLI_callback_global_init(); -#ifdef WITH_GAMEENGINE - syshandle = SYS_GetSystem(); -#else - syshandle = 0; -#endif - /* first test for background */ #ifndef WITH_PYTHON_MODULE ba = BLI_argsInit(argc, (const char **)argv); /* skip binary path */ @@ -394,7 +380,7 @@ int main( /* ensure we free on early exit */ app_init_data.ba = ba; - main_args_setup(C, ba, &syshandle); + main_args_setup(C, ba); BLI_argsParse(ba, 1, NULL, NULL); @@ -402,7 +388,6 @@ int main( #else G.factory_startup = true; /* using preferences or user startup makes no sense for py-as-module */ - (void)syshandle; #endif #ifdef WITH_FFMPEG @@ -517,20 +502,6 @@ int main( WM_exit(C); } else { - if (G.fileflags & G_FILE_AUTOPLAY) { - if (G.f & G_SCRIPT_AUTOEXEC) { - if (WM_init_game(C)) { - return 0; - } - } - else { - if (!(G.f & G_SCRIPT_AUTOEXEC_FAIL_QUIET)) { - G.f |= G_SCRIPT_AUTOEXEC_FAIL; - BLI_snprintf(G.autoexec_fail, sizeof(G.autoexec_fail), "Game AutoStart"); - } - } - } - if (!G.file_loaded) { WM_init_splash(C); } diff --git a/source/creator/creator_args.c b/source/creator/creator_args.c index dac22322361..96aeba56eee 100644 --- a/source/creator/creator_args.c +++ b/source/creator/creator_args.c @@ -76,13 +76,6 @@ #include "GPU_draw.h" -/* for passing information between creator and gameengine */ -#ifdef WITH_GAMEENGINE -# include "BL_System.h" -#else /* dummy */ -# define SYS_SystemHandle int -#endif - #ifdef WITH_LIBMV # include "libmv-capi.h" #endif @@ -511,11 +504,6 @@ static int arg_handle_print_help(int UNUSED(argc), const char **UNUSED(argv), vo BLI_argsPrintArgDoc(ba, "--start-console"); BLI_argsPrintArgDoc(ba, "--no-native-pixels"); - - printf("\n"); - printf("Game Engine Specific Options:\n"); - BLI_argsPrintArgDoc(ba, "-g"); - printf("\n"); printf("Python Options:\n"); BLI_argsPrintArgDoc(ba, "--enable-autoexec"); @@ -581,7 +569,6 @@ static int arg_handle_print_help(int UNUSED(argc), const char **UNUSED(argv), vo BLI_argsPrintArgDoc(ba, "--env-system-scripts"); BLI_argsPrintArgDoc(ba, "--env-system-python"); printf("\n"); - BLI_argsPrintArgDoc(ba, "-nojoystick"); BLI_argsPrintArgDoc(ba, "-noaudio"); BLI_argsPrintArgDoc(ba, "-setaudio"); @@ -1125,27 +1112,6 @@ static int arg_handle_register_extension(int UNUSED(argc), const char **UNUSED(a return 0; } -static const char arg_handle_joystick_disable_doc[] = -"\n\tDisable joystick support." -; -static int arg_handle_joystick_disable(int UNUSED(argc), const char **UNUSED(argv), void *data) -{ -#ifndef WITH_GAMEENGINE - (void)data; -#else - SYS_SystemHandle *syshandle = data; - - /** - * don't initialize joysticks if user doesn't want to use joysticks - * failed joystick initialization delays over 5 seconds, before game engine start - */ - SYS_WriteCommandLineInt(*syshandle, "nojoystick", 1); - if (G.debug & G_DEBUG) printf("disabling nojoystick\n"); -#endif - - return 0; -} - static const char arg_handle_audio_disable_doc[] = "\n\tForce sound system to None." ; @@ -1379,76 +1345,6 @@ static int arg_handle_extension_set(int argc, const char **argv, void *data) } } -static const char arg_handle_ge_parameters_set_doc[] = -"Game Engine specific options\n" -"\n" -"\t'fixedtime'\n" -"\t\tRun on 50 hertz without dropping frames.\n" -"\t'vertexarrays'\n" -"\t\tUse Vertex Arrays for rendering (usually faster).\n" -"\t'nomipmap'\n" -"\t\tNo Texture Mipmapping.\n" -"\t'linearmipmap'\n" -"\t\tLinear Texture Mipmapping instead of Nearest (default)." -; -static int arg_handle_ge_parameters_set(int argc, const char **argv, void *data) -{ - int a = 0; -#ifdef WITH_GAMEENGINE - SYS_SystemHandle syshandle = *(SYS_SystemHandle *)data; -#else - (void)data; -#endif - - /** - * gameengine parameters are automatically put into system - * -g [paramname = value] - * -g [boolparamname] - * example: - * -g novertexarrays - * -g maxvertexarraysize = 512 - */ - - if (argc >= 1) { - const char *paramname = argv[a]; - /* check for single value versus assignment */ - if (a + 1 < argc && (*(argv[a + 1]) == '=')) { - a++; - if (a + 1 < argc) { - a++; - /* assignment */ -#ifdef WITH_GAMEENGINE - SYS_WriteCommandLineString(syshandle, paramname, argv[a]); -#endif - } - else { - printf("Error: argument assignment (%s) without value.\n", paramname); - return 0; - } - /* name arg eaten */ - - } - else { -#ifdef WITH_GAMEENGINE - SYS_WriteCommandLineInt(syshandle, argv[a], 1); -#endif - /* doMipMap */ - if (STREQ(argv[a], "nomipmap")) { - GPU_set_mipmap(0); //doMipMap = 0; - } - /* linearMipMap */ - if (STREQ(argv[a], "linearmipmap")) { - GPU_set_mipmap(1); - GPU_set_linear_mipmap(1); //linearMipMap = 1; - } - - - } /* if (*(argv[a + 1]) == '=') */ - } - - return a; -} - static const char arg_handle_render_frame_doc[] = "\n" "\tRender frame and save it.\n" @@ -1890,7 +1786,7 @@ static int arg_handle_load_file(int UNUSED(argc), const char **argv, void *data) } -void main_args_setup(bContext *C, bArgs *ba, SYS_SystemHandle *syshandle) +void main_args_setup(bContext *C, bArgs *ba) { #define CB(a) a##_doc, a @@ -2004,12 +1900,10 @@ void main_args_setup(bContext *C, bArgs *ba, SYS_SystemHandle *syshandle) BLI_argsAdd(ba, 2, NULL, "--no-native-pixels", CB(arg_handle_native_pixels_set), ba); /* third pass: disabling things and forcing settings */ - BLI_argsAddCase(ba, 3, "-nojoystick", 1, NULL, 0, CB(arg_handle_joystick_disable), syshandle); BLI_argsAddCase(ba, 3, "-noaudio", 1, NULL, 0, CB(arg_handle_audio_disable), NULL); BLI_argsAddCase(ba, 3, "-setaudio", 1, NULL, 0, CB(arg_handle_audio_set), NULL); /* fourth pass: processing arguments */ - BLI_argsAdd(ba, 4, "-g", NULL, CB(arg_handle_ge_parameters_set), syshandle); BLI_argsAdd(ba, 4, "-f", "--render-frame", CB(arg_handle_render_frame), C); BLI_argsAdd(ba, 4, "-a", "--render-anim", CB(arg_handle_render_animation), C); BLI_argsAdd(ba, 4, "-S", "--scene", CB(arg_handle_scene_set), C); diff --git a/source/creator/creator_intern.h b/source/creator/creator_intern.h index a972a926677..311c8b74006 100644 --- a/source/creator/creator_intern.h +++ b/source/creator/creator_intern.h @@ -33,7 +33,7 @@ struct bContext; #ifndef WITH_PYTHON_MODULE /* creator_args.c */ -void main_args_setup(struct bContext *C, struct bArgs *ba, SYS_SystemHandle *syshandle); +void main_args_setup(struct bContext *C, struct bArgs *ba); void main_args_setup_post(struct bContext *C, struct bArgs *ba); diff --git a/source/creator/creator_signals.c b/source/creator/creator_signals.c index feb108da289..55f9777f55a 100644 --- a/source/creator/creator_signals.c +++ b/source/creator/creator_signals.c @@ -65,13 +65,6 @@ #include "BKE_report.h" -/* for passing information between creator and gameengine */ -#ifdef WITH_GAMEENGINE -# include "BL_System.h" -#else /* dummy */ -# define SYS_SystemHandle int -#endif - #include #include "creator_intern.h" /* own include */ diff --git a/source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp b/source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp deleted file mode 100644 index 4e8f0eba9b7..00000000000 --- a/source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp +++ /dev/null @@ -1,683 +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 ***** - * Blender's Ketsji startpoint - */ - -/** \file gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp - * \ingroup blroutines - */ - - -#include -#include -#include - -#ifdef _MSC_VER - /* don't show stl-warnings */ -# pragma warning (disable:4786) -#endif - -#include "GPU_glew.h" - -#include "KX_BlenderCanvas.h" -#include "KX_BlenderKeyboardDevice.h" -#include "KX_BlenderMouseDevice.h" -#include "KX_BlenderSystem.h" -#include "BL_Material.h" - -#include "KX_KetsjiEngine.h" -#include "KX_BlenderSceneConverter.h" -#include "KX_PythonInit.h" -#include "KX_PyConstraintBinding.h" -#include "KX_PythonMain.h" - -#include "RAS_OpenGLRasterizer.h" -#include "RAS_ListRasterizer.h" - -#include "NG_LoopBackNetworkDeviceInterface.h" - -#include "BL_System.h" - -#include "GPU_extensions.h" -#include "EXP_Value.h" - - -extern "C" { - #include "DNA_object_types.h" - #include "DNA_view3d_types.h" - #include "DNA_screen_types.h" - #include "DNA_userdef_types.h" - #include "DNA_scene_types.h" - #include "DNA_windowmanager_types.h" - - #include "BKE_global.h" - #include "BKE_report.h" - #include "BKE_ipo.h" - #include "BKE_main.h" - #include "BKE_context.h" - #include "BKE_sound.h" - - /* avoid c++ conflict with 'new' */ - #define new _new - #include "BKE_screen.h" - #undef new - - #include "MEM_guardedalloc.h" - - #include "BLI_blenlib.h" - #include "BLO_readfile.h" - - #include "../../blender/windowmanager/WM_types.h" - #include "../../blender/windowmanager/wm_window.h" - -/* avoid more includes (not used by BGE) */ -typedef void * wmUIHandlerFunc; -typedef void * wmUIHandlerRemoveFunc; - - #include "../../blender/windowmanager/wm_event_system.h" -} - -#ifdef WITH_AUDASPACE -# include -#endif - -static BlendFileData *load_game_data(const char *filename) -{ - ReportList reports; - BlendFileData *bfd; - - BKE_reports_init(&reports, RPT_STORE); - bfd= BLO_read_from_file(filename, &reports, BLO_READ_SKIP_USERDEF); - - if (!bfd) { - printf("Loading %s failed: ", filename); - BKE_reports_print(&reports, RPT_ERROR); - } - - BKE_reports_clear(&reports); - - return bfd; -} - -static int BL_KetsjiNextFrame(KX_KetsjiEngine *ketsjiengine, bContext *C, wmWindow *win, Scene *scene, ARegion *ar, - KX_BlenderKeyboardDevice* keyboarddevice, KX_BlenderMouseDevice* mousedevice, int draw_letterbox) -{ - int exitrequested; - - // first check if we want to exit - exitrequested = ketsjiengine->GetExitCode(); - - // kick the engine - bool render = ketsjiengine->NextFrame(); - - if (render) { - if (draw_letterbox) { - // Clear screen to border color - // We do this here since we set the canvas to be within the frames. This means the engine - // itself is unaware of the extra space, so we clear the whole region for it. - glClearColor(scene->gm.framing.col[0], scene->gm.framing.col[1], scene->gm.framing.col[2], 1.0f); - glViewport(ar->winrct.xmin, ar->winrct.ymin, - BLI_rcti_size_x(&ar->winrct), BLI_rcti_size_y(&ar->winrct)); - glClear(GL_COLOR_BUFFER_BIT); - } - - // render the frame - ketsjiengine->Render(); - } - - wm_window_process_events_nosleep(); - - // test for the ESC key - //XXX while (qtest()) - while (wmEvent *event= (wmEvent *)win->queue.first) { - short val = 0; - //unsigned short event = 0; //XXX extern_qread(&val); - unsigned int unicode = event->utf8_buf[0] ? BLI_str_utf8_as_unicode(event->utf8_buf) : event->ascii; - - if (keyboarddevice->ConvertBlenderEvent(event->type, event->val, unicode)) - exitrequested = KX_EXIT_REQUEST_BLENDER_ESC; - - /* Coordinate conversion... where - * should this really be? - */ - if (event->type == MOUSEMOVE) { - /* Note, not nice! XXX 2.5 event hack */ - val = event->x - ar->winrct.xmin; - mousedevice->ConvertBlenderEvent(MOUSEX, val, 0); - - val = ar->winy - (event->y - ar->winrct.ymin) - 1; - mousedevice->ConvertBlenderEvent(MOUSEY, val, 0); - } - else { - mousedevice->ConvertBlenderEvent(event->type, event->val, 0); - } - - BLI_remlink(&win->queue, event); - wm_event_free(event); - } - - if (win != CTX_wm_window(C)) { - exitrequested= KX_EXIT_REQUEST_OUTSIDE; /* window closed while bge runs */ - } - return exitrequested; -} - - -#ifdef WITH_PYTHON -static struct BL_KetsjiNextFrameState { - class KX_KetsjiEngine* ketsjiengine; - struct bContext *C; - struct wmWindow* win; - struct Scene* scene; - struct ARegion *ar; - KX_BlenderKeyboardDevice* keyboarddevice; - KX_BlenderMouseDevice* mousedevice; - int draw_letterbox; -} ketsjinextframestate; - -static int BL_KetsjiPyNextFrame(void *state0) -{ - BL_KetsjiNextFrameState *state = (BL_KetsjiNextFrameState *) state0; - return BL_KetsjiNextFrame( - state->ketsjiengine, - state->C, - state->win, - state->scene, - state->ar, - state->keyboarddevice, - state->mousedevice, - state->draw_letterbox); -} -#endif - - -extern "C" void StartKetsjiShell(struct bContext *C, struct ARegion *ar, rcti *cam_frame, int always_use_expand_framing) -{ - /* context values */ - struct wmWindowManager *wm= CTX_wm_manager(C); - struct wmWindow *win= CTX_wm_window(C); - struct Scene *startscene= CTX_data_scene(C); - struct Main* maggie1= CTX_data_main(C); - - - RAS_Rect area_rect; - area_rect.SetLeft(cam_frame->xmin); - area_rect.SetBottom(cam_frame->ymin); - area_rect.SetRight(cam_frame->xmax); - area_rect.SetTop(cam_frame->ymax); - - int exitrequested = KX_EXIT_REQUEST_NO_REQUEST; - Main* blenderdata = maggie1; - - char* startscenename = startscene->id.name+2; - char pathname[FILE_MAXDIR+FILE_MAXFILE], oldsce[FILE_MAXDIR+FILE_MAXFILE]; - STR_String exitstring = ""; - BlendFileData *bfd= NULL; - - BLI_strncpy(pathname, blenderdata->name, sizeof(pathname)); - BLI_strncpy(oldsce, G.main->name, sizeof(oldsce)); -#ifdef WITH_PYTHON - resetGamePythonPath(); // need this so running a second time wont use an old blendfiles path - setGamePythonPath(G.main->name); - - // Acquire Python's GIL (global interpreter lock) - // so we can safely run Python code and API calls - PyGILState_STATE gilstate = PyGILState_Ensure(); - - PyObject *pyGlobalDict = PyDict_New(); /* python utility storage, spans blend file loading */ -#endif - - // Globals to be carried on over blender files - GlobalSettings gs; - gs.matmode= startscene->gm.matmode; - gs.glslflag= startscene->gm.flag; - - do - { - View3D *v3d= CTX_wm_view3d(C); - RegionView3D *rv3d= CTX_wm_region_view3d(C); - - // get some preferences - SYS_SystemHandle syshandle = SYS_GetSystem(); - bool properties = (SYS_GetCommandLineInt(syshandle, "show_properties", 0) != 0); - bool usefixed = (SYS_GetCommandLineInt(syshandle, "fixedtime", 0) != 0); - bool profile = (SYS_GetCommandLineInt(syshandle, "show_profile", 0) != 0); - bool frameRate = (SYS_GetCommandLineInt(syshandle, "show_framerate", 0) != 0); - bool animation_record = (SYS_GetCommandLineInt(syshandle, "animation_record", 0) != 0); - bool displaylists = false; // (SYS_GetCommandLineInt(syshandle, "displaylists", 0) != 0) && GPU_display_list_support(); -#ifdef WITH_PYTHON - bool nodepwarnings = (SYS_GetCommandLineInt(syshandle, "ignore_deprecation_warnings", 0) != 0); -#endif - // bool novertexarrays = (SYS_GetCommandLineInt(syshandle, "novertexarrays", 0) != 0); - bool mouse_state = (startscene->gm.flag & GAME_SHOW_MOUSE) != 0; - bool restrictAnimFPS = (startscene->gm.flag & GAME_RESTRICT_ANIM_UPDATES) != 0; - - short drawtype = v3d->drawtype; - - /* we do not support material mode in game engine, force change to texture mode */ - if (drawtype == OB_MATERIAL) drawtype = OB_TEXTURE; - if (animation_record) usefixed= false; /* override since you don't want to run full-speed for sim recording */ - - // create the canvas and rasterizer - RAS_ICanvas* canvas = new KX_BlenderCanvas(wm, win, area_rect, ar); - - // default mouse state set on render panel - if (mouse_state) - canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL); - else - canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE); - - // Setup vsync - int previous_vsync = 0; - canvas->GetSwapInterval(previous_vsync); - if (startscene->gm.vsync == VSYNC_ADAPTIVE) - canvas->SetSwapInterval(-1); - else - canvas->SetSwapInterval((startscene->gm.vsync == VSYNC_ON) ? 1 : 0); - - RAS_IRasterizer* rasterizer = NULL; - RAS_STORAGE_TYPE raster_storage = RAS_AUTO_STORAGE; - - if (startscene->gm.raster_storage == RAS_STORE_VBO) { - raster_storage = RAS_VBO; - } - else if (startscene->gm.raster_storage == RAS_STORE_VA) { - raster_storage = RAS_VA; - } - //Don't use displaylists with VBOs - //If auto starts using VBOs, make sure to check for that here - if (displaylists && raster_storage != RAS_VBO) - rasterizer = new RAS_ListRasterizer(canvas, true, raster_storage); - else - rasterizer = new RAS_OpenGLRasterizer(canvas, raster_storage); - - RAS_IRasterizer::MipmapOption mipmapval = rasterizer->GetMipmapping(); - - - // create the inputdevices - KX_BlenderKeyboardDevice* keyboarddevice = new KX_BlenderKeyboardDevice(); - KX_BlenderMouseDevice* mousedevice = new KX_BlenderMouseDevice(); - - // create a networkdevice - NG_NetworkDeviceInterface* networkdevice = new - NG_LoopBackNetworkDeviceInterface(); - - // - // create a ketsji/blendersystem (only needed for timing and stuff) - KX_BlenderSystem* kxsystem = new KX_BlenderSystem(); - - // create the ketsjiengine - KX_KetsjiEngine* ketsjiengine = new KX_KetsjiEngine(kxsystem); - - // set the devices - ketsjiengine->SetKeyboardDevice(keyboarddevice); - ketsjiengine->SetMouseDevice(mousedevice); - ketsjiengine->SetNetworkDevice(networkdevice); - ketsjiengine->SetCanvas(canvas); - ketsjiengine->SetRasterizer(rasterizer); - ketsjiengine->SetUseFixedTime(usefixed); - ketsjiengine->SetTimingDisplay(frameRate, profile, properties); - ketsjiengine->SetRestrictAnimationFPS(restrictAnimFPS); - ketsjiengine->SetRender(true); - KX_KetsjiEngine::SetExitKey(ConvertKeyCode(startscene->gm.exitkey)); - - //set the global settings (carried over if restart/load new files) - ketsjiengine->SetGlobalSettings(&gs); - -#ifdef WITH_PYTHON - CValue::SetDeprecationWarnings(nodepwarnings); -#endif - - //lock frame and camera enabled - storing global values - int tmp_lay= startscene->lay; - Object *tmp_camera = startscene->camera; - - if (v3d->scenelock==0) { - startscene->lay= v3d->lay; - startscene->camera= v3d->camera; - } - - // some blender stuff - float camzoom = 1.0f; - int draw_letterbox = 0; - - if (rv3d->persp==RV3D_CAMOB) { - if (startscene->gm.framing.type == SCE_GAMEFRAMING_BARS) { /* Letterbox */ - draw_letterbox = 1; - } - else { - camzoom = 1.0f / BKE_screen_view3d_zoom_to_fac(rv3d->camzoom); - } - } - - rasterizer->SetDrawingMode(drawtype); - ketsjiengine->SetCameraZoom(camzoom); - ketsjiengine->SetCameraOverrideZoom(2.0f); - - // if we got an exitcode 3 (KX_EXIT_REQUEST_START_OTHER_GAME) load a different file - if (exitrequested == KX_EXIT_REQUEST_START_OTHER_GAME || exitrequested == KX_EXIT_REQUEST_RESTART_GAME) - { - exitrequested = KX_EXIT_REQUEST_NO_REQUEST; - if (bfd) BLO_blendfiledata_free(bfd); - - char basedpath[FILE_MAX]; - // base the actuator filename with respect - // to the original file working directory - - if (exitstring != "") - BLI_strncpy(basedpath, exitstring.ReadPtr(), sizeof(basedpath)); - - // load relative to the last loaded file, this used to be relative - // to the first file but that makes no sense, relative paths in - // blend files should be relative to that file, not some other file - // that happened to be loaded first - BLI_path_abs(basedpath, pathname); - bfd = load_game_data(basedpath); - - // if it wasn't loaded, try it forced relative - if (!bfd) - { - // just add "//" in front of it - char temppath[FILE_MAX] = "//"; - BLI_strncpy(temppath + 2, basedpath, FILE_MAX - 2); - - BLI_path_abs(temppath, pathname); - bfd = load_game_data(temppath); - } - - // if we got a loaded blendfile, proceed - if (bfd) - { - blenderdata = bfd->main; - startscenename = bfd->curscene->id.name + 2; - - if (blenderdata) { - BLI_strncpy(G.main->name, blenderdata->name, sizeof(G.main->name)); - BLI_strncpy(pathname, blenderdata->name, sizeof(pathname)); -#ifdef WITH_PYTHON - setGamePythonPath(G.main->name); -#endif - } - } - // else forget it, we can't find it - else - { - exitrequested = KX_EXIT_REQUEST_QUIT_GAME; - } - } - - Scene *scene= bfd ? bfd->curscene : (Scene *)BLI_findstring(&blenderdata->scene, startscenename, offsetof(ID, name) + 2); - - if (scene) - { - int startFrame = scene->r.cfra; - ketsjiengine->SetAnimRecordMode(animation_record, startFrame); - - // Quad buffered needs a special window. - if (scene->gm.stereoflag == STEREO_ENABLED) { - if (scene->gm.stereomode != RAS_IRasterizer::RAS_STEREO_QUADBUFFERED) - rasterizer->SetStereoMode((RAS_IRasterizer::StereoMode) scene->gm.stereomode); - - rasterizer->SetEyeSeparation(scene->gm.eyeseparation); - } - - rasterizer->SetBackColor(scene->gm.framing.col); - } - - if (exitrequested != KX_EXIT_REQUEST_QUIT_GAME) - { - if (rv3d->persp != RV3D_CAMOB) - { - ketsjiengine->EnableCameraOverride(startscenename); - ketsjiengine->SetCameraOverrideUseOrtho((rv3d->persp == RV3D_ORTHO)); - ketsjiengine->SetCameraOverrideProjectionMatrix(MT_CmMatrix4x4(rv3d->winmat)); - ketsjiengine->SetCameraOverrideViewMatrix(MT_CmMatrix4x4(rv3d->viewmat)); - ketsjiengine->SetCameraOverrideClipping(v3d->near, v3d->far); - ketsjiengine->SetCameraOverrideLens(v3d->lens); - } - - // create a scene converter, create and convert the startingscene - KX_ISceneConverter* sceneconverter = new KX_BlenderSceneConverter(blenderdata, ketsjiengine); - ketsjiengine->SetSceneConverter(sceneconverter); - if (always_use_expand_framing) - sceneconverter->SetAlwaysUseExpandFraming(true); - - sceneconverter->SetMaterials(true); - - if (gs.matmode == GAME_MAT_GLSL) - sceneconverter->SetGLSLMaterials(true); - if (scene->gm.flag & GAME_NO_MATERIAL_CACHING) - sceneconverter->SetCacheMaterials(false); - - KX_Scene* startscene = new KX_Scene(keyboarddevice, - mousedevice, - networkdevice, - startscenename, - scene, - canvas); - -#ifdef WITH_PYTHON - // some python things - PyObject *gameLogic, *gameLogic_keys; - setupGamePython(ketsjiengine, startscene, blenderdata, pyGlobalDict, &gameLogic, &gameLogic_keys, 0, NULL); -#endif // WITH_PYTHON - - //initialize Dome Settings - if (scene->gm.stereoflag == STEREO_DOME) - ketsjiengine->InitDome(scene->gm.dome.res, scene->gm.dome.mode, scene->gm.dome.angle, scene->gm.dome.resbuf, scene->gm.dome.tilt, scene->gm.dome.warptext); - - // initialize 3D Audio Settings - AUD_Device* device = BKE_sound_get_device(); - AUD_Device_setSpeedOfSound(device, scene->audio.speed_of_sound); - AUD_Device_setDopplerFactor(device, scene->audio.doppler_factor); - AUD_Device_setDistanceModel(device, AUD_DistanceModel(scene->audio.distance_model)); - - // from see blender.c: - // FIXME: this version patching should really be part of the file-reading code, - // but we still get too many unrelated data-corruption crashes otherwise... - if (blenderdata->versionfile < 250) - do_versions_ipos_to_animato(blenderdata); - - if (sceneconverter) - { - // convert and add scene - sceneconverter->ConvertScene( - startscene, - rasterizer, - canvas); - ketsjiengine->AddScene(startscene); - - // init the rasterizer - rasterizer->Init(); - - // start the engine - ketsjiengine->StartEngine(true); - - - // Set the animation playback rate for ipo's and actions - // the framerate below should patch with FPS macro defined in blendef.h - // Could be in StartEngine set the framerate, we need the scene to do this - ketsjiengine->SetAnimFrameRate(FPS); - -#ifdef WITH_PYTHON - char *python_main = NULL; - pynextframestate.state = NULL; - pynextframestate.func = NULL; - python_main = KX_GetPythonMain(scene); - - // the mainloop - printf("\nBlender Game Engine Started\n"); - if (python_main) { - char *python_code = KX_GetPythonCode(blenderdata, python_main); - if (python_code) { - // Set python environement variable. - KX_SetActiveScene(startscene); - PHY_SetActiveEnvironment(startscene->GetPhysicsEnvironment()); - - ketsjinextframestate.ketsjiengine = ketsjiengine; - ketsjinextframestate.C = C; - ketsjinextframestate.win = win; - ketsjinextframestate.scene = scene; - ketsjinextframestate.ar = ar; - ketsjinextframestate.keyboarddevice = keyboarddevice; - ketsjinextframestate.mousedevice = mousedevice; - ketsjinextframestate.draw_letterbox = draw_letterbox; - - pynextframestate.state = &ketsjinextframestate; - pynextframestate.func = &BL_KetsjiPyNextFrame; - printf("Yielding control to Python script '%s'...\n", python_main); - PyRun_SimpleString(python_code); - printf("Exit Python script '%s'\n", python_main); - MEM_freeN(python_code); - } - } - else -#endif /* WITH_PYTHON */ - { - while (!exitrequested) - { - exitrequested = BL_KetsjiNextFrame(ketsjiengine, C, win, scene, ar, keyboarddevice, mousedevice, draw_letterbox); - } - } - printf("Blender Game Engine Finished\n"); - exitstring = ketsjiengine->GetExitString(); -#ifdef WITH_PYTHON - if (python_main) MEM_freeN(python_main); -#endif /* WITH_PYTHON */ - - gs = *(ketsjiengine->GetGlobalSettings()); - - // when exiting the mainloop -#ifdef WITH_PYTHON - // Clears the dictionary by hand: - // This prevents, extra references to global variables - // inside the GameLogic dictionary when the python interpreter is finalized. - // which allows the scene to safely delete them :) - // see: (space.c)->start_game - - //PyDict_Clear(PyModule_GetDict(gameLogic)); - - // Keep original items, means python plugins will autocomplete members - PyObject *gameLogic_keys_new = PyDict_Keys(PyModule_GetDict(gameLogic)); - const Py_ssize_t numitems= PyList_GET_SIZE(gameLogic_keys_new); - Py_ssize_t listIndex; - for (listIndex=0; listIndex < numitems; listIndex++) { - PyObject *item = PyList_GET_ITEM(gameLogic_keys_new, listIndex); - if (!PySequence_Contains(gameLogic_keys, item)) { - PyDict_DelItem( PyModule_GetDict(gameLogic), item); - } - } - Py_DECREF(gameLogic_keys_new); - gameLogic_keys_new = NULL; -#endif - ketsjiengine->StopEngine(); -#ifdef WITH_PYTHON - exitGamePythonScripting(); -#endif - networkdevice->Disconnect(); - } - if (sceneconverter) - { - delete sceneconverter; - sceneconverter = NULL; - } - -#ifdef WITH_PYTHON - Py_DECREF(gameLogic_keys); - gameLogic_keys = NULL; -#endif - } - //lock frame and camera enabled - restoring global values - if (v3d->scenelock==0) { - startscene->lay= tmp_lay; - startscene->camera= tmp_camera; - } - - if (exitrequested != KX_EXIT_REQUEST_OUTSIDE) - { - // set the cursor back to normal - canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL); - - // set mipmap setting back to its original value - rasterizer->SetMipmapping(mipmapval); - } - - // clean up some stuff - if (ketsjiengine) - { - delete ketsjiengine; - ketsjiengine = NULL; - } - if (kxsystem) - { - delete kxsystem; - kxsystem = NULL; - } - if (networkdevice) - { - delete networkdevice; - networkdevice = NULL; - } - if (keyboarddevice) - { - delete keyboarddevice; - keyboarddevice = NULL; - } - if (mousedevice) - { - delete mousedevice; - mousedevice = NULL; - } - if (rasterizer) - { - delete rasterizer; - rasterizer = NULL; - } - if (canvas) - { - canvas->SetSwapInterval(previous_vsync); // Set the swap interval back - delete canvas; - canvas = NULL; - } - - // stop all remaining playing sounds - AUD_Device_stopAll(BKE_sound_get_device()); - - } while (exitrequested == KX_EXIT_REQUEST_RESTART_GAME || exitrequested == KX_EXIT_REQUEST_START_OTHER_GAME); - - if (bfd) BLO_blendfiledata_free(bfd); - - BLI_strncpy(G.main->name, oldsce, sizeof(G.main->name)); - -#ifdef WITH_PYTHON - PyDict_Clear(pyGlobalDict); - Py_DECREF(pyGlobalDict); - - // Release Python's GIL - PyGILState_Release(gilstate); -#endif - -} diff --git a/source/gameengine/BlenderRoutines/BL_System.cpp b/source/gameengine/BlenderRoutines/BL_System.cpp deleted file mode 100644 index 251182a07aa..00000000000 --- a/source/gameengine/BlenderRoutines/BL_System.cpp +++ /dev/null @@ -1,102 +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 ***** - * Interface to the commandline arguments - */ - -/** \file gameengine/BlenderRoutines/BL_System.cpp - * \ingroup blroutines - */ - -#include "CTR_Map.h" -#include "STR_HashedString.h" -#include "BL_System.h" - -struct SingletonSystem { - CTR_Map int_params; - CTR_Map float_params; - CTR_Map string_params; -}; - -static SingletonSystem *_system_instance = NULL; - -SYS_SystemHandle SYS_GetSystem() -{ - if (!_system_instance) - _system_instance = new SingletonSystem(); - - return (SYS_SystemHandle)_system_instance; -} - -void SYS_DeleteSystem(SYS_SystemHandle sys) -{ - if (_system_instance) { - delete _system_instance; - _system_instance = NULL; - } -} - -int SYS_GetCommandLineInt(SYS_SystemHandle sys, const char *paramname, int defaultvalue) -{ - int *result = ((SingletonSystem *)sys)->int_params[paramname]; - if (result) - return *result; - - return defaultvalue; -} - -float SYS_GetCommandLineFloat(SYS_SystemHandle sys, const char *paramname, float defaultvalue) -{ - float *result = ((SingletonSystem *)sys)->float_params[paramname]; - if (result) - return *result; - - return defaultvalue; -} - -const char *SYS_GetCommandLineString(SYS_SystemHandle sys, const char *paramname, const char *defaultvalue) -{ - STR_String *result = ((SingletonSystem *)sys)->string_params[paramname]; - if (result) - return *result; - - return defaultvalue; -} - -void SYS_WriteCommandLineInt(SYS_SystemHandle sys, const char *paramname, int value) -{ - ((SingletonSystem *)sys)->int_params.insert(paramname, value); -} - -void SYS_WriteCommandLineFloat(SYS_SystemHandle sys, const char *paramname, float value) -{ - ((SingletonSystem *)sys)->float_params.insert(paramname, value); -} - -void SYS_WriteCommandLineString(SYS_SystemHandle sys, const char *paramname, const char *value) -{ - ((SingletonSystem *)sys)->string_params.insert(paramname, value); -} - diff --git a/source/gameengine/BlenderRoutines/BL_System.h b/source/gameengine/BlenderRoutines/BL_System.h deleted file mode 100644 index b9f51393f44..00000000000 --- a/source/gameengine/BlenderRoutines/BL_System.h +++ /dev/null @@ -1,70 +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 ***** - * System specific information / access. - * Interface to the commandline arguments - */ - -/** \file gameengine/BlenderRoutines/BL_System.h - * \ingroup blroutines - */ - -#ifndef __BL_SYSTEM_H__ -#define __BL_SYSTEM_H__ - -#ifdef __cplusplus -extern "C" { -#endif - -/* Game Engine command line parameters */ - -typedef void* SYS_SystemHandle; - -extern SYS_SystemHandle SYS_GetSystem(void); -extern void SYS_DeleteSystem(SYS_SystemHandle sys); - -extern int SYS_GetCommandLineInt(SYS_SystemHandle sys, const char *paramname, int defaultvalue); -extern float SYS_GetCommandLineFloat(SYS_SystemHandle sys, const char *paramname, float defaultvalue); -extern const char *SYS_GetCommandLineString(SYS_SystemHandle sys, const char *paramname, const char *defaultvalue); - -extern void SYS_WriteCommandLineInt(SYS_SystemHandle sys, const char *paramname, int value); -extern void SYS_WriteCommandLineFloat(SYS_SystemHandle sys, const char *paramname, float value); -extern void SYS_WriteCommandLineString(SYS_SystemHandle sys, const char *paramname, const char *value); - -/* Start game engine */ - -struct bContext; -struct ARegion; -struct rcti; - -extern void StartKetsjiShell(struct bContext *C, struct ARegion *ar, - struct rcti *cam_frame, int always_use_expand_framing); - -#ifdef __cplusplus -} -#endif - -#endif /* __BL_SYSTEM_H__ */ - diff --git a/source/gameengine/BlenderRoutines/CMakeLists.txt b/source/gameengine/BlenderRoutines/CMakeLists.txt deleted file mode 100644 index 42293050753..00000000000 --- a/source/gameengine/BlenderRoutines/CMakeLists.txt +++ /dev/null @@ -1,78 +0,0 @@ - -set(INC - . - ../Converter - ../Expressions - ../GameLogic - ../Ketsji - ../Network - ../Network/LoopBackNetwork - ../Physics/Bullet - ../Physics/common - ../Rasterizer - ../Rasterizer/RAS_OpenGLRasterizer - ../SceneGraph - ../../blender - ../../blender/blenfont - ../../blender/blenkernel - ../../blender/blenlib - ../../blender/blenloader - ../../blender/editors/include - ../../blender/gpu - ../../blender/imbuf - ../../blender/makesdna - ../../blender/makesrna - ../../blender/windowmanager - ../../../intern/container - ../../../intern/glew-mx - ../../../intern/guardedalloc - ../../../intern/string -) - -set(INC_SYS - ../../../intern/moto/include - ${PTHREADS_INCLUDE_DIRS} - ${GLEW_INCLUDE_PATH} - ${BOOST_INCLUDE_DIR} -) - -set(SRC - BL_KetsjiEmbedStart.cpp - BL_System.cpp - KX_BlenderCanvas.cpp - KX_BlenderInputDevice.cpp - KX_BlenderKeyboardDevice.cpp - KX_BlenderMouseDevice.cpp - KX_BlenderSystem.cpp - - BL_System.h - KX_BlenderCanvas.h - KX_BlenderInputDevice.h - KX_BlenderKeyboardDevice.h - KX_BlenderMouseDevice.h - KX_BlenderSystem.h -) - -add_definitions(${GL_DEFINITIONS}) - -if(WITH_AUDASPACE) - add_definitions(-DWITH_AUDASPACE) - - list(APPEND INC_SYS - ${AUDASPACE_C_INCLUDE_DIRS} - ) -endif() - -if(WITH_CODEC_FFMPEG) - add_definitions(-DWITH_FFMPEG) -endif() - -if(WITH_BULLET) - list(APPEND INC_SYS - ${BULLET_INCLUDE_DIRS} - ) - add_definitions(-DWITH_BULLET) -endif() - - -blender_add_lib(ge_blen_routines "${SRC}" "${INC}" "${INC_SYS}") diff --git a/source/gameengine/BlenderRoutines/KX_BlenderCanvas.cpp b/source/gameengine/BlenderRoutines/KX_BlenderCanvas.cpp deleted file mode 100644 index 6fdc823ba1a..00000000000 --- a/source/gameengine/BlenderRoutines/KX_BlenderCanvas.cpp +++ /dev/null @@ -1,352 +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/BlenderRoutines/KX_BlenderCanvas.cpp - * \ingroup blroutines - */ - -#include "GPU_glew.h" - -#include "MEM_guardedalloc.h" - -#include "KX_BlenderCanvas.h" - -#include "DNA_screen_types.h" -#include "DNA_scene_types.h" -#include "DNA_windowmanager_types.h" - -#include "BKE_image.h" - -#include -#include - -extern "C" { -#include "WM_api.h" -#include "wm_cursors.h" -#include "wm_window.h" -} - -KX_BlenderCanvas::KX_BlenderCanvas(wmWindowManager *wm, wmWindow *win, RAS_Rect &rect, struct ARegion *ar) : -m_wm(wm), -m_win(win), -m_frame_rect(rect) -{ - // initialize area so that it's available for game logic on frame 1 (ImageViewport) - m_area_rect = rect; - // area boundaries needed for mouse coordinates in Letterbox framing mode - m_area_left = ar->winrct.xmin; - m_area_top = ar->winrct.ymax; - m_frame = 1; - - glGetIntegerv(GL_VIEWPORT, (GLint *)m_viewport); -} - -KX_BlenderCanvas::~KX_BlenderCanvas() -{ -} - -void KX_BlenderCanvas::Init() -{ - glDepthFunc(GL_LEQUAL); -} - - -void KX_BlenderCanvas::SwapBuffers() -{ - wm_window_swap_buffers(m_win); -} - -void KX_BlenderCanvas::SetSwapInterval(int interval) -{ - wm_window_set_swap_interval(m_win, interval); -} - -bool KX_BlenderCanvas::GetSwapInterval(int &intervalOut) -{ - return wm_window_get_swap_interval(m_win, &intervalOut); -} - -void KX_BlenderCanvas::GetDisplayDimensions(int &width, int &height) -{ - wm_get_screensize(&width, &height); -} - -void KX_BlenderCanvas::ResizeWindow(int width, int height) -{ - // Not implemented for the embedded player -} - -void KX_BlenderCanvas::SetFullScreen(bool enable) -{ - // Not implemented for the embedded player -} - -bool KX_BlenderCanvas::GetFullScreen() -{ - // Not implemented for the embedded player - return false; -} - -bool KX_BlenderCanvas::BeginDraw() -{ - // in case of multi-window we need to ensure we are drawing to the correct - // window always, because it may change in window event handling - wm_window_make_drawable(m_wm, m_win); - return true; -} - - -void KX_BlenderCanvas::EndDraw() -{ - // nothing needs to be done here -} - -void KX_BlenderCanvas::BeginFrame() -{ - glEnable(GL_DEPTH_TEST); - glDepthFunc(GL_LEQUAL); -} - - -void KX_BlenderCanvas::EndFrame() -{ - glDisable(GL_FOG); -} - - - -void KX_BlenderCanvas::ClearColor(float r,float g,float b,float a) -{ - glClearColor(r,g,b,a); -} - - - -void KX_BlenderCanvas::ClearBuffer(int type) -{ - int ogltype = 0; - - if (type & RAS_ICanvas::COLOR_BUFFER ) - ogltype |= GL_COLOR_BUFFER_BIT; - - if (type & RAS_ICanvas::DEPTH_BUFFER ) - ogltype |= GL_DEPTH_BUFFER_BIT; - glClear(ogltype); -} - -int KX_BlenderCanvas::GetWidth( -) const { - return m_frame_rect.GetWidth(); -} - -int KX_BlenderCanvas::GetHeight( -) const { - return m_frame_rect.GetHeight(); -} - -int KX_BlenderCanvas::GetMouseX(int x) -{ - int left = GetWindowArea().GetLeft(); - return x - (left - m_area_left); -} - -int KX_BlenderCanvas::GetMouseY(int y) -{ - int top = GetWindowArea().GetTop(); - return y - (m_area_top - top); -} - -float KX_BlenderCanvas::GetMouseNormalizedX(int x) -{ - int can_x = GetMouseX(x); - return float(can_x)/this->GetWidth(); -} - -float KX_BlenderCanvas::GetMouseNormalizedY(int y) -{ - int can_y = GetMouseY(y); - return float(can_y)/this->GetHeight(); -} - -RAS_Rect & -KX_BlenderCanvas:: -GetWindowArea( -) { - return m_area_rect; -} - - void -KX_BlenderCanvas:: -SetViewPort( - int x1, int y1, - int x2, int y2 -) { - /* x1 and y1 are the min pixel coordinate (e.g. 0) - * x2 and y2 are the max pixel coordinate - * the width,height is calculated including both pixels - * therefore: max - min + 1 - */ - int vp_width = (x2 - x1) + 1; - int vp_height = (y2 - y1) + 1; - int minx = m_frame_rect.GetLeft(); - int miny = m_frame_rect.GetBottom(); - - m_area_rect.SetLeft(minx + x1); - m_area_rect.SetBottom(miny + y1); - m_area_rect.SetRight(minx + x2); - m_area_rect.SetTop(miny + y2); - - m_viewport[0] = minx+x1; - m_viewport[1] = miny+y1; - m_viewport[2] = vp_width; - m_viewport[3] = vp_height; - - glViewport(minx + x1, miny + y1, vp_width, vp_height); - glScissor(minx + x1, miny + y1, vp_width, vp_height); -} - - void -KX_BlenderCanvas:: -UpdateViewPort( - int x1, int y1, - int x2, int y2 -) { - m_viewport[0] = x1; - m_viewport[1] = y1; - m_viewport[2] = x2; - m_viewport[3] = y2; -} - - const int* -KX_BlenderCanvas:: -GetViewPort() { -#ifdef DEBUG - // If we're in a debug build, we might as well make sure our values don't differ - // from what the gpu thinks we have. This could lead to nasty, hard to find bugs. - int viewport[4]; - glGetIntegerv(GL_VIEWPORT, viewport); - assert(viewport[0] == m_viewport[0]); - assert(viewport[1] == m_viewport[1]); - assert(viewport[2] == m_viewport[2]); - assert(viewport[3] == m_viewport[3]); -#endif - - return m_viewport; -} - -void KX_BlenderCanvas::SetMouseState(RAS_MouseState mousestate) -{ - m_mousestate = mousestate; - - switch (mousestate) - { - case MOUSE_INVISIBLE: - { - WM_cursor_set(m_win, CURSOR_NONE); - break; - } - case MOUSE_WAIT: - { - WM_cursor_set(m_win, CURSOR_WAIT); - break; - } - case MOUSE_NORMAL: - { - WM_cursor_set(m_win, CURSOR_STD); - break; - } - default: - { - } - } -} - - - -// (0,0) is top left, (width,height) is bottom right -void KX_BlenderCanvas::SetMousePosition(int x,int y) -{ - int winX = m_frame_rect.GetLeft(); - int winY = m_frame_rect.GetBottom(); - int winH = m_frame_rect.GetHeight(); - - WM_cursor_warp(m_win, winX + x, winY + (winH-y)); -} - - -/* get shot from frontbuffer sort of a copy from screendump.c */ -static unsigned int *screenshot(ScrArea *curarea, int *dumpsx, int *dumpsy) -{ - int x=0, y=0; - unsigned int *dumprect= NULL; - - x= curarea->totrct.xmin; - y= curarea->totrct.ymin; - *dumpsx= curarea->totrct.xmax-x; - *dumpsy= curarea->totrct.ymax-y; - - if (*dumpsx && *dumpsy) { - - dumprect= (unsigned int *)MEM_mallocN(sizeof(int) * (*dumpsx) * (*dumpsy), "dumprect"); - glReadBuffer(GL_FRONT); - glReadPixels(x, y, *dumpsx, *dumpsy, GL_RGBA, GL_UNSIGNED_BYTE, dumprect); - glFinish(); - glReadBuffer(GL_BACK); - } - - return dumprect; -} - -void KX_BlenderCanvas::MakeScreenShot(const char *filename) -{ - ScrArea area_dummy= {0}; - unsigned int *dumprect; - int dumpsx, dumpsy; - - area_dummy.totrct.xmin = m_frame_rect.GetLeft(); - area_dummy.totrct.xmax = m_frame_rect.GetRight(); - area_dummy.totrct.ymin = m_frame_rect.GetBottom(); - area_dummy.totrct.ymax = m_frame_rect.GetTop(); - - dumprect = screenshot(&area_dummy, &dumpsx, &dumpsy); - if (!dumprect) { - std::cerr << "KX_BlenderCanvas: Unable to take screenshot!" << std::endl; - return; - } - - /* initialize image file format data */ - Scene *scene = WM_window_get_active_scene(m_win); - ImageFormatData *im_format = (ImageFormatData *)MEM_mallocN(sizeof(ImageFormatData), "im_format"); - - if (scene) - *im_format = scene->r.im_format; - else - BKE_imformat_defaults(im_format); - - /* save_screenshot() frees dumprect and im_format */ - save_screenshot(filename, dumpsx, dumpsy, dumprect, im_format); -} diff --git a/source/gameengine/BlenderRoutines/KX_BlenderCanvas.h b/source/gameengine/BlenderRoutines/KX_BlenderCanvas.h deleted file mode 100644 index 6f408f86551..00000000000 --- a/source/gameengine/BlenderRoutines/KX_BlenderCanvas.h +++ /dev/null @@ -1,222 +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_BlenderCanvas.h - * \ingroup blroutines - */ - -#ifndef __KX_BLENDERCANVAS_H__ -#define __KX_BLENDERCANVAS_H__ - -#ifdef WIN32 -#include -#endif - -#include "RAS_ICanvas.h" -#include "RAS_Rect.h" - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -struct ARegion; -struct wmWindow; -struct wmWindowManager; - -/** - * 2D Blender device context abstraction. - * The connection from 3d rendercontext to 2d Blender surface embedding. - */ - -class KX_BlenderCanvas : public RAS_ICanvas -{ -private: - /** - * Rect that defines the area used for rendering, - * relative to the context */ - RAS_Rect m_displayarea; - int m_viewport[4]; - -public: - /* Construct a new canvas. - * - * \param area The Blender ARegion to run the game within. - */ - KX_BlenderCanvas(struct wmWindowManager *wm, struct wmWindow* win, RAS_Rect &rect, struct ARegion* ar); - ~KX_BlenderCanvas(); - - void - Init( - ); - - void - SwapBuffers( - ); - - void - SetSwapInterval( - int interval - ); - - bool - GetSwapInterval( - int &intervalOut - ); - - void GetDisplayDimensions(int &width, int &height); - - void - ResizeWindow( - int width, - int height - ); - - void - SetFullScreen( - bool enable - ); - - bool - GetFullScreen(); - - void - BeginFrame( - ); - - void - EndFrame( - ); - - void - ClearColor( - float r, - float g, - float b, - float a - ); - - void - ClearBuffer( - int type - ); - - int - GetWidth( - ) const; - - int - GetHeight( - ) const; - - int - GetMouseX(int x - ); - - int - GetMouseY(int y - ); - - float - GetMouseNormalizedX(int x - ); - - float - GetMouseNormalizedY(int y - ); - - const - RAS_Rect & - GetDisplayArea( - ) const { - return m_displayarea; - }; - - void - SetDisplayArea(RAS_Rect *rect - ) { - m_displayarea= *rect; - }; - - RAS_Rect & - GetWindowArea( - ); - - void - SetViewPort( - int x1, int y1, - int x2, int y2 - ); - - void - UpdateViewPort( - int x1, int y1, - int x2, int y2 - ); - - const int* - GetViewPort(); - - void - SetMouseState( - RAS_MouseState mousestate - ); - - void - SetMousePosition( - int x, - int y - ); - - void - MakeScreenShot( - const char* filename - ); - - bool - BeginDraw( - ); - - void - EndDraw( - ); - -private: - /** Blender area the game engine is running within */ - struct wmWindowManager *m_wm; - struct wmWindow* m_win; - RAS_Rect m_frame_rect; - RAS_Rect m_area_rect; - int m_area_left; - int m_area_top; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_BlenderCanvas") -#endif -}; - -#endif /* __KX_BLENDERCANVAS_H__ */ diff --git a/source/gameengine/BlenderRoutines/KX_BlenderInputDevice.cpp b/source/gameengine/BlenderRoutines/KX_BlenderInputDevice.cpp deleted file mode 100644 index 8d224051df4..00000000000 --- a/source/gameengine/BlenderRoutines/KX_BlenderInputDevice.cpp +++ /dev/null @@ -1,33 +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/BlenderRoutines/KX_BlenderInputDevice.cpp - * \ingroup blroutines - */ - -#include "KX_BlenderInputDevice.h" - diff --git a/source/gameengine/BlenderRoutines/KX_BlenderInputDevice.h b/source/gameengine/BlenderRoutines/KX_BlenderInputDevice.h deleted file mode 100644 index a936f328545..00000000000 --- a/source/gameengine/BlenderRoutines/KX_BlenderInputDevice.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_BlenderInputDevice.h - * \ingroup blroutines - */ - -#ifndef __KX_BLENDERINPUTDEVICE_H__ -#define __KX_BLENDERINPUTDEVICE_H__ - -#ifdef _MSC_VER -# pragma warning(disable:4786) // shut off 255 char limit debug template warning -#endif - -#include - -#include "wm_event_types.h" -#include "WM_types.h" -#include "SCA_IInputDevice.h" -#include "BL_BlenderDataConversion.h" - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -/** - * Base Class for Blender specific inputdevices. - * Blender specific inputdevices are used when the gameengine is running in embedded mode instead of standalone mode. - */ -class BL_BlenderInputDevice : public SCA_IInputDevice -{ -public: - BL_BlenderInputDevice() - { - } - - virtual ~BL_BlenderInputDevice() - { - - } - - KX_EnumInputs ToNative(unsigned short incode) { - return ConvertKeyCode(incode); - } - - virtual bool IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode)=0; - // virtual const SCA_InputEvent& GetEventValue(SCA_IInputDevice::KX_EnumInputs inputcode)=0; - virtual bool ConvertBlenderEvent(unsigned short incode, short val, unsigned int unicode)=0; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_BlenderInputDevice") -#endif -}; - -#endif /* __KX_BLENDERINPUTDEVICE_H__ */ diff --git a/source/gameengine/BlenderRoutines/KX_BlenderKeyboardDevice.cpp b/source/gameengine/BlenderRoutines/KX_BlenderKeyboardDevice.cpp deleted file mode 100644 index ea78d2d389e..00000000000 --- a/source/gameengine/BlenderRoutines/KX_BlenderKeyboardDevice.cpp +++ /dev/null @@ -1,169 +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/BlenderRoutines/KX_BlenderKeyboardDevice.cpp - * \ingroup blroutines - */ - - -#ifdef _MSC_VER - /* annoying warnings about truncated STL debug info */ -# pragma warning (disable:4786) -#endif - -#include "KX_BlenderKeyboardDevice.h" -#include "KX_KetsjiEngine.h" - -KX_BlenderKeyboardDevice::KX_BlenderKeyboardDevice() - : m_hookesc(false) -{ - -} -KX_BlenderKeyboardDevice::~KX_BlenderKeyboardDevice() -{ - -} - -/** - * IsPressed gives boolean information about keyboard status, true if pressed, false if not - */ - -bool KX_BlenderKeyboardDevice::IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode) -{ - const SCA_InputEvent & inevent = m_eventStatusTables[m_currentTable][inputcode]; - bool pressed = (inevent.m_status == SCA_InputEvent::KX_JUSTACTIVATED || - inevent.m_status == SCA_InputEvent::KX_ACTIVE); - return pressed; -} -/*const SCA_InputEvent& KX_BlenderKeyboardDevice::GetEventValue(SCA_IInputDevice::KX_EnumInputs inputcode) -{ - return m_eventStatusTables[m_currentTable][inputcode]; -} -*/ -/** - * NextFrame toggles currentTable with previousTable, - * and copy relevant event information from previous to current - * (pressed keys need to be remembered) - */ -void KX_BlenderKeyboardDevice::NextFrame() -{ - SCA_IInputDevice::NextFrame(); - - // now convert justpressed keyevents into regular (active) keyevents - int previousTable = 1-m_currentTable; - for (int keyevent= KX_BEGINKEY; keyevent<= KX_ENDKEY;keyevent++) - { - SCA_InputEvent& oldevent = m_eventStatusTables[previousTable][keyevent]; - if (oldevent.m_status == SCA_InputEvent::KX_JUSTACTIVATED || - oldevent.m_status == SCA_InputEvent::KX_ACTIVE ) - { - m_eventStatusTables[m_currentTable][keyevent] = oldevent; - m_eventStatusTables[m_currentTable][keyevent].m_status = SCA_InputEvent::KX_ACTIVE; - } - } -} - -/** - * ConvertBlenderEvent translates blender keyboard events into ketsji kbd events - * extra event information is stored, like ramp-mode (just released/pressed) -*/ -bool KX_BlenderKeyboardDevice::ConvertBlenderEvent(unsigned short incode, short val, unsigned int unicode) -{ - bool result = false; - - // convert event - KX_EnumInputs kxevent = this->ToNative(incode); - - // only process it, if it's a key - if (kxevent >= KX_BEGINKEY && kxevent <= KX_ENDKEY) - { - int previousTable = 1-m_currentTable; - - if (val == KM_PRESS || val == KM_DBL_CLICK) - { - if (kxevent == KX_KetsjiEngine::GetExitKey() && val != 0 && !m_hookesc) - result = true; - if (kxevent == KX_PAUSEKEY && val && (IsPressed(KX_LEFTCTRLKEY) || IsPressed(KX_RIGHTCTRLKEY))) - result = true; - - // todo: convert val ?? - m_eventStatusTables[m_currentTable][kxevent].m_eventval = val ; //??? - m_eventStatusTables[m_currentTable][kxevent].m_unicode = unicode; - - switch (m_eventStatusTables[previousTable][kxevent].m_status) - { - case SCA_InputEvent::KX_JUSTACTIVATED: - { - m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_ACTIVE; - break; - } - case SCA_InputEvent::KX_ACTIVE: - - { - m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_ACTIVE; - break; - } - case SCA_InputEvent::KX_NO_INPUTSTATUS: - { - m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_JUSTACTIVATED; - break; - } - default: - { - m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_JUSTACTIVATED; - } - } - - } else if (val == KM_RELEASE) - { - // blender eventval == 0 - switch (m_eventStatusTables[previousTable][kxevent].m_status) - { - case SCA_InputEvent::KX_JUSTACTIVATED: - { - m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_JUSTRELEASED; - break; - } - case SCA_InputEvent::KX_ACTIVE: - { - m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_JUSTRELEASED; - break; - } - default: - { - m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_NO_INPUTSTATUS; - } - } - } - } - return result; -} - -void KX_BlenderKeyboardDevice::HookEscape() -{ - m_hookesc = true; -} diff --git a/source/gameengine/BlenderRoutines/KX_BlenderKeyboardDevice.h b/source/gameengine/BlenderRoutines/KX_BlenderKeyboardDevice.h deleted file mode 100644 index 10a5b00937d..00000000000 --- a/source/gameengine/BlenderRoutines/KX_BlenderKeyboardDevice.h +++ /dev/null @@ -1,62 +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_BlenderKeyboardDevice.h - * \ingroup blroutines - */ - -#ifndef __KX_BLENDERKEYBOARDDEVICE_H__ -#define __KX_BLENDERKEYBOARDDEVICE_H__ - -#include "KX_BlenderInputDevice.h" - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -class KX_BlenderKeyboardDevice : public BL_BlenderInputDevice -{ - bool m_hookesc; -public: - KX_BlenderKeyboardDevice(); - virtual ~KX_BlenderKeyboardDevice(); - - virtual bool IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode); -// virtual const SCA_InputEvent& GetEventValue(SCA_IInputDevice::KX_EnumInputs inputcode); - virtual bool ConvertBlenderEvent(unsigned short incode, short val, unsigned int unicode); - virtual void NextFrame(); - virtual void HookEscape(); -private: - /* short m_exit_key; */ /* UNUSED */ - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_BlenderKeyboardDevice") -#endif -}; - -#endif /* __KX_BLENDERKEYBOARDDEVICE_H__ */ diff --git a/source/gameengine/BlenderRoutines/KX_BlenderMouseDevice.cpp b/source/gameengine/BlenderRoutines/KX_BlenderMouseDevice.cpp deleted file mode 100644 index 9df06e83b92..00000000000 --- a/source/gameengine/BlenderRoutines/KX_BlenderMouseDevice.cpp +++ /dev/null @@ -1,192 +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/BlenderRoutines/KX_BlenderMouseDevice.cpp - * \ingroup blroutines - */ - -#ifdef _MSC_VER - /* annoying warnings about truncated STL debug info */ -# pragma warning (disable:4786) -#endif - -#include "KX_BlenderMouseDevice.h" - -KX_BlenderMouseDevice::KX_BlenderMouseDevice() -{ - -} -KX_BlenderMouseDevice::~KX_BlenderMouseDevice() -{ - -} - -/** - * IsPressed gives boolean information about mouse status, true if pressed, false if not - */ - -bool KX_BlenderMouseDevice::IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode) -{ - const SCA_InputEvent & inevent = m_eventStatusTables[m_currentTable][inputcode]; - bool pressed = (inevent.m_status == SCA_InputEvent::KX_JUSTACTIVATED || - inevent.m_status == SCA_InputEvent::KX_ACTIVE); - return pressed; -} -/*const SCA_InputEvent& KX_BlenderMouseDevice::GetEventValue(SCA_IInputDevice::KX_EnumInputs inputcode) -{ - return m_eventStatusTables[m_currentTable][inputcode]; -} -*/ - -/** - * NextFrame toggles currentTable with previousTable, - * and copy relevant event information from previous to current - * (pressed keys need to be remembered) - */ -void KX_BlenderMouseDevice::NextFrame() -{ - SCA_IInputDevice::NextFrame(); - - // now convert justpressed keyevents into regular (active) keyevents - int previousTable = 1-m_currentTable; - for (int mouseevent= KX_BEGINMOUSE; mouseevent< KX_ENDMOUSEBUTTONS;mouseevent++) - { - SCA_InputEvent& oldevent = m_eventStatusTables[previousTable][mouseevent]; - if (oldevent.m_status == SCA_InputEvent::KX_JUSTACTIVATED || - oldevent.m_status == SCA_InputEvent::KX_ACTIVE ) - { - m_eventStatusTables[m_currentTable][mouseevent] = oldevent; - m_eventStatusTables[m_currentTable][mouseevent].m_status = SCA_InputEvent::KX_ACTIVE; - } - } - for (int mousemove= KX_ENDMOUSEBUTTONS; mousemove< KX_ENDMOUSE;mousemove++) - { - SCA_InputEvent& oldevent = m_eventStatusTables[previousTable][mousemove]; - m_eventStatusTables[m_currentTable][mousemove] = oldevent; - if (oldevent.m_status == SCA_InputEvent::KX_JUSTACTIVATED || - oldevent.m_status == SCA_InputEvent::KX_ACTIVE ) - { - - m_eventStatusTables[m_currentTable][mousemove].m_status = SCA_InputEvent::KX_JUSTRELEASED; - } else - { - if (oldevent.m_status == SCA_InputEvent::KX_JUSTRELEASED) - { - - m_eventStatusTables[m_currentTable][mousemove].m_status = SCA_InputEvent::KX_NO_INPUTSTATUS; - } - } - } -} - - -/** - * ConvertBlenderEvent translates blender mouse events into ketsji kbd events - * extra event information is stored, like ramp-mode (just released/pressed) - */ -bool KX_BlenderMouseDevice::ConvertBlenderEvent(unsigned short incode, short val, unsigned int unicode) -{ - bool result = false; - - // convert event - KX_EnumInputs kxevent = this->ToNative(incode); - int previousTable = 1-m_currentTable; - - // only process it, if it's a key - if (kxevent > KX_BEGINMOUSE && kxevent < KX_ENDMOUSEBUTTONS) - { - if (val == KM_PRESS || val == KM_DBL_CLICK) - { - m_eventStatusTables[m_currentTable][kxevent].m_eventval = val ; //??? - - switch (m_eventStatusTables[previousTable][kxevent].m_status) - { - - case SCA_InputEvent::KX_ACTIVE: - case SCA_InputEvent::KX_JUSTACTIVATED: - { - m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_ACTIVE; - break; - } - case SCA_InputEvent::KX_JUSTRELEASED: - { - m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_JUSTACTIVATED; - break; - } - default: - { - m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_JUSTACTIVATED; - } - } - - } else if (val == KM_RELEASE) - { - // blender eventval == 0 - switch (m_eventStatusTables[previousTable][kxevent].m_status) - { - case SCA_InputEvent::KX_JUSTACTIVATED: - case SCA_InputEvent::KX_ACTIVE: - { - m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_JUSTRELEASED; - break; - } - default: - { - m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_NO_INPUTSTATUS; - } - } - } - } - - if (kxevent > KX_ENDMOUSEBUTTONS && kxevent < KX_ENDMOUSE) - { - m_eventStatusTables[m_currentTable][kxevent].m_eventval = val ; //remember mouse position - - switch (m_eventStatusTables[previousTable][kxevent].m_status) - { - - case SCA_InputEvent::KX_ACTIVE: - case SCA_InputEvent::KX_JUSTACTIVATED: - { - m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_ACTIVE; - break; - } - case SCA_InputEvent::KX_JUSTRELEASED: - { - m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_ACTIVE; - break; - } - default: - { - m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_JUSTACTIVATED; - } - } - } - - - return result; -} diff --git a/source/gameengine/BlenderRoutines/KX_BlenderMouseDevice.h b/source/gameengine/BlenderRoutines/KX_BlenderMouseDevice.h deleted file mode 100644 index 04b78aff05c..00000000000 --- a/source/gameengine/BlenderRoutines/KX_BlenderMouseDevice.h +++ /dev/null @@ -1,58 +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_BlenderMouseDevice.h - * \ingroup blroutines - */ - -#ifndef __KX_BLENDERMOUSEDEVICE_H__ -#define __KX_BLENDERMOUSEDEVICE_H__ - -#include "KX_BlenderInputDevice.h" - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -class KX_BlenderMouseDevice : public BL_BlenderInputDevice -{ -public: - KX_BlenderMouseDevice(); - virtual ~KX_BlenderMouseDevice(); - - virtual bool IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode); -// virtual const SCA_InputEvent& GetEventValue(SCA_IInputDevice::KX_EnumInputs inputcode); - virtual bool ConvertBlenderEvent(unsigned short incode, short val, unsigned int unicode); - virtual void NextFrame(); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_BlenderMouseDevice") -#endif -}; - -#endif /* __KX_BLENDERMOUSEDEVICE_H__ */ diff --git a/source/gameengine/BlenderRoutines/KX_BlenderSystem.cpp b/source/gameengine/BlenderRoutines/KX_BlenderSystem.cpp deleted file mode 100644 index 0582e79d269..00000000000 --- a/source/gameengine/BlenderRoutines/KX_BlenderSystem.cpp +++ /dev/null @@ -1,59 +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/BlenderRoutines/KX_BlenderSystem.cpp - * \ingroup blroutines - */ - - -#include "KX_ISystem.h" - -#ifdef _MSC_VER -# pragma warning (disable:4786) -#endif - -#ifdef WIN32 -#include -#endif - -#include -#include -#include "KX_BlenderInputDevice.h" -#include "KX_BlenderSystem.h" - -#include "PIL_time.h" - -KX_BlenderSystem::KX_BlenderSystem() -: KX_ISystem() -{ - m_starttime = PIL_check_seconds_timer(); -} - -double KX_BlenderSystem::GetTimeInSeconds() -{ - return PIL_check_seconds_timer() - m_starttime; -} diff --git a/source/gameengine/BlenderRoutines/KX_BlenderSystem.h b/source/gameengine/BlenderRoutines/KX_BlenderSystem.h deleted file mode 100644 index 0867ef2421f..00000000000 --- a/source/gameengine/BlenderRoutines/KX_BlenderSystem.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_BlenderSystem.h - * \ingroup blroutines - * \brief Blender System embedding. Needed when gameengine runs embedded within Blender. - */ - -#ifndef __KX_BLENDERSYSTEM_H__ -#define __KX_BLENDERSYSTEM_H__ - -#include "KX_ISystem.h" - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -class KX_BlenderSystem : public KX_ISystem -{ - double m_starttime; - -public: - KX_BlenderSystem(); - virtual ~KX_BlenderSystem() {} - virtual double GetTimeInSeconds(); - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_BlenderSystem") -#endif -}; - -#endif /* __KX_BLENDERSYSTEM_H__ */ diff --git a/source/gameengine/CMakeLists.txt b/source/gameengine/CMakeLists.txt deleted file mode 100644 index 62523175f46..00000000000 --- a/source/gameengine/CMakeLists.txt +++ /dev/null @@ -1,57 +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 ***** - -remove_extra_strict_flags() - -# there are too many inter-includes so best define here -if(WITH_PYTHON) - blender_include_dirs_sys("${PYTHON_INCLUDE_DIRS}") - add_definitions(-DWITH_PYTHON) -endif() - -add_subdirectory(BlenderRoutines) -add_subdirectory(Converter) -add_subdirectory(Expressions) -add_subdirectory(GameLogic) -add_subdirectory(Ketsji) -add_subdirectory(Ketsji/KXNetwork) -add_subdirectory(Network) -add_subdirectory(Network/LoopBackNetwork) -add_subdirectory(Physics/Dummy) -add_subdirectory(Rasterizer) -add_subdirectory(Rasterizer/RAS_OpenGLRasterizer) -add_subdirectory(SceneGraph) - -if(WITH_BULLET) - add_subdirectory(Physics/Bullet) -endif() - -if(WITH_PYTHON) - add_subdirectory(VideoTexture) -endif() - -if(WITH_PLAYER) - add_subdirectory(GamePlayer) -endif() diff --git a/source/gameengine/Converter/BL_ActionActuator.cpp b/source/gameengine/Converter/BL_ActionActuator.cpp deleted file mode 100644 index d28cdb84275..00000000000 --- a/source/gameengine/Converter/BL_ActionActuator.cpp +++ /dev/null @@ -1,664 +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/Converter/BL_ActionActuator.cpp - * \ingroup bgeconv - */ - - -#include "SCA_LogicManager.h" -#include "BL_ActionActuator.h" -#include "BL_ArmatureObject.h" -#include "BL_SkinDeformer.h" -#include "BL_Action.h" -#include "BL_ActionManager.h" -#include "KX_GameObject.h" -#include "STR_HashedString.h" -#include "MEM_guardedalloc.h" -#include "DNA_nla_types.h" -#include "DNA_action_types.h" -#include "DNA_armature_types.h" -#include "DNA_scene_types.h" -#include "BLI_blenlib.h" -#include "BLI_math.h" -#include "BLI_utildefines.h" -#include "MT_Matrix4x4.h" - -#include "BKE_action.h" -#include "EXP_FloatValue.h" -#include "EXP_PyObjectPlus.h" -#include "KX_PyMath.h" - -extern "C" { -#include "BKE_animsys.h" -#include "BKE_action.h" -#include "RNA_access.h" -#include "RNA_define.h" -} - -BL_ActionActuator::BL_ActionActuator(SCA_IObject *gameobj, - const STR_String& propname, - const STR_String& framepropname, - float starttime, - float endtime, - struct bAction *action, - short playtype, - short blend_mode, - short blendin, - short priority, - short layer, - float layer_weight, - short ipo_flags, - short end_reset, - float stride) - : SCA_IActuator(gameobj, KX_ACT_ACTION), - - m_lastpos(0, 0, 0), - m_blendframe(0), - m_flag(0), - m_startframe (starttime), - m_endframe(endtime) , - m_starttime(0), - m_localtime(starttime), - m_lastUpdate(-1), - m_blendin(blendin), - m_blendstart(0), - m_stridelength(stride), - m_layer_weight(layer_weight), - m_playtype(playtype), - m_blendmode(blend_mode), - m_priority(priority), - m_layer(layer), - m_ipo_flags(ipo_flags), - m_action(action), - m_propname(propname), - m_framepropname(framepropname) -{ - if (!end_reset) - m_flag |= ACT_FLAG_CONTINUE; -}; - -BL_ActionActuator::~BL_ActionActuator() -{ -} - -void BL_ActionActuator::ProcessReplica() -{ - SCA_IActuator::ProcessReplica(); - - m_localtime=m_startframe; - m_lastUpdate=-1; - -} - -void BL_ActionActuator::SetBlendTime(float newtime) -{ - m_blendframe = newtime; -} - -void BL_ActionActuator::SetLocalTime(float curtime) -{ - float dt = (curtime-m_starttime)*KX_KetsjiEngine::GetAnimFrameRate(); - - if (m_endframe < m_startframe) - dt = -dt; - - m_localtime = m_startframe + dt; - - // Handle wrap around - if (m_localtime < min(m_startframe, m_endframe) || m_localtime > max(m_startframe, m_endframe)) - { - switch (m_playtype) { - case ACT_ACTION_PLAY: - // Clamp - m_localtime = m_endframe; - break; - case ACT_ACTION_LOOP_END: - // Put the time back to the beginning - m_localtime = m_startframe; - m_starttime = curtime; - break; - case ACT_ACTION_PINGPONG: - // Swap the start and end frames - float temp = m_startframe; - m_startframe = m_endframe; - m_endframe = temp; - - m_starttime = curtime; - - m_flag ^= ACT_FLAG_REVERSE; - - break; - } - } -} - -void BL_ActionActuator::ResetStartTime(float curtime) -{ - float dt = m_localtime - m_startframe; - - m_starttime = curtime - dt / (KX_KetsjiEngine::GetAnimFrameRate()); - //SetLocalTime(curtime); -} - -CValue* BL_ActionActuator::GetReplica() -{ - BL_ActionActuator* replica = new BL_ActionActuator(*this);//m_float,GetName()); - replica->ProcessReplica(); - return replica; -} - -bool BL_ActionActuator::Update(double curtime, bool frame) -{ - bool bNegativeEvent = false; - bool bPositiveEvent = false; - bool bUseContinue = false; - KX_GameObject *obj = (KX_GameObject*)GetParent(); - short playtype = BL_Action::ACT_MODE_PLAY; - short blendmode = (m_blendmode == ACT_ACTION_ADD) ? BL_Action::ACT_BLEND_ADD : BL_Action::ACT_BLEND_BLEND; - float start = m_startframe; - float end = m_endframe; - - // If we don't have an action, we can't do anything - if (!m_action) - return false; - - // Convert our playtype to one that BL_Action likes - switch (m_playtype) { - case ACT_ACTION_LOOP_END: - case ACT_ACTION_LOOP_STOP: - playtype = BL_Action::ACT_MODE_LOOP; - break; - - case ACT_ACTION_PINGPONG: - // We handle ping pong ourselves to increase compabitility - // with files made prior to animation changes from GSoC 2011. - playtype = BL_Action::ACT_MODE_PLAY; - - if (m_flag & ACT_FLAG_REVERSE) - { - start = m_endframe; - end = m_startframe; - } - - break; - case ACT_ACTION_FROM_PROP: - CValue* prop = GetParent()->GetProperty(m_propname); - - // If we don't have a property, we can't do anything, so just bail - if (!prop) return false; - - playtype = BL_Action::ACT_MODE_PLAY; - start = end = prop->GetNumber(); - - break; - } - - if (m_flag & ACT_FLAG_CONTINUE) - bUseContinue = true; - - - // Handle events - if (frame) - { - bNegativeEvent = m_negevent; - bPositiveEvent = m_posevent; - RemoveAllEvents(); - } - - // "Active" actions need to keep updating their current frame - if (bUseContinue && (m_flag & ACT_FLAG_ACTIVE)) - m_localtime = obj->GetActionFrame(m_layer); - - if (m_flag & ACT_FLAG_ATTEMPT_PLAY) - SetLocalTime(curtime); - else - ResetStartTime(curtime); - - // Handle a frame property if it's defined - if ((m_flag & ACT_FLAG_ACTIVE) && m_framepropname[0] != 0) - { - CValue* oldprop = obj->GetProperty(m_framepropname); - CValue* newval = new CFloatValue(obj->GetActionFrame(m_layer)); - if (oldprop) - oldprop->SetValue(newval); - else - obj->SetProperty(m_framepropname, newval); - - newval->Release(); - } - - // Handle a finished animation - if ((m_flag & ACT_FLAG_PLAY_END) && (m_flag & ACT_FLAG_ACTIVE) && obj->IsActionDone(m_layer)) - { - m_flag &= ~ACT_FLAG_ACTIVE; - - if (m_playtype == ACT_ACTION_PINGPONG) { - m_flag ^= ACT_FLAG_REVERSE; - } - else { - m_flag &= ~ACT_FLAG_ATTEMPT_PLAY; - return false; - } - } - - // If a different action is playing, we've been overruled and are no longer active - if (obj->GetCurrentAction(m_layer) != m_action && !obj->IsActionDone(m_layer)) - m_flag &= ~ACT_FLAG_ACTIVE; - - if (bPositiveEvent || (m_flag & ACT_FLAG_ATTEMPT_PLAY && !(m_flag & ACT_FLAG_ACTIVE))) - { - if (bPositiveEvent && m_playtype == ACT_ACTION_PLAY) - { - if (obj->IsActionDone(m_layer)) - m_localtime = start; - ResetStartTime(curtime); - } - - if (obj->PlayAction(m_action->id.name+2, start, end, m_layer, m_priority, m_blendin, playtype, m_layer_weight, m_ipo_flags, 1.f, blendmode)) - { - m_flag |= ACT_FLAG_ACTIVE; - if (bUseContinue) - obj->SetActionFrame(m_layer, m_localtime); - - if (m_playtype == ACT_ACTION_PLAY || m_playtype == ACT_ACTION_PINGPONG) - m_flag |= ACT_FLAG_PLAY_END; - else - m_flag &= ~ACT_FLAG_PLAY_END; - } - m_flag |= ACT_FLAG_ATTEMPT_PLAY; - } - else if ((m_flag & ACT_FLAG_ACTIVE) && bNegativeEvent) - { - m_flag &= ~ACT_FLAG_ATTEMPT_PLAY; - m_localtime = obj->GetActionFrame(m_layer); - bAction *curr_action = obj->GetCurrentAction(m_layer); - if (curr_action && curr_action != m_action) - { - // Someone changed the action on us, so we wont mess with it - // Hopefully there wont be too many problems with two actuators using - // the same action... - m_flag &= ~ACT_FLAG_ACTIVE; - return false; - } - - switch (m_playtype) { - case ACT_ACTION_FROM_PROP: - case ACT_ACTION_LOOP_STOP: - obj->StopAction(m_layer); // Stop the action after getting the frame - - // We're done - m_flag &= ~ACT_FLAG_ACTIVE; - return false; - case ACT_ACTION_LOOP_END: - // Convert into a play and let it finish - obj->SetPlayMode(m_layer, BL_Action::ACT_MODE_PLAY); - - m_flag |= ACT_FLAG_PLAY_END; - break; - - case ACT_ACTION_FLIPPER: - // Convert into a play action and play back to the beginning - float temp = end; - end = start; - start = curr_action ? obj->GetActionFrame(m_layer) : temp; - obj->PlayAction(m_action->id.name+2, start, end, m_layer, m_priority, 0, BL_Action::ACT_MODE_PLAY, m_layer_weight, m_ipo_flags, 1.f, blendmode); - - m_flag |= ACT_FLAG_PLAY_END; - break; - } - } - - return m_flag & ACT_FLAG_ACTIVE; -} - -void BL_ActionActuator::DecLink() -{ - SCA_IActuator::DecLink(); - /* In this case no controllers use this action actuator, - and it should stop its action. */ - if (m_links == 0) { - KX_GameObject *obj = (KX_GameObject *)GetParent(); - obj->StopAction(m_layer); - } -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -PyObject *BL_ActionActuator::PyGetChannel(PyObject *value) -{ - PyErr_SetString(PyExc_NotImplementedError, "BL_ActionActuator.getChannel() no longer works, please use BL_ArmatureObject.channels instead"); - return NULL; -#if 0 // XXX To be removed in a later version (first removed in 2.64) - const char *string= _PyUnicode_AsString(value); - - if (GetParent()->GetGameObjectType() != SCA_IObject::OBJ_ARMATURE) - { - PyErr_SetString(PyExc_NotImplementedError, "actuator.getChannel(): Only armatures support channels"); - return NULL; - } - - if (!string) { - PyErr_SetString(PyExc_TypeError, "expected a single string"); - return NULL; - } - - bPoseChannel *pchan; - - if (m_userpose==NULL && m_pose==NULL) { - BL_ArmatureObject *obj = (BL_ArmatureObject*)GetParent(); - obj->GetPose(&m_pose); /* Get the underlying pose from the armature */ - } - - // BKE_pose_channel_find_name accounts for NULL pose, run on both in case one exists but - // the channel doesnt - if ( !(pchan=BKE_pose_channel_find_name(m_userpose, string)) && - !(pchan=BKE_pose_channel_find_name(m_pose, string)) ) - { - PyErr_SetString(PyExc_ValueError, "channel doesnt exist"); - return NULL; - } - - PyObject *ret = PyTuple_New(3); - - PyObject *list = PyList_New(3); - PyList_SET_ITEM(list, 0, PyFloat_FromDouble(pchan->loc[0])); - PyList_SET_ITEM(list, 1, PyFloat_FromDouble(pchan->loc[1])); - PyList_SET_ITEM(list, 2, PyFloat_FromDouble(pchan->loc[2])); - PyTuple_SET_ITEM(ret, 0, list); - - list = PyList_New(3); - PyList_SET_ITEM(list, 0, PyFloat_FromDouble(pchan->size[0])); - PyList_SET_ITEM(list, 1, PyFloat_FromDouble(pchan->size[1])); - PyList_SET_ITEM(list, 2, PyFloat_FromDouble(pchan->size[2])); - PyTuple_SET_ITEM(ret, 1, list); - - list = PyList_New(4); - PyList_SET_ITEM(list, 0, PyFloat_FromDouble(pchan->quat[0])); - PyList_SET_ITEM(list, 1, PyFloat_FromDouble(pchan->quat[1])); - PyList_SET_ITEM(list, 2, PyFloat_FromDouble(pchan->quat[2])); - PyList_SET_ITEM(list, 3, PyFloat_FromDouble(pchan->quat[3])); - PyTuple_SET_ITEM(ret, 2, list); - - return ret; -#if 0 - return Py_BuildValue("([fff][fff][ffff])", - pchan->loc[0], pchan->loc[1], pchan->loc[2], - pchan->size[0], pchan->size[1], pchan->size[2], - pchan->quat[0], pchan->quat[1], pchan->quat[2], pchan->quat[3] ); -#endif -#endif -} - -/* setChannel */ -KX_PYMETHODDEF_DOC(BL_ActionActuator, setChannel, -"setChannel(channel, matrix)\n" -"\t - channel : A string specifying the name of the bone channel.\n" -"\t - matrix : A 4x4 matrix specifying the overriding transformation\n" -"\t as an offset from the bone's rest position.\n") -{ - PyErr_SetString(PyExc_NotImplementedError, "BL_ActionActuator.setChannel() no longer works, please use BL_ArmatureObject.channels instead"); - return NULL; - -#if 0 // XXX To be removed in a later version (first removed in 2.64) - BL_ArmatureObject *obj = (BL_ArmatureObject*)GetParent(); - char *string; - PyObject *pymat= NULL; - PyObject *pyloc= NULL, *pysize= NULL, *pyquat= NULL; - bPoseChannel *pchan; - - if (GetParent()->GetGameObjectType() != SCA_IObject::OBJ_ARMATURE) - { - PyErr_SetString(PyExc_NotImplementedError, "actuator.setChannel(): Only armatures support channels"); - return NULL; - } - - if (PyTuple_Size(args)==2) { - if (!PyArg_ParseTuple(args,"sO:setChannel", &string, &pymat)) // matrix - return NULL; - } - else if (PyTuple_Size(args)==4) { - if (!PyArg_ParseTuple(args,"sOOO:setChannel", &string, &pyloc, &pysize, &pyquat)) // loc/size/quat - return NULL; - } - else { - PyErr_SetString(PyExc_ValueError, "Expected a string and a 4x4 matrix (2 args) or a string and loc/size/quat sequences (4 args)"); - return NULL; - } - - if (pymat) { - float matrix[4][4]; - MT_Matrix4x4 mat; - - if (!PyMatTo(pymat, mat)) - return NULL; - - mat.getValue((float*)matrix); - - BL_ArmatureObject *obj = (BL_ArmatureObject*)GetParent(); - - if (!m_userpose) { - if (!m_pose) - obj->GetPose(&m_pose); /* Get the underlying pose from the armature */ - game_copy_pose(&m_userpose, m_pose, 0); - } - // pchan= BKE_pose_channel_verify(m_userpose, string); // adds the channel if its not there. - pchan= BKE_pose_channel_find_name(m_userpose, string); // adds the channel if its not there. - - if (pchan) { - copy_v3_v3(pchan->loc, matrix[3]); - mat4_to_size(pchan->size, matrix); - mat4_to_quat(pchan->quat, matrix); - } - } - else { - MT_Vector3 loc; - MT_Vector3 size; - MT_Quaternion quat; - - if (!PyVecTo(pyloc, loc) || !PyVecTo(pysize, size) || !PyQuatTo(pyquat, quat)) - return NULL; - - // same as above - if (!m_userpose) { - if (!m_pose) - obj->GetPose(&m_pose); /* Get the underlying pose from the armature */ - game_copy_pose(&m_userpose, m_pose, 0); - } - // pchan= BKE_pose_channel_verify(m_userpose, string); - pchan= BKE_pose_channel_find_name(m_userpose, string); // adds the channel if its not there. - - // for some reason loc.setValue(pchan->loc) fails - if (pchan) { - pchan->loc[0] = loc[0]; pchan->loc[1] = loc[1]; pchan->loc[2] = loc[2]; - pchan->size[0] = size[0]; pchan->size[1] = size[1]; pchan->size[2] = size[2]; - pchan->quat[0] = quat[3]; pchan->quat[1] = quat[0]; pchan->quat[2] = quat[1]; pchan->quat[3] = quat[2]; /* notice xyzw -> wxyz is intentional */ - } - } - - if (pchan==NULL) { - PyErr_SetString(PyExc_ValueError, "Channel could not be found, use the 'channelNames' attribute to get a list of valid channels"); - return NULL; - } - - Py_RETURN_NONE; -#endif -} - -/* ------------------------------------------------------------------------- */ -/* Python Integration Hooks */ -/* ------------------------------------------------------------------------- */ - -PyTypeObject BL_ActionActuator::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "BL_ActionActuator", - 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 BL_ActionActuator::Methods[] = { - {"getChannel", (PyCFunction) BL_ActionActuator::sPyGetChannel, METH_O}, - KX_PYMETHODTABLE(BL_ActionActuator, setChannel), - {NULL,NULL} //Sentinel -}; - -PyAttributeDef BL_ActionActuator::Attributes[] = { - KX_PYATTRIBUTE_FLOAT_RW("frameStart", 0, MAXFRAMEF, BL_ActionActuator, m_startframe), - KX_PYATTRIBUTE_FLOAT_RW("frameEnd", 0, MAXFRAMEF, BL_ActionActuator, m_endframe), - KX_PYATTRIBUTE_FLOAT_RW("blendIn", 0, MAXFRAMEF, BL_ActionActuator, m_blendin), - KX_PYATTRIBUTE_RW_FUNCTION("action", BL_ActionActuator, pyattr_get_action, pyattr_set_action), - KX_PYATTRIBUTE_RO_FUNCTION("channelNames", BL_ActionActuator, pyattr_get_channel_names), - KX_PYATTRIBUTE_SHORT_RW("priority", 0, 100, false, BL_ActionActuator, m_priority), - KX_PYATTRIBUTE_SHORT_RW("layer", 0, MAX_ACTION_LAYERS-1, true, BL_ActionActuator, m_layer), - KX_PYATTRIBUTE_FLOAT_RW("layerWeight", 0, 1.0, BL_ActionActuator, m_layer_weight), - KX_PYATTRIBUTE_RW_FUNCTION("frame", BL_ActionActuator, pyattr_get_frame, pyattr_set_frame), - KX_PYATTRIBUTE_STRING_RW("propName", 0, MAX_PROP_NAME, false, BL_ActionActuator, m_propname), - KX_PYATTRIBUTE_STRING_RW("framePropName", 0, MAX_PROP_NAME, false, BL_ActionActuator, m_framepropname), - KX_PYATTRIBUTE_RW_FUNCTION("useContinue", BL_ActionActuator, pyattr_get_use_continue, pyattr_set_use_continue), - KX_PYATTRIBUTE_FLOAT_RW_CHECK("blendTime", 0, MAXFRAMEF, BL_ActionActuator, m_blendframe, CheckBlendTime), - KX_PYATTRIBUTE_SHORT_RW_CHECK("mode",0,100,false,BL_ActionActuator,m_playtype,CheckType), - { NULL } //Sentinel -}; - -PyObject *BL_ActionActuator::pyattr_get_action(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - BL_ActionActuator* self = static_cast(self_v); - return PyUnicode_FromString(self->GetAction() ? self->GetAction()->id.name+2 : ""); -} - -int BL_ActionActuator::pyattr_set_action(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - BL_ActionActuator* self = static_cast(self_v); - - if (!PyUnicode_Check(value)) - { - PyErr_SetString(PyExc_ValueError, "actuator.action = val: Action Actuator, expected the string name of the action"); - return PY_SET_ATTR_FAIL; - } - - bAction *action= NULL; - STR_String val = _PyUnicode_AsString(value); - - if (val != "") - { - action= (bAction*)self->GetLogicManager()->GetActionByName(val); - if (!action) - { - PyErr_SetString(PyExc_ValueError, "actuator.action = val: Action Actuator, action not found!"); - return PY_SET_ATTR_FAIL; - } - } - - self->SetAction(action); - return PY_SET_ATTR_SUCCESS; - -} - -PyObject *BL_ActionActuator::pyattr_get_channel_names(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - PyErr_SetString(PyExc_NotImplementedError, "BL_ActionActuator.channelNames no longer works, please use BL_ArmatureObject.channels instead"); - return NULL; - -#if 0 // XXX To be removed in a later version (first removed in 2.64) - BL_ActionActuator* self = static_cast(self_v); - PyObject *ret= PyList_New(0); - PyObject *item; - - if (self->GetParent()->GetGameObjectType() != SCA_IObject::OBJ_ARMATURE) - { - PyErr_SetString(PyExc_NotImplementedError, "actuator.channelNames: Only armatures support channels"); - return NULL; - } - - bPose *pose= ((BL_ArmatureObject*)self->GetParent())->GetOrigPose(); - - if (pose) { - bPoseChannel *pchan; - for (pchan= (bPoseChannel *)pose->chanbase.first; pchan; pchan= (bPoseChannel *)pchan->next) { - item= PyUnicode_FromString(pchan->name); - PyList_Append(ret, item); - Py_DECREF(item); - } - } - - return ret; -#endif -} - -PyObject *BL_ActionActuator::pyattr_get_use_continue(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - BL_ActionActuator* self = static_cast(self_v); - return PyBool_FromLong(self->m_flag & ACT_FLAG_CONTINUE); -} - -int BL_ActionActuator::pyattr_set_use_continue(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - BL_ActionActuator* self = static_cast(self_v); - - if (PyObject_IsTrue(value)) - self->m_flag |= ACT_FLAG_CONTINUE; - else - self->m_flag &= ~ACT_FLAG_CONTINUE; - - return PY_SET_ATTR_SUCCESS; -} - -PyObject *BL_ActionActuator::pyattr_get_frame(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - BL_ActionActuator* self = static_cast(self_v); - return PyFloat_FromDouble(((KX_GameObject*)self->m_gameobj)->GetActionFrame(self->m_layer)); -} - -int BL_ActionActuator::pyattr_set_frame(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - BL_ActionActuator* self = static_cast(self_v); - - ((KX_GameObject*)self->m_gameobj)->SetActionFrame(self->m_layer, PyFloat_AsDouble(value)); - - return PY_SET_ATTR_SUCCESS; -} - -#endif // WITH_PYTHON diff --git a/source/gameengine/Converter/BL_ActionActuator.h b/source/gameengine/Converter/BL_ActionActuator.h deleted file mode 100644 index a43cf0f0a7b..00000000000 --- a/source/gameengine/Converter/BL_ActionActuator.h +++ /dev/null @@ -1,158 +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 BL_ActionActuator.h - * \ingroup bgeconv - */ - -#ifndef __BL_ACTIONACTUATOR_H__ -#define __BL_ACTIONACTUATOR_H__ - -#include "CTR_HashedPtr.h" -#include "SCA_IActuator.h" -#include "DNA_actuator_types.h" -#include "MT_Point3.h" - -class BL_ActionActuator : public SCA_IActuator -{ -public: - Py_Header - BL_ActionActuator(SCA_IObject* gameobj, - const STR_String& propname, - const STR_String& framepropname, - float starttime, - float endtime, - struct bAction *action, - short playtype, - short blend_mode, - short blendin, - short priority, - short layer, - float layer_weight, - short ipo_flags, - short end_reset, - float stride); - - virtual ~BL_ActionActuator(); - virtual bool Update(double curtime, bool frame); - virtual CValue* GetReplica(); - virtual void ProcessReplica(); - - void SetBlendTime(float newtime); - void SetLocalTime(float curtime); - void ResetStartTime(float curtime); - - bAction* GetAction() { return m_action; } - void SetAction(bAction* act) { m_action= act; } - - virtual void DecLink(); - -#ifdef WITH_PYTHON - - KX_PYMETHOD_O(BL_ActionActuator,GetChannel) - KX_PYMETHOD_DOC(BL_ActionActuator,setChannel) - - static PyObject* pyattr_get_action(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_action(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_channel_names(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_use_continue(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_use_continue(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_frame(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_frame(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - - static int CheckBlendTime(void *self, const PyAttributeDef*) - { - BL_ActionActuator* act = reinterpret_cast(self); - - if (act->m_blendframe > act->m_blendin) - act->m_blendframe = act->m_blendin; - - return 0; - } - - static int CheckType(void *self, const PyAttributeDef*) - { - BL_ActionActuator* act = reinterpret_cast(self); - - switch (act->m_playtype) { - case ACT_ACTION_PLAY: - case ACT_ACTION_PINGPONG: - case ACT_ACTION_FLIPPER: - case ACT_ACTION_LOOP_STOP: - case ACT_ACTION_LOOP_END: - case ACT_ACTION_FROM_PROP: - return 0; - default: - PyErr_SetString(PyExc_ValueError, "Action Actuator, invalid play type supplied"); - return 1; - } - } -#endif /* WITH_PYTHON */ - -protected: - MT_Point3 m_lastpos; - float m_blendframe; - int m_flag; - /** The frame this action starts */ - float m_startframe; - /** The frame this action ends */ - float m_endframe; - /** The time this action started */ - float m_starttime; - /** The current time of the action */ - float m_localtime; - - float m_lastUpdate; - float m_blendin; - float m_blendstart; - float m_stridelength; - float m_layer_weight; - short m_playtype; - short m_blendmode; - short m_priority; - short m_layer; - short m_ipo_flags; - struct bAction *m_action; - STR_String m_propname; - STR_String m_framepropname; -}; - -// Not all of these values are used in BL_ActionActuator anymore, -// but BL_ShapeActionActuator still uses them, so we keep them around -// for now. -enum { - ACT_FLAG_REVERSE = 1<<0, - ACT_FLAG_LOCKINPUT = 1<<1, - ACT_FLAG_KEYUP = 1<<2, - ACT_FLAG_ACTIVE = 1<<3, - ACT_FLAG_CONTINUE = 1<<4, - ACT_FLAG_PLAY_END = 1<<5, - ACT_FLAG_ATTEMPT_PLAY = 1<<6, -}; - -#endif - diff --git a/source/gameengine/Converter/BL_ArmatureActuator.cpp b/source/gameengine/Converter/BL_ArmatureActuator.cpp deleted file mode 100644 index 67cc7d2c291..00000000000 --- a/source/gameengine/Converter/BL_ArmatureActuator.cpp +++ /dev/null @@ -1,271 +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/Converter/BL_ArmatureActuator.cpp - * \ingroup bgeconv - */ - - -#include "DNA_action_types.h" -#include "DNA_constraint_types.h" -#include "DNA_actuator_types.h" -#include "BKE_constraint.h" -#include "BL_ArmatureActuator.h" -#include "BL_ArmatureObject.h" -#include "BLI_math.h" - -/** - * This class is the conversion of the Pose channel constraint. - * It makes a link between the pose constraint and the KX scene. - * The main purpose is to give access to the constraint target - * to link it to a game object. - * It also allows to activate/deactivate constraints during the game. - * Later it will also be possible to create constraint on the fly - */ - -BL_ArmatureActuator::BL_ArmatureActuator(SCA_IObject* obj, - int type, - const char *posechannel, - const char *constraintname, - KX_GameObject* targetobj, - KX_GameObject* subtargetobj, - float weight, - float influence) : - SCA_IActuator(obj, KX_ACT_ARMATURE), - m_constraint(NULL), - m_gametarget(targetobj), - m_gamesubtarget(subtargetobj), - m_posechannel(posechannel), - m_constraintname(constraintname), - m_weight(weight), - m_influence(influence), - m_type(type) -{ - if (m_gametarget) - m_gametarget->RegisterActuator(this); - if (m_gamesubtarget) - m_gamesubtarget->RegisterActuator(this); - FindConstraint(); -} - -BL_ArmatureActuator::~BL_ArmatureActuator() -{ - if (m_gametarget) - m_gametarget->UnregisterActuator(this); - if (m_gamesubtarget) - m_gamesubtarget->UnregisterActuator(this); -} - -void BL_ArmatureActuator::ProcessReplica() -{ - // the replica is tracking the same object => register it (this may be changed in Relnk()) - if (m_gametarget) - m_gametarget->RegisterActuator(this); - if (m_gamesubtarget) - m_gamesubtarget->UnregisterActuator(this); - SCA_IActuator::ProcessReplica(); -} - -void BL_ArmatureActuator::ReParent(SCA_IObject* parent) -{ - SCA_IActuator::ReParent(parent); - // must remap the constraint - FindConstraint(); -} - -bool BL_ArmatureActuator::UnlinkObject(SCA_IObject* clientobj) -{ - bool res=false; - if (clientobj == m_gametarget) - { - // this object is being deleted, we cannot continue to track it. - m_gametarget = NULL; - res = true; - } - if (clientobj == m_gamesubtarget) - { - // this object is being deleted, we cannot continue to track it. - m_gamesubtarget = NULL; - res = true; - } - return res; -} - -void BL_ArmatureActuator::Relink(CTR_Map *obj_map) -{ - void **h_obj = (*obj_map)[m_gametarget]; - if (h_obj) { - if (m_gametarget) - m_gametarget->UnregisterActuator(this); - m_gametarget = (KX_GameObject*)(*h_obj); - m_gametarget->RegisterActuator(this); - } - h_obj = (*obj_map)[m_gamesubtarget]; - if (h_obj) { - if (m_gamesubtarget) - m_gamesubtarget->UnregisterActuator(this); - m_gamesubtarget = (KX_GameObject*)(*h_obj); - m_gamesubtarget->RegisterActuator(this); - } -} - -void BL_ArmatureActuator::FindConstraint() -{ - m_constraint = NULL; - - if (m_gameobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE) { - BL_ArmatureObject* armobj = (BL_ArmatureObject*)m_gameobj; - m_constraint = armobj->GetConstraint(m_posechannel, m_constraintname); - } -} - -bool BL_ArmatureActuator::Update(double curtime, bool frame) -{ - // the only role of this actuator is to ensure that the armature pose will be evaluated - bool result = false; - bool bNegativeEvent = IsNegativeEvent(); - RemoveAllEvents(); - - if (!bNegativeEvent) { - BL_ArmatureObject *obj = (BL_ArmatureObject*)GetParent(); - switch (m_type) { - case ACT_ARM_RUN: - result = true; - obj->UpdateTimestep(curtime); - break; - case ACT_ARM_ENABLE: - if (m_constraint) - m_constraint->ClrConstraintFlag(CONSTRAINT_OFF); - break; - case ACT_ARM_DISABLE: - if (m_constraint) - m_constraint->SetConstraintFlag(CONSTRAINT_OFF); - break; - case ACT_ARM_SETTARGET: - if (m_constraint) { - m_constraint->SetTarget(m_gametarget); - m_constraint->SetSubtarget(m_gamesubtarget); - } - break; - case ACT_ARM_SETWEIGHT: - if (m_constraint) - m_constraint->SetWeight(m_weight); - break; - case ACT_ARM_SETINFLUENCE: - if (m_constraint) - m_constraint->SetInfluence(m_influence); - break; - } - } - return result; -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python Integration Hooks */ -/* ------------------------------------------------------------------------- */ - -PyTypeObject BL_ArmatureActuator::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "BL_ArmatureActuator", - 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 BL_ArmatureActuator::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef BL_ArmatureActuator::Attributes[] = { - KX_PYATTRIBUTE_RO_FUNCTION("constraint", BL_ArmatureActuator, pyattr_get_constraint), - KX_PYATTRIBUTE_RW_FUNCTION("target", BL_ArmatureActuator, pyattr_get_object, pyattr_set_object), - KX_PYATTRIBUTE_RW_FUNCTION("subtarget", BL_ArmatureActuator, pyattr_get_object, pyattr_set_object), - KX_PYATTRIBUTE_FLOAT_RW("weight",0.0f,1.0f,BL_ArmatureActuator,m_weight), - KX_PYATTRIBUTE_FLOAT_RW("influence",0.0f,1.0f,BL_ArmatureActuator,m_influence), - KX_PYATTRIBUTE_INT_RW("type",0,ACT_ARM_MAXTYPE,false,BL_ArmatureActuator,m_type), - { NULL } //Sentinel -}; - -PyObject *BL_ArmatureActuator::pyattr_get_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef) -{ - BL_ArmatureActuator* actuator = static_cast(self); - KX_GameObject *target = (!strcmp(attrdef->m_name, "target")) ? actuator->m_gametarget : actuator->m_gamesubtarget; - if (!target) - Py_RETURN_NONE; - else - return target->GetProxy(); -} - -int BL_ArmatureActuator::pyattr_set_object(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - BL_ArmatureActuator* actuator = static_cast(self); - KX_GameObject* &target = (!strcmp(attrdef->m_name, "target")) ? actuator->m_gametarget : actuator->m_gamesubtarget; - KX_GameObject *gameobj; - - if (!ConvertPythonToGameObject(actuator->GetLogicManager(), value, &gameobj, true, "actuator.object = value: BL_ArmatureActuator")) - return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error - - if (target != NULL) - target->UnregisterActuator(actuator); - - target = gameobj; - - if (target) - target->RegisterActuator(actuator); - - return PY_SET_ATTR_SUCCESS; -} - -PyObject *BL_ArmatureActuator::pyattr_get_constraint(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef) -{ - BL_ArmatureActuator* actuator = static_cast(self); - BL_ArmatureConstraint* constraint = actuator->m_constraint; - if (!constraint) - Py_RETURN_NONE; - else - return constraint->GetProxy(); -} - -#endif // WITH_PYTHON - diff --git a/source/gameengine/Converter/BL_ArmatureActuator.h b/source/gameengine/Converter/BL_ArmatureActuator.h deleted file mode 100644 index ba02c5aa362..00000000000 --- a/source/gameengine/Converter/BL_ArmatureActuator.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 BL_ArmatureActuator.h - * \ingroup bgeconv - */ - -#ifndef __BL_ARMATUREACTUATOR_H__ -#define __BL_ARMATUREACTUATOR_H__ - -#include "SCA_IActuator.h" -#include "BL_ArmatureConstraint.h" - -/** - * This class is the conversion of the Pose channel constraint. - * It makes a link between the pose constraint and the KX scene. - * The main purpose is to give access to the constraint target - * to link it to a game object. - * It also allows to activate/deactivate constraints during the game. - * Later it will also be possible to create constraint on the fly - */ - -class BL_ArmatureActuator : public SCA_IActuator -{ - Py_Header -public: - BL_ArmatureActuator(SCA_IObject* gameobj, - int type, - const char *posechannel, - const char *constraintname, - KX_GameObject* targetobj, - KX_GameObject* subtargetobj, - float weight, - float influence); - - virtual ~BL_ArmatureActuator(); - - virtual CValue* GetReplica() { - BL_ArmatureActuator* replica = new BL_ArmatureActuator(*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); - virtual void ReParent(SCA_IObject* parent); - -#ifdef WITH_PYTHON - - /* These are used to get and set m_target */ - static PyObject *pyattr_get_constraint(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - 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 */ - -private: - // identify the constraint that this actuator controls - void FindConstraint(); - - BL_ArmatureConstraint* m_constraint; - KX_GameObject* m_gametarget; - KX_GameObject* m_gamesubtarget; - STR_String m_posechannel; - STR_String m_constraintname; - float m_weight; - float m_influence; - int m_type; -}; - -#endif /* __BL_ARMATUREACTUATOR_H__ */ diff --git a/source/gameengine/Converter/BL_ArmatureChannel.cpp b/source/gameengine/Converter/BL_ArmatureChannel.cpp deleted file mode 100644 index 2b8dfd8f8d1..00000000000 --- a/source/gameengine/Converter/BL_ArmatureChannel.cpp +++ /dev/null @@ -1,469 +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/Converter/BL_ArmatureChannel.cpp - * \ingroup bgeconv - */ - - -#include "DNA_armature_types.h" -#include "BL_ArmatureChannel.h" -#include "BL_ArmatureObject.h" -#include "BL_ArmatureConstraint.h" -#include "BLI_math.h" -#include "BLI_string.h" -#include - -#ifdef WITH_PYTHON - -PyTypeObject BL_ArmatureChannel::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "BL_ArmatureChannel", - 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 -}; - -PyObject *BL_ArmatureChannel::py_repr(void) -{ - return PyUnicode_FromString(m_posechannel->name); -} - -PyObject *BL_ArmatureChannel::GetProxy() -{ - return GetProxyPlus_Ext(this, &Type, m_posechannel); -} - -PyObject *BL_ArmatureChannel::NewProxy(bool py_owns) -{ - return NewProxyPlus_Ext(this, &Type, m_posechannel, py_owns); -} - -#endif // WITH_PYTHON - -BL_ArmatureChannel::BL_ArmatureChannel( - BL_ArmatureObject *armature, - bPoseChannel *posechannel) - : PyObjectPlus(), m_posechannel(posechannel), m_armature(armature) -{ -} - -BL_ArmatureChannel::~BL_ArmatureChannel() -{ -} - -#ifdef WITH_PYTHON - -// PYTHON - -PyMethodDef BL_ArmatureChannel::Methods[] = { - {NULL,NULL} //Sentinel -}; - -// order of definition of attributes, must match Attributes[] array -#define BCA_BONE 0 -#define BCA_PARENT 1 - -PyAttributeDef BL_ArmatureChannel::Attributes[] = { - // Keep these attributes in order of BCA_ defines!!! used by py_attr_getattr and py_attr_setattr - KX_PYATTRIBUTE_RO_FUNCTION("bone",BL_ArmatureChannel,py_attr_getattr), - KX_PYATTRIBUTE_RO_FUNCTION("parent",BL_ArmatureChannel,py_attr_getattr), - - { NULL } //Sentinel -}; - -/* attributes directly taken from bPoseChannel */ -PyAttributeDef BL_ArmatureChannel::AttributesPtr[] = { - KX_PYATTRIBUTE_CHAR_RO("name",bPoseChannel,name), - KX_PYATTRIBUTE_FLAG_RO("has_ik",bPoseChannel,flag, POSE_CHAIN), - KX_PYATTRIBUTE_FLAG_NEGATIVE_RO("ik_dof_x",bPoseChannel,ikflag, BONE_IK_NO_XDOF), - KX_PYATTRIBUTE_FLAG_NEGATIVE_RO("ik_dof_y",bPoseChannel,ikflag, BONE_IK_NO_YDOF), - KX_PYATTRIBUTE_FLAG_NEGATIVE_RO("ik_dof_z",bPoseChannel,ikflag, BONE_IK_NO_ZDOF), - KX_PYATTRIBUTE_FLAG_RO("ik_limit_x",bPoseChannel,ikflag, BONE_IK_XLIMIT), - KX_PYATTRIBUTE_FLAG_RO("ik_limit_y",bPoseChannel,ikflag, BONE_IK_YLIMIT), - KX_PYATTRIBUTE_FLAG_RO("ik_limit_z",bPoseChannel,ikflag, BONE_IK_ZLIMIT), - KX_PYATTRIBUTE_FLAG_RO("ik_rot_control",bPoseChannel,ikflag, BONE_IK_ROTCTL), - KX_PYATTRIBUTE_FLAG_RO("ik_lin_control",bPoseChannel,ikflag, BONE_IK_LINCTL), - KX_PYATTRIBUTE_FLOAT_VECTOR_RW("location",-FLT_MAX,FLT_MAX,bPoseChannel,loc,3), - KX_PYATTRIBUTE_FLOAT_VECTOR_RW("scale",-FLT_MAX,FLT_MAX,bPoseChannel,size,3), - KX_PYATTRIBUTE_FLOAT_VECTOR_RW("rotation_quaternion",-1.0f,1.0f,bPoseChannel,quat,4), - KX_PYATTRIBUTE_FLOAT_VECTOR_RW("rotation_euler",-10.f,10.f,bPoseChannel,eul,3), - KX_PYATTRIBUTE_SHORT_RW("rotation_mode",ROT_MODE_MIN,ROT_MODE_MAX,false,bPoseChannel,rotmode), - KX_PYATTRIBUTE_FLOAT_MATRIX_RO("channel_matrix",bPoseChannel,chan_mat,4), - KX_PYATTRIBUTE_FLOAT_MATRIX_RO("pose_matrix",bPoseChannel,pose_mat,4), - KX_PYATTRIBUTE_FLOAT_VECTOR_RO("pose_head",bPoseChannel,pose_head,3), - KX_PYATTRIBUTE_FLOAT_VECTOR_RO("pose_tail",bPoseChannel,pose_tail,3), - KX_PYATTRIBUTE_FLOAT_RO("ik_min_x",bPoseChannel,limitmin[0]), - KX_PYATTRIBUTE_FLOAT_RO("ik_max_x",bPoseChannel,limitmax[0]), - KX_PYATTRIBUTE_FLOAT_RO("ik_min_y",bPoseChannel,limitmin[1]), - KX_PYATTRIBUTE_FLOAT_RO("ik_max_y",bPoseChannel,limitmax[1]), - KX_PYATTRIBUTE_FLOAT_RO("ik_min_z",bPoseChannel,limitmin[2]), - KX_PYATTRIBUTE_FLOAT_RO("ik_max_z",bPoseChannel,limitmax[2]), - KX_PYATTRIBUTE_FLOAT_RO("ik_stiffness_x",bPoseChannel,stiffness[0]), - KX_PYATTRIBUTE_FLOAT_RO("ik_stiffness_y",bPoseChannel,stiffness[1]), - KX_PYATTRIBUTE_FLOAT_RO("ik_stiffness_z",bPoseChannel,stiffness[2]), - KX_PYATTRIBUTE_FLOAT_RO("ik_stretch",bPoseChannel,ikstretch), - KX_PYATTRIBUTE_FLOAT_RW("ik_rot_weight",0,1.0f,bPoseChannel,ikrotweight), - KX_PYATTRIBUTE_FLOAT_RW("ik_lin_weight",0,1.0f,bPoseChannel,iklinweight), - KX_PYATTRIBUTE_RW_FUNCTION("joint_rotation",BL_ArmatureChannel,py_attr_get_joint_rotation,py_attr_set_joint_rotation), - { NULL } //Sentinel -}; - -PyObject *BL_ArmatureChannel::py_attr_getattr(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef) -{ - BL_ArmatureChannel* self = static_cast(self_v); - bPoseChannel* channel = self->m_posechannel; - int attr_order = attrdef-Attributes; - - if (!channel) { - PyErr_SetString(PyExc_AttributeError, "channel is NULL"); - return NULL; - } - - switch (attr_order) { - case BCA_BONE: - // bones are standalone proxy - return NewProxyPlus_Ext(NULL,&BL_ArmatureBone::Type,channel->bone,false); - case BCA_PARENT: - { - BL_ArmatureChannel* parent = self->m_armature->GetChannel(channel->parent); - if (parent) - return parent->GetProxy(); - else - Py_RETURN_NONE; - } - } - PyErr_SetString(PyExc_AttributeError, "channel unknown attribute"); - return NULL; -} - -int BL_ArmatureChannel::py_attr_setattr(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - BL_ArmatureChannel* self = static_cast(self_v); - bPoseChannel* channel = self->m_posechannel; - int attr_order = attrdef-Attributes; - -// int ival; -// double dval; -// char* sval; -// KX_GameObject *oval; - - if (!channel) { - PyErr_SetString(PyExc_AttributeError, "channel is NULL"); - return PY_SET_ATTR_FAIL; - } - - switch (attr_order) { - default: - break; - } - - PyErr_SetString(PyExc_AttributeError, "channel unknown attribute"); - return PY_SET_ATTR_FAIL; -} - -PyObject *BL_ArmatureChannel::py_attr_get_joint_rotation(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef) -{ - bPoseChannel* pchan = static_cast(self_v); - // decompose the pose matrix in euler rotation - float rest_mat[3][3]; - float pose_mat[3][3]; - float joint_mat[3][3]; - float joints[3]; - float norm; - double sa, ca; - // get rotation in armature space - copy_m3_m4(pose_mat, pchan->pose_mat); - normalize_m3(pose_mat); - if (pchan->parent) { - // bone has a parent, compute the rest pose of the bone taking actual pose of parent - mul_m3_m3m4(rest_mat, pchan->parent->pose_mat, pchan->bone->bone_mat); - normalize_m3(rest_mat); - } else { - // otherwise, the bone matrix in armature space is the rest pose - copy_m3_m4(rest_mat, pchan->bone->arm_mat); - } - // remove the rest pose to get the joint movement - transpose_m3(rest_mat); - mul_m3_m3m3(joint_mat, rest_mat, pose_mat); - joints[0] = joints[1] = joints[2] = 0.f; - // returns a 3 element list that gives corresponding joint - int flag = 0; - if (!(pchan->ikflag & BONE_IK_NO_XDOF)) - flag |= 1; - if (!(pchan->ikflag & BONE_IK_NO_YDOF)) - flag |= 2; - if (!(pchan->ikflag & BONE_IK_NO_ZDOF)) - flag |= 4; - switch (flag) { - case 0: // fixed joint - break; - case 1: // X only - mat3_to_eulO( joints, EULER_ORDER_XYZ,joint_mat); - joints[1] = joints[2] = 0.f; - break; - case 2: // Y only - mat3_to_eulO( joints, EULER_ORDER_XYZ,joint_mat); - joints[0] = joints[2] = 0.f; - break; - case 3: // X+Y - mat3_to_eulO( joints, EULER_ORDER_ZYX,joint_mat); - joints[2] = 0.f; - break; - case 4: // Z only - mat3_to_eulO( joints, EULER_ORDER_XYZ,joint_mat); - joints[0] = joints[1] = 0.f; - break; - case 5: // X+Z - // decompose this as an equivalent rotation vector in X/Z plane - joints[0] = joint_mat[1][2]; - joints[2] = -joint_mat[1][0]; - norm = normalize_v3(joints); - if (norm < FLT_EPSILON) { - norm = (joint_mat[1][1] < 0.0f) ? (float)M_PI : 0.0f; - } else { - norm = acos(joint_mat[1][1]); - } - mul_v3_fl(joints, norm); - break; - case 6: // Y+Z - mat3_to_eulO( joints, EULER_ORDER_XYZ,joint_mat); - joints[0] = 0.f; - break; - case 7: // X+Y+Z - // equivalent axis - joints[0] = (joint_mat[1][2]-joint_mat[2][1])*0.5f; - joints[1] = (joint_mat[2][0]-joint_mat[0][2])*0.5f; - joints[2] = (joint_mat[0][1]-joint_mat[1][0])*0.5f; - sa = len_v3(joints); - ca = (joint_mat[0][0]+joint_mat[1][1]+joint_mat[1][1]-1.0f)*0.5f; - if (sa > (double)FLT_EPSILON) { - norm = atan2(sa,ca)/sa; - } else { - if (ca < 0.0) { - norm = M_PI; - mul_v3_fl(joints,0.f); - if (joint_mat[0][0] > 0.f) { - joints[0] = 1.0f; - } else if (joint_mat[1][1] > 0.f) { - joints[1] = 1.0f; - } else { - joints[2] = 1.0f; - } - } else { - norm = 0.0; - } - } - mul_v3_fl(joints,norm); - break; - } - return Vector_CreatePyObject(joints, 3, NULL); -} - -int BL_ArmatureChannel::py_attr_set_joint_rotation(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - BL_ArmatureChannel* self = static_cast(self_v); - bPoseChannel* pchan = self->m_posechannel; - PyObject *item; - float joints[3]; - float quat[4]; - - if (!PySequence_Check(value) || PySequence_Size(value) != 3) { - PyErr_SetString(PyExc_AttributeError, "expected a sequence of 3 floats"); - return PY_SET_ATTR_FAIL; - } - for (int i=0; i<3; i++) { - item = PySequence_GetItem(value, i); /* new ref */ - joints[i] = PyFloat_AsDouble(item); - Py_DECREF(item); - if (joints[i] == -1.0f && PyErr_Occurred()) { - PyErr_SetString(PyExc_AttributeError, "expected a sequence of 3 floats"); - return PY_SET_ATTR_FAIL; - } - } - - int flag = 0; - if (!(pchan->ikflag & BONE_IK_NO_XDOF)) - flag |= 1; - if (!(pchan->ikflag & BONE_IK_NO_YDOF)) - flag |= 2; - if (!(pchan->ikflag & BONE_IK_NO_ZDOF)) - flag |= 4; - unit_qt(quat); - switch (flag) { - case 0: // fixed joint - break; - case 1: // X only - joints[1] = joints[2] = 0.f; - eulO_to_quat( quat,joints, EULER_ORDER_XYZ); - break; - case 2: // Y only - joints[0] = joints[2] = 0.f; - eulO_to_quat( quat,joints, EULER_ORDER_XYZ); - break; - case 3: // X+Y - joints[2] = 0.f; - eulO_to_quat( quat,joints, EULER_ORDER_ZYX); - break; - case 4: // Z only - joints[0] = joints[1] = 0.f; - eulO_to_quat( quat,joints, EULER_ORDER_XYZ); - break; - case 5: // X+Z - // X and Z are components of an equivalent rotation axis - joints[1] = 0; - axis_angle_to_quat( quat,joints, len_v3(joints)); - break; - case 6: // Y+Z - joints[0] = 0.f; - eulO_to_quat( quat,joints, EULER_ORDER_XYZ); - break; - case 7: // X+Y+Z - // equivalent axis - axis_angle_to_quat( quat,joints, len_v3(joints)); - break; - } - if (pchan->rotmode > 0) { - quat_to_eulO( joints, pchan->rotmode,quat); - copy_v3_v3(pchan->eul, joints); - } else - copy_qt_qt(pchan->quat, quat); - return PY_SET_ATTR_SUCCESS; -} - -// ************************* -// BL_ArmatureBone -// -// Access to Bone structure -PyTypeObject BL_ArmatureBone::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "BL_ArmatureBone", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_bone_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 -}; - -// not used since this class is never instantiated -PyObject *BL_ArmatureBone::GetProxy() -{ - return NULL; -} -PyObject *BL_ArmatureBone::NewProxy(bool py_owns) -{ - return NULL; -} - -PyObject *BL_ArmatureBone::py_bone_repr(PyObject *self) -{ - Bone* bone = static_castBGE_PROXY_PTR(self); - return PyUnicode_FromString(bone->name); -} - -PyMethodDef BL_ArmatureBone::Methods[] = { - {NULL,NULL} //Sentinel -}; - -/* no attributes on C++ class since it is never instantiated */ -PyAttributeDef BL_ArmatureBone::Attributes[] = { - { NULL } //Sentinel -}; - -// attributes that work on proxy ptr (points to a Bone structure) -PyAttributeDef BL_ArmatureBone::AttributesPtr[] = { - KX_PYATTRIBUTE_CHAR_RO("name",Bone,name), - KX_PYATTRIBUTE_FLAG_RO("connected",Bone,flag, BONE_CONNECTED), - KX_PYATTRIBUTE_FLAG_RO("hinge",Bone,flag, BONE_HINGE), - KX_PYATTRIBUTE_FLAG_NEGATIVE_RO("inherit_scale",Bone,flag, BONE_NO_SCALE), - KX_PYATTRIBUTE_SHORT_RO("bbone_segments",Bone,segments), - KX_PYATTRIBUTE_FLOAT_RO("roll",Bone,roll), - KX_PYATTRIBUTE_FLOAT_VECTOR_RO("head",Bone,head,3), - KX_PYATTRIBUTE_FLOAT_VECTOR_RO("tail",Bone,tail,3), - KX_PYATTRIBUTE_FLOAT_RO("length",Bone,length), - KX_PYATTRIBUTE_FLOAT_VECTOR_RO("arm_head",Bone,arm_head,3), - KX_PYATTRIBUTE_FLOAT_VECTOR_RO("arm_tail",Bone,arm_tail,3), - KX_PYATTRIBUTE_FLOAT_MATRIX_RO("arm_mat",Bone,arm_mat,4), - KX_PYATTRIBUTE_FLOAT_MATRIX_RO("bone_mat",Bone,bone_mat,3), - KX_PYATTRIBUTE_RO_FUNCTION("parent",BL_ArmatureBone,py_bone_get_parent), - KX_PYATTRIBUTE_RO_FUNCTION("children",BL_ArmatureBone,py_bone_get_children), - { NULL } //Sentinel -}; - -PyObject *BL_ArmatureBone::py_bone_get_parent(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef) -{ - Bone* bone = reinterpret_cast(self); - if (bone->parent) { - // create a proxy unconnected to any GE object - return NewProxyPlus_Ext(NULL,&Type,bone->parent,false); - } - Py_RETURN_NONE; -} - -PyObject *BL_ArmatureBone::py_bone_get_children(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef) -{ - Bone* bone = reinterpret_cast(self); - Bone* child; - int count = 0; - for (child = (Bone *)bone->childbase.first; child; child = child->next) - count++; - - PyObject *childrenlist = PyList_New(count); - - for (count = 0, child = (Bone *)bone->childbase.first; child; child = child->next, ++count) - PyList_SET_ITEM(childrenlist,count,NewProxyPlus_Ext(NULL,&Type,child,false)); - - return childrenlist; -} - -#endif // WITH_PYTHON diff --git a/source/gameengine/Converter/BL_ArmatureChannel.h b/source/gameengine/Converter/BL_ArmatureChannel.h deleted file mode 100644 index a07097f8178..00000000000 --- a/source/gameengine/Converter/BL_ArmatureChannel.h +++ /dev/null @@ -1,101 +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 BL_ArmatureChannel.h - * \ingroup bgeconv - */ - -#ifndef __BL_ARMATURECHANNEL_H__ -#define __BL_ARMATURECHANNEL_H__ - -#include "DNA_action_types.h" -#include "CTR_HashedPtr.h" -#include "CTR_Map.h" -#include "EXP_PyObjectPlus.h" - -class SCA_IObject; -class KX_GameObject; -class BL_ArmatureObject; -struct bConstraint; -struct bPoseChannel; -struct Object; -struct bPose; - -class BL_ArmatureChannel : public PyObjectPlus -{ - // use Py_HeaderPtr since we use generic pointer in proxy - Py_HeaderPtr; - -private: - friend class BL_ArmatureObject; - struct bPoseChannel* m_posechannel; - BL_ArmatureObject* m_armature; - -public: - BL_ArmatureChannel(class BL_ArmatureObject *armature, - struct bPoseChannel *posechannel); - virtual ~BL_ArmatureChannel(); - - inline const char *GetName() - { - return m_posechannel->name; - } - -#ifdef WITH_PYTHON - // Python access - virtual PyObject *py_repr(void); - - static PyObject *py_attr_getattr(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - static int py_attr_setattr(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject *py_attr_get_joint_rotation(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - static int py_attr_set_joint_rotation(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); -#endif /* WITH_PYTHON */ -}; - -/* this is a factory class to access bBone data field in the GE. - * It's not supposed to be instantiated, we only need it for the Attributes and Method array. - * The actual proxy object will be manually created using NewProxyPtr */ -class BL_ArmatureBone : public PyObjectPlus -{ - // use Py_HeaderPtr since we use generic pointer in proxy - Py_HeaderPtr; -private: - // make constructor private to make sure no one tries to instantiate this class - BL_ArmatureBone() {} - virtual ~BL_ArmatureBone() {} - -public: - -#ifdef WITH_PYTHON - static PyObject *py_bone_repr(PyObject *self); - static PyObject *py_bone_get_parent(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *py_bone_get_children(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); -#endif - -}; - -#endif /* __BL_ARMATURECHANNEL_H__ */ diff --git a/source/gameengine/Converter/BL_ArmatureConstraint.cpp b/source/gameengine/Converter/BL_ArmatureConstraint.cpp deleted file mode 100644 index d0c7e061fb7..00000000000 --- a/source/gameengine/Converter/BL_ArmatureConstraint.cpp +++ /dev/null @@ -1,456 +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/Converter/BL_ArmatureConstraint.cpp - * \ingroup bgeconv - */ - - -#include "DNA_constraint_types.h" -#include "DNA_action_types.h" -#include "BL_ArmatureConstraint.h" -#include "BL_ArmatureObject.h" -#include "BLI_math.h" -#include "BLI_string.h" -#include "KX_PythonInit.h" - -#ifdef WITH_PYTHON - -PyTypeObject BL_ArmatureConstraint::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "BL_ArmatureConstraint", - 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 -}; - -PyObject *BL_ArmatureConstraint::py_repr(void) -{ - return PyUnicode_FromString(m_name); -} - -#endif // WITH_PYTHON - -BL_ArmatureConstraint::BL_ArmatureConstraint( - BL_ArmatureObject *armature, - bPoseChannel *posechannel, - bConstraint *constraint, - KX_GameObject* target, - KX_GameObject* subtarget) - : PyObjectPlus(), m_constraint(constraint), m_posechannel(posechannel), m_armature(armature) -{ - m_target = target; - m_blendtarget = (target) ? target->GetBlenderObject() : NULL; - m_subtarget = subtarget; - m_blendsubtarget = (subtarget) ? subtarget->GetBlenderObject() : NULL; - m_pose = m_subpose = NULL; - if (m_blendtarget) { - copy_m4_m4(m_blendmat, m_blendtarget->obmat); - if (m_blendtarget->type == OB_ARMATURE) - m_pose = m_blendtarget->pose; - } - if (m_blendsubtarget) { - copy_m4_m4(m_blendsubmat, m_blendsubtarget->obmat); - if (m_blendsubtarget->type == OB_ARMATURE) - m_subpose = m_blendsubtarget->pose; - } - if (m_target) - m_target->RegisterObject(m_armature); - if (m_subtarget) - m_subtarget->RegisterObject(m_armature); - BLI_snprintf(m_name, sizeof(m_name), "%s:%s", m_posechannel->name, m_constraint->name); -} - -BL_ArmatureConstraint::~BL_ArmatureConstraint() -{ - if (m_target) - m_target->UnregisterObject(m_armature); - if (m_subtarget) - m_subtarget->UnregisterObject(m_armature); -} - -BL_ArmatureConstraint* BL_ArmatureConstraint::GetReplica() const -{ - BL_ArmatureConstraint* replica = new BL_ArmatureConstraint(*this); - replica->ProcessReplica(); - return replica; -} - -void BL_ArmatureConstraint::ReParent(BL_ArmatureObject* armature) -{ - m_armature = armature; - if (m_target) - m_target->RegisterObject(armature); - if (m_subtarget) - m_subtarget->RegisterObject(armature); - // find the corresponding constraint in the new armature object - if (m_constraint) { - bPose* newpose = armature->GetOrigPose(); - char* constraint = m_constraint->name; - char* posechannel = m_posechannel->name; - bPoseChannel* pchan; - bConstraint* pcon; - m_constraint = NULL; - m_posechannel = NULL; - // and locate the constraint - for (pchan = (bPoseChannel*)newpose->chanbase.first; pchan; pchan = (bPoseChannel*)pchan->next) { - if (!strcmp(pchan->name, posechannel)) { - // now locate the constraint - for (pcon = (bConstraint *)pchan->constraints.first; pcon; pcon = (bConstraint *)pcon->next) { - if (!strcmp(pcon->name, constraint)) { - m_constraint = pcon; - m_posechannel = pchan; - break; - } - } - break; - } - } - } -} - -void BL_ArmatureConstraint::Relink(CTR_Map *obj_map) -{ - void **h_obj = (*obj_map)[m_target]; - if (h_obj) { - m_target->UnregisterObject(m_armature); - m_target = (KX_GameObject*)(*h_obj); - m_target->RegisterObject(m_armature); - } - h_obj = (*obj_map)[m_subtarget]; - if (h_obj) { - m_subtarget->UnregisterObject(m_armature); - m_subtarget = (KX_GameObject*)(*h_obj); - m_subtarget->RegisterObject(m_armature); - } -} - -bool BL_ArmatureConstraint::UnlinkObject(SCA_IObject* clientobj) -{ - bool res=false; - if (clientobj == m_target) { - m_target = NULL; - res = true; - } - if (clientobj == m_subtarget) { - m_subtarget = NULL; - res = true; - } - return res; -} - -void BL_ArmatureConstraint::UpdateTarget() -{ - if (m_constraint && !(m_constraint->flag&CONSTRAINT_OFF) && (!m_blendtarget || m_target)) { - if (m_blendtarget) { - // external target, must be updated - m_target->UpdateBlenderObjectMatrix(m_blendtarget); - if (m_pose && m_target->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE) - // update the pose in case a bone is specified in the constraint target - m_blendtarget->pose = ((BL_ArmatureObject*)m_target)->GetOrigPose(); - } - if (m_blendsubtarget && m_subtarget) { - m_subtarget->UpdateBlenderObjectMatrix(m_blendsubtarget); - if (m_subpose && m_subtarget->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE) - m_blendsubtarget->pose = ((BL_ArmatureObject*)m_subtarget)->GetOrigPose(); - } - } -} - -void BL_ArmatureConstraint::RestoreTarget() -{ - if (m_constraint && !(m_constraint->flag&CONSTRAINT_OFF) && (!m_blendtarget || m_target)) { - if (m_blendtarget) { - copy_m4_m4(m_blendtarget->obmat, m_blendmat); - if (m_pose) - m_blendtarget->pose = m_pose; - } - if (m_blendsubtarget && m_subtarget) { - copy_m4_m4(m_blendsubtarget->obmat, m_blendsubmat); - if (m_subpose) - m_blendsubtarget->pose = m_subpose; - } - } -} - -bool BL_ArmatureConstraint::Match(const char* posechannel, const char* constraint) -{ - return (!strcmp(m_posechannel->name, posechannel) && !strcmp(m_constraint->name, constraint)); -} - -void BL_ArmatureConstraint::SetTarget(KX_GameObject* target) -{ - if (m_blendtarget) { - if (target != m_target) { - m_target->UnregisterObject(m_armature); - m_target = target; - if (m_target) - m_target->RegisterObject(m_armature); - } - } - -} - -void BL_ArmatureConstraint::SetSubtarget(KX_GameObject* subtarget) -{ - if (m_blendsubtarget) { - if (subtarget != m_subtarget) { - m_subtarget->UnregisterObject(m_armature); - m_subtarget = subtarget; - if (m_subtarget) - m_subtarget->RegisterObject(m_armature); - } - } - -} - -#ifdef WITH_PYTHON - -// PYTHON - -PyMethodDef BL_ArmatureConstraint::Methods[] = { - {NULL,NULL} //Sentinel -}; - -// order of definition of attributes, must match Attributes[] array -#define BCA_TYPE 0 -#define BCA_NAME 1 -#define BCA_ENFORCE 2 -#define BCA_HEADTAIL 3 -#define BCA_LINERROR 4 -#define BCA_ROTERROR 5 -#define BCA_TARGET 6 -#define BCA_SUBTARGET 7 -#define BCA_ACTIVE 8 -#define BCA_IKWEIGHT 9 -#define BCA_IKTYPE 10 -#define BCA_IKFLAG 11 -#define BCA_IKDIST 12 -#define BCA_IKMODE 13 - -PyAttributeDef BL_ArmatureConstraint::Attributes[] = { - // Keep these attributes in order of BCA_ defines!!! used by py_attr_getattr and py_attr_setattr - KX_PYATTRIBUTE_RO_FUNCTION("type",BL_ArmatureConstraint,py_attr_getattr), - KX_PYATTRIBUTE_RO_FUNCTION("name",BL_ArmatureConstraint,py_attr_getattr), - KX_PYATTRIBUTE_RW_FUNCTION("enforce",BL_ArmatureConstraint,py_attr_getattr,py_attr_setattr), - KX_PYATTRIBUTE_RW_FUNCTION("headtail",BL_ArmatureConstraint,py_attr_getattr,py_attr_setattr), - KX_PYATTRIBUTE_RO_FUNCTION("lin_error",BL_ArmatureConstraint,py_attr_getattr), - KX_PYATTRIBUTE_RO_FUNCTION("rot_error",BL_ArmatureConstraint,py_attr_getattr), - KX_PYATTRIBUTE_RW_FUNCTION("target",BL_ArmatureConstraint,py_attr_getattr,py_attr_setattr), - KX_PYATTRIBUTE_RW_FUNCTION("subtarget",BL_ArmatureConstraint,py_attr_getattr,py_attr_setattr), - KX_PYATTRIBUTE_RW_FUNCTION("active",BL_ArmatureConstraint,py_attr_getattr,py_attr_setattr), - KX_PYATTRIBUTE_RW_FUNCTION("ik_weight",BL_ArmatureConstraint,py_attr_getattr,py_attr_setattr), - KX_PYATTRIBUTE_RO_FUNCTION("ik_type",BL_ArmatureConstraint,py_attr_getattr), - KX_PYATTRIBUTE_RO_FUNCTION("ik_flag",BL_ArmatureConstraint,py_attr_getattr), - KX_PYATTRIBUTE_RW_FUNCTION("ik_dist",BL_ArmatureConstraint,py_attr_getattr,py_attr_setattr), - KX_PYATTRIBUTE_RW_FUNCTION("ik_mode",BL_ArmatureConstraint,py_attr_getattr,py_attr_setattr), - - { NULL } //Sentinel -}; - - -PyObject *BL_ArmatureConstraint::py_attr_getattr(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef) -{ - BL_ArmatureConstraint* self = static_cast(self_v); - bConstraint* constraint = self->m_constraint; - bKinematicConstraint* ikconstraint = (constraint && constraint->type == CONSTRAINT_TYPE_KINEMATIC) ? (bKinematicConstraint*)constraint->data : NULL; - int attr_order = attrdef-Attributes; - - if (!constraint) { - PyErr_SetString(PyExc_AttributeError, "constraint is NULL"); - return NULL; - } - - switch (attr_order) { - case BCA_TYPE: - return PyLong_FromLong(constraint->type); - case BCA_NAME: - return PyUnicode_FromString(constraint->name); - case BCA_ENFORCE: - return PyFloat_FromDouble(constraint->enforce); - case BCA_HEADTAIL: - return PyFloat_FromDouble(constraint->headtail); - case BCA_LINERROR: - return PyFloat_FromDouble(constraint->lin_error); - case BCA_ROTERROR: - return PyFloat_FromDouble(constraint->rot_error); - case BCA_TARGET: - if (!self->m_target) - Py_RETURN_NONE; - else - return self->m_target->GetProxy(); - case BCA_SUBTARGET: - if (!self->m_subtarget) - Py_RETURN_NONE; - else - return self->m_subtarget->GetProxy(); - case BCA_ACTIVE: - return PyBool_FromLong((constraint->flag & CONSTRAINT_OFF) == 0); - case BCA_IKWEIGHT: - case BCA_IKTYPE: - case BCA_IKFLAG: - case BCA_IKDIST: - case BCA_IKMODE: - if (!ikconstraint) { - PyErr_SetString(PyExc_AttributeError, "constraint is not of IK type"); - return NULL; - } - switch (attr_order) { - case BCA_IKWEIGHT: - return PyFloat_FromDouble(ikconstraint->weight); - case BCA_IKTYPE: - return PyLong_FromLong(ikconstraint->type); - case BCA_IKFLAG: - return PyLong_FromLong(ikconstraint->flag); - case BCA_IKDIST: - return PyFloat_FromDouble(ikconstraint->dist); - case BCA_IKMODE: - return PyLong_FromLong(ikconstraint->mode); - } - // should not come here - break; - } - PyErr_SetString(PyExc_AttributeError, "constraint unknown attribute"); - return NULL; -} - -int BL_ArmatureConstraint::py_attr_setattr(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - BL_ArmatureConstraint* self = static_cast(self_v); - bConstraint* constraint = self->m_constraint; - bKinematicConstraint* ikconstraint = (constraint && constraint->type == CONSTRAINT_TYPE_KINEMATIC) ? (bKinematicConstraint*)constraint->data : NULL; - int attr_order = attrdef-Attributes; - int ival; - double dval; -// char* sval; - SCA_LogicManager *logicmgr = KX_GetActiveScene()->GetLogicManager(); - KX_GameObject *oval; - - if (!constraint) { - PyErr_SetString(PyExc_AttributeError, "constraint is NULL"); - return PY_SET_ATTR_FAIL; - } - - switch (attr_order) { - case BCA_ENFORCE: - dval = PyFloat_AsDouble(value); - if (dval < 0.0 || dval > 1.0) { /* also accounts for non float */ - PyErr_SetString(PyExc_AttributeError, "constraint.enforce = float: BL_ArmatureConstraint, expected a float between 0 and 1"); - return PY_SET_ATTR_FAIL; - } - constraint->enforce = dval; - return PY_SET_ATTR_SUCCESS; - - case BCA_HEADTAIL: - dval = PyFloat_AsDouble(value); - if (dval < 0.0 || dval > 1.0) { /* also accounts for non float */ - PyErr_SetString(PyExc_AttributeError, "constraint.headtail = float: BL_ArmatureConstraint, expected a float between 0 and 1"); - return PY_SET_ATTR_FAIL; - } - constraint->headtail = dval; - return PY_SET_ATTR_SUCCESS; - - case BCA_TARGET: - if (!ConvertPythonToGameObject(logicmgr, value, &oval, true, "constraint.target = value: BL_ArmatureConstraint")) - return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error - self->SetTarget(oval); - return PY_SET_ATTR_SUCCESS; - - case BCA_SUBTARGET: - if (!ConvertPythonToGameObject(logicmgr, value, &oval, true, "constraint.subtarget = value: BL_ArmatureConstraint")) - return PY_SET_ATTR_FAIL; // ConvertPythonToGameObject sets the error - self->SetSubtarget(oval); - return PY_SET_ATTR_SUCCESS; - - case BCA_ACTIVE: - ival = PyObject_IsTrue( value ); - if (ival == -1) { - PyErr_SetString(PyExc_AttributeError, "constraint.active = bool: BL_ArmatureConstraint, expected True or False"); - return PY_SET_ATTR_FAIL; - } - self->m_constraint->flag = (self->m_constraint->flag & ~CONSTRAINT_OFF) | ((ival)?0:CONSTRAINT_OFF); - return PY_SET_ATTR_SUCCESS; - - case BCA_IKWEIGHT: - case BCA_IKDIST: - case BCA_IKMODE: - if (!ikconstraint) { - PyErr_SetString(PyExc_AttributeError, "constraint is not of IK type"); - return PY_SET_ATTR_FAIL; - } - switch (attr_order) { - case BCA_IKWEIGHT: - dval = PyFloat_AsDouble(value); - if (dval < 0.0 || dval > 1.0) { /* also accounts for non float */ - PyErr_SetString(PyExc_AttributeError, "constraint.weight = float: BL_ArmatureConstraint, expected a float between 0 and 1"); - return PY_SET_ATTR_FAIL; - } - ikconstraint->weight = dval; - return PY_SET_ATTR_SUCCESS; - - case BCA_IKDIST: - dval = PyFloat_AsDouble(value); - if (dval < 0.0) { /* also accounts for non float */ - PyErr_SetString(PyExc_AttributeError, "constraint.ik_dist = float: BL_ArmatureConstraint, expected a positive float"); - return PY_SET_ATTR_FAIL; - } - ikconstraint->dist = dval; - return PY_SET_ATTR_SUCCESS; - - case BCA_IKMODE: - ival = PyLong_AsLong(value); - if (ival < 0) { - PyErr_SetString(PyExc_AttributeError, "constraint.ik_mode = integer: BL_ArmatureConstraint, expected a positive integer"); - return PY_SET_ATTR_FAIL; - } - ikconstraint->mode = ival; - return PY_SET_ATTR_SUCCESS; - } - // should not come here - break; - - } - - PyErr_SetString(PyExc_AttributeError, "constraint unknown attribute"); - return PY_SET_ATTR_FAIL; -} - -#endif // WITH_PYTHON diff --git a/source/gameengine/Converter/BL_ArmatureConstraint.h b/source/gameengine/Converter/BL_ArmatureConstraint.h deleted file mode 100644 index 1d9f7f0d548..00000000000 --- a/source/gameengine/Converter/BL_ArmatureConstraint.h +++ /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 BL_ArmatureConstraint.h - * \ingroup bgeconv - */ - -#ifndef __BL_ARMATURECONSTRAINT_H__ -#define __BL_ARMATURECONSTRAINT_H__ - -#include "DNA_constraint_types.h" -#include "CTR_HashedPtr.h" -#include "CTR_Map.h" -#include "EXP_PyObjectPlus.h" - -class SCA_IObject; -class KX_GameObject; -class BL_ArmatureObject; -struct bConstraint; -struct bPoseChannel; -struct Object; -struct bPose; - -/** - * SG_DList : element of controlled constraint list - * head = BL_ArmatureObject::m_controlledConstraints - * SG_QList : not used - */ -class BL_ArmatureConstraint : public PyObjectPlus -{ - Py_Header - -private: - struct bConstraint* m_constraint; - struct bPoseChannel* m_posechannel; - class BL_ArmatureObject* m_armature; - char m_name[64]; - KX_GameObject* m_target; - KX_GameObject* m_subtarget; - struct Object* m_blendtarget; - struct Object* m_blendsubtarget; - float m_blendmat[4][4]; - float m_blendsubmat[4][4]; - struct bPose* m_pose; - struct bPose* m_subpose; - -public: - BL_ArmatureConstraint(class BL_ArmatureObject *armature, - struct bPoseChannel *posechannel, - struct bConstraint *constraint, - KX_GameObject* target, - KX_GameObject* subtarget); - virtual ~BL_ArmatureConstraint(); - - BL_ArmatureConstraint* GetReplica() const; - void ReParent(BL_ArmatureObject* armature); - void Relink(CTR_Map *map); - bool UnlinkObject(SCA_IObject* clientobj); - - void UpdateTarget(); - void RestoreTarget(); - - bool Match(const char* posechannel, const char* constraint); - const char* GetName() { return m_name; } - - void SetConstraintFlag(int flag) - { - if (m_constraint) - m_constraint->flag |= flag; - } - void ClrConstraintFlag(int flag) - { - if (m_constraint) - m_constraint->flag &= ~flag; - } - void SetWeight(float weight) - { - if (m_constraint && m_constraint->type == CONSTRAINT_TYPE_KINEMATIC && m_constraint->data) { - bKinematicConstraint* con = (bKinematicConstraint*)m_constraint->data; - con->weight = weight; - } - } - void SetInfluence(float influence) - { - if (m_constraint) - m_constraint->enforce = influence; - } - void SetTarget(KX_GameObject* target); - void SetSubtarget(KX_GameObject* subtarget); - -#ifdef WITH_PYTHON - - // Python access - virtual PyObject *py_repr(void); - - static PyObject *py_attr_getattr(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - static int py_attr_setattr(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); -#endif /* WITH_PYTHON */ -}; - -#endif /* __BL_ARMATURECONSTRAINT_H__ */ diff --git a/source/gameengine/Converter/BL_ArmatureObject.cpp b/source/gameengine/Converter/BL_ArmatureObject.cpp deleted file mode 100644 index 049fd49cab9..00000000000 --- a/source/gameengine/Converter/BL_ArmatureObject.cpp +++ /dev/null @@ -1,691 +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/Converter/BL_ArmatureObject.cpp - * \ingroup bgeconv - */ - - -#include "BL_ArmatureObject.h" -#include "BL_ActionActuator.h" -#include "BL_Action.h" -#include "KX_BlenderSceneConverter.h" -#include "MEM_guardedalloc.h" -#include "BLI_blenlib.h" -#include "BLI_math.h" -#include "BLI_utildefines.h" -#include "BLI_ghash.h" -#include "BIK_api.h" -#include "BKE_action.h" -#include "BKE_armature.h" -#include "BKE_object.h" -#include "BKE_library.h" -#include "BKE_global.h" - -extern "C" { -#include "BKE_animsys.h" -} - -#include "BKE_constraint.h" -#include "CTR_Map.h" -#include "CTR_HashedPtr.h" -#include "MEM_guardedalloc.h" -#include "DNA_action_types.h" -#include "DNA_armature_types.h" -#include "DNA_object_types.h" -#include "DNA_scene_types.h" -#include "DNA_constraint_types.h" -#include "RNA_access.h" -#include "KX_PythonInit.h" -#include "KX_KetsjiEngine.h" - -#include "EXP_ListWrapper.h" - -#include "MT_Matrix4x4.h" - -/** - * Move here pose function for game engine so that we can mix with GE objects - * Principle is as follow: - * Use Blender structures so that BKE_pose_where_is can be used unchanged - * Copy the constraint so that they can be enabled/disabled/added/removed at runtime - * Don't copy the constraints for the pose used by the Action actuator, it does not need them. - * Scan the constraint structures so that the KX equivalent of target objects are identified and - * stored in separate list. - * When it is about to evaluate the pose, set the KX object position in the obmat of the corresponding - * Blender objects and restore after the evaluation. - */ -static void game_copy_pose(bPose **dst, bPose *src, int copy_constraint) -{ - bPose *out; - bPoseChannel *pchan, *outpchan; - GHash *ghash; - - /* the game engine copies the current armature pose and then swaps - * the object pose pointer. this makes it possible to change poses - * without affecting the original blender data. */ - - if (!src) { - *dst=NULL; - return; - } - else if (*dst==src) { - printf("game_copy_pose source and target are the same\n"); - *dst=NULL; - return; - } - - out= (bPose*)MEM_dupallocN(src); - out->chanhash = NULL; - out->agroups.first= out->agroups.last= NULL; - out->ikdata = NULL; - out->ikparam = MEM_dupallocN(src->ikparam); - out->flag |= POSE_GAME_ENGINE; - BLI_duplicatelist(&out->chanbase, &src->chanbase); - - /* remap pointers */ - ghash= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, "game_copy_pose gh"); - - pchan= (bPoseChannel *)src->chanbase.first; - outpchan= (bPoseChannel *)out->chanbase.first; - for (; pchan; pchan=pchan->next, outpchan=outpchan->next) - BLI_ghash_insert(ghash, pchan, outpchan); - - for (pchan = (bPoseChannel *)out->chanbase.first; pchan; pchan = pchan->next) { - pchan->parent= (bPoseChannel *)BLI_ghash_lookup(ghash, pchan->parent); - pchan->child= (bPoseChannel *)BLI_ghash_lookup(ghash, pchan->child); - - if (copy_constraint) { - ListBase listb; - // copy all constraint for backward compatibility - // BKE_constraints_copy NULLs listb, no need to make extern for this operation. - BKE_constraints_copy(&listb, &pchan->constraints, false); - pchan->constraints= listb; - } - else { - BLI_listbase_clear(&pchan->constraints); - } - - if (pchan->custom) { - id_us_plus(&pchan->custom->id); - } - - // fails to link, props are not used in the BGE yet. -#if 0 - if (pchan->prop) - pchan->prop= IDP_CopyProperty(pchan->prop); -#endif - pchan->prop = NULL; - pchan->draw_data = NULL; - } - - BLI_ghash_free(ghash, NULL, NULL); - // set acceleration structure for channel lookup - BKE_pose_channels_hash_make(out); - *dst=out; -} - - - -/* Only allowed for Poses with identical channels */ -static void game_blend_poses(bPose *dst, bPose *src, float srcweight, short mode) -{ - bPoseChannel *dchan; - const bPoseChannel *schan; - bConstraint *dcon, *scon; - float dstweight; - int i; - - if (mode == BL_Action::ACT_BLEND_BLEND) - { - dstweight = 1.0f - srcweight; - } else if (mode == BL_Action::ACT_BLEND_ADD) - { - dstweight = 1.0f; - } else { - dstweight = 1.0f; - } - - schan= (bPoseChannel *)src->chanbase.first; - for (dchan = (bPoseChannel *)dst->chanbase.first; dchan; dchan=(bPoseChannel *)dchan->next, schan= (bPoseChannel *)schan->next) { - // always blend on all channels since we don't know which one has been set - /* quat interpolation done separate */ - if (schan->rotmode == ROT_MODE_QUAT) { - float dquat[4], squat[4]; - - copy_qt_qt(dquat, dchan->quat); - copy_qt_qt(squat, schan->quat); - // Normalize quaternions so that interpolation/multiplication result is correct. - normalize_qt(dquat); - normalize_qt(squat); - - if (mode==BL_Action::ACT_BLEND_BLEND) - interp_qt_qtqt(dchan->quat, dquat, squat, srcweight); - else { - mul_fac_qt_fl(squat, srcweight); - mul_qt_qtqt(dchan->quat, dquat, squat); - } - - normalize_qt(dchan->quat); - } - - for (i=0; i<3; i++) { - /* blending for loc and scale are pretty self-explanatory... */ - dchan->loc[i] = (dchan->loc[i]*dstweight) + (schan->loc[i]*srcweight); - dchan->size[i] = 1.0f + ((dchan->size[i]-1.0f)*dstweight) + ((schan->size[i]-1.0f)*srcweight); - - /* euler-rotation interpolation done here instead... */ - // FIXME: are these results decent? - if (schan->rotmode) - dchan->eul[i] = (dchan->eul[i]*dstweight) + (schan->eul[i]*srcweight); - } - for (dcon= (bConstraint *)dchan->constraints.first, scon= (bConstraint *)schan->constraints.first; - dcon && scon; - dcon = dcon->next, scon = scon->next) - { - /* no 'add' option for constraint blending */ - dcon->enforce= dcon->enforce*(1.0f-srcweight) + scon->enforce*srcweight; - } - } - - /* this pose is now in src time */ - dst->ctime= src->ctime; -} - -BL_ArmatureObject::BL_ArmatureObject( - void* sgReplicationInfo, - SG_Callbacks callbacks, - Object *armature, - Scene *scene, - int vert_deform_type) - -: KX_GameObject(sgReplicationInfo,callbacks), - m_controlledConstraints(), - m_poseChannels(), - m_scene(scene), // maybe remove later. needed for BKE_pose_where_is - m_lastframe(0.0), - m_timestep(0.040), - m_vert_deform_type(vert_deform_type), - m_constraintNumber(0), - m_channelNumber(0), - m_lastapplyframe(0.0) -{ - m_origObjArma = armature; // Keep a copy of the original armature so we can fix drivers later - m_objArma = BKE_object_copy(G.main, armature); - m_objArma->data = BKE_armature_copy(G.main, (bArmature *)armature->data); - // During object replication ob->data is increase, we decrease it now because we get a copy. - id_us_min(&((bArmature *)m_origObjArma->data)->id); - m_pose = m_objArma->pose; - // need this to get iTaSC working ok in the BGE - m_pose->flag |= POSE_GAME_ENGINE; - memcpy(m_obmat, m_objArma->obmat, sizeof(m_obmat)); - - // The side-effect of this method registers this object as "animatable" with the KX_Scene. - GetActionManager(); -} - -BL_ArmatureObject::~BL_ArmatureObject() -{ - BL_ArmatureConstraint* constraint; - while ((constraint = m_controlledConstraints.Remove()) != NULL) { - delete constraint; - } - BL_ArmatureChannel* channel; - while ((channel = static_cast(m_poseChannels.Remove())) != NULL) { - delete channel; - } - - if (m_objArma) { - BKE_libblock_free(G.main, m_objArma->data); - BKE_libblock_free(G.main, m_objArma); - } -} - - -void BL_ArmatureObject::LoadConstraints(KX_BlenderSceneConverter* converter) -{ - // first delete any existing constraint (should not have any) - while (!m_controlledConstraints.Empty()) { - BL_ArmatureConstraint* constraint = m_controlledConstraints.Remove(); - delete constraint; - } - m_constraintNumber = 0; - - // list all the constraint and convert them to BL_ArmatureConstraint - // get the persistent pose structure - bPoseChannel* pchan; - bConstraint* pcon; - const bConstraintTypeInfo* cti; - Object* blendtarget; - KX_GameObject* gametarget; - KX_GameObject* gamesubtarget; - - // and locate the constraint - for (pchan = (bPoseChannel *)m_pose->chanbase.first; pchan; pchan = pchan->next) { - for (pcon = (bConstraint *)pchan->constraints.first; pcon; pcon = pcon->next) { - if (pcon->flag & CONSTRAINT_DISABLE) - continue; - // which constraint should we support? - switch (pcon->type) { - case CONSTRAINT_TYPE_TRACKTO: - case CONSTRAINT_TYPE_DAMPTRACK: - case CONSTRAINT_TYPE_KINEMATIC: - case CONSTRAINT_TYPE_ROTLIKE: - case CONSTRAINT_TYPE_LOCLIKE: - case CONSTRAINT_TYPE_MINMAX: - case CONSTRAINT_TYPE_SIZELIKE: - case CONSTRAINT_TYPE_LOCKTRACK: - case CONSTRAINT_TYPE_STRETCHTO: - case CONSTRAINT_TYPE_CLAMPTO: - case CONSTRAINT_TYPE_TRANSFORM: - case CONSTRAINT_TYPE_DISTLIMIT: - case CONSTRAINT_TYPE_TRANSLIKE: - cti = BKE_constraint_typeinfo_get(pcon); - gametarget = gamesubtarget = NULL; - if (cti && cti->get_constraint_targets) { - ListBase listb = { NULL, NULL }; - cti->get_constraint_targets(pcon, &listb); - if (listb.first) { - bConstraintTarget* target = (bConstraintTarget*)listb.first; - if (target->tar && target->tar != m_objArma) { - // only remember external objects, self target is handled automatically - blendtarget = target->tar; - gametarget = converter->FindGameObject(blendtarget); - } - if (target->next != NULL) { - // secondary target - target = target->next; - if (target->tar && target->tar != m_objArma) { - // only track external object - blendtarget = target->tar; - gamesubtarget = converter->FindGameObject(blendtarget); - } - } - } - if (cti->flush_constraint_targets) - cti->flush_constraint_targets(pcon, &listb, 1); - } - BL_ArmatureConstraint* constraint = new BL_ArmatureConstraint(this, pchan, pcon, gametarget, gamesubtarget); - m_controlledConstraints.AddBack(constraint); - m_constraintNumber++; - } - } - } - - // If we have constraints, make sure we get treated as an "animated" object - if (m_constraintNumber > 0) - GetActionManager(); -} - -BL_ArmatureConstraint* BL_ArmatureObject::GetConstraint(const char* posechannel, const char* constraintname) -{ - SG_DList::iterator cit(m_controlledConstraints); - for (cit.begin(); !cit.end(); ++cit) { - BL_ArmatureConstraint* constraint = *cit; - if (constraint->Match(posechannel, constraintname)) - return constraint; - } - return NULL; -} - -BL_ArmatureConstraint* BL_ArmatureObject::GetConstraint(const char* posechannelconstraint) -{ - // performance: use hash string instead of plain string compare - SG_DList::iterator cit(m_controlledConstraints); - for (cit.begin(); !cit.end(); ++cit) { - BL_ArmatureConstraint* constraint = *cit; - if (!strcmp(constraint->GetName(), posechannelconstraint)) - return constraint; - } - return NULL; -} - -BL_ArmatureConstraint* BL_ArmatureObject::GetConstraint(int index) -{ - SG_DList::iterator cit(m_controlledConstraints); - for (cit.begin(); !cit.end() && index; ++cit, --index); - return (cit.end()) ? NULL : *cit; -} - -/* this function is called to populate the m_poseChannels list */ -void BL_ArmatureObject::LoadChannels() -{ - if (m_poseChannels.Empty()) { - bPoseChannel* pchan; - BL_ArmatureChannel* proxy; - - m_channelNumber = 0; - for (pchan = (bPoseChannel *)m_pose->chanbase.first; pchan; pchan=(bPoseChannel *)pchan->next) { - proxy = new BL_ArmatureChannel(this, pchan); - m_poseChannels.AddBack(proxy); - m_channelNumber++; - } - } -} - -BL_ArmatureChannel* BL_ArmatureObject::GetChannel(bPoseChannel* pchan) -{ - LoadChannels(); - SG_DList::iterator cit(m_poseChannels); - for (cit.begin(); !cit.end(); ++cit) - { - BL_ArmatureChannel* channel = *cit; - if (channel->m_posechannel == pchan) - return channel; - } - return NULL; -} - -BL_ArmatureChannel* BL_ArmatureObject::GetChannel(const char* str) -{ - LoadChannels(); - SG_DList::iterator cit(m_poseChannels); - for (cit.begin(); !cit.end(); ++cit) - { - BL_ArmatureChannel* channel = *cit; - if (!strcmp(channel->m_posechannel->name, str)) - return channel; - } - return NULL; -} - -BL_ArmatureChannel* BL_ArmatureObject::GetChannel(int index) -{ - LoadChannels(); - if (index < 0 || index >= m_channelNumber) - return NULL; - SG_DList::iterator cit(m_poseChannels); - for (cit.begin(); !cit.end() && index; ++cit, --index); - return (cit.end()) ? NULL : *cit; -} - -CValue* BL_ArmatureObject::GetReplica() -{ - BL_ArmatureObject* replica = new BL_ArmatureObject(*this); - replica->ProcessReplica(); - return replica; -} - -void BL_ArmatureObject::ProcessReplica() -{ - KX_GameObject::ProcessReplica(); - - bArmature* tmp = (bArmature*)m_objArma->data; - m_objArma = BKE_object_copy(G.main, m_objArma); - m_objArma->data = BKE_armature_copy(G.main, tmp); - m_pose = m_objArma->pose; -} - -void BL_ArmatureObject::ReParentLogic() -{ - SG_DList::iterator cit(m_controlledConstraints); - for (cit.begin(); !cit.end(); ++cit) { - (*cit)->ReParent(this); - } - KX_GameObject::ReParentLogic(); -} - -void BL_ArmatureObject::Relink(CTR_Map *obj_map) -{ - SG_DList::iterator cit(m_controlledConstraints); - for (cit.begin(); !cit.end(); ++cit) { - (*cit)->Relink(obj_map); - } - KX_GameObject::Relink(obj_map); -} - -bool BL_ArmatureObject::UnlinkObject(SCA_IObject* clientobj) -{ - // clientobj is being deleted, make sure we don't hold any reference to it - bool res = false; - SG_DList::iterator cit(m_controlledConstraints); - for (cit.begin(); !cit.end(); ++cit) { - res |= (*cit)->UnlinkObject(clientobj); - } - return res; -} - -void BL_ArmatureObject::ApplyPose() -{ - /* TODO: This doesn't work currently because of eval_ctx. */ -#if 0 - m_armpose = m_objArma->pose; - m_objArma->pose = m_pose; - // in the GE, we use ctime to store the timestep - m_pose->ctime = (float)m_timestep; - //m_scene->r.cfra++; - if (m_lastapplyframe != m_lastframe) { - // update the constraint if any, first put them all off so that only the active ones will be updated - SG_DList::iterator cit(m_controlledConstraints); - for (cit.begin(); !cit.end(); ++cit) { - (*cit)->UpdateTarget(); - } - // update ourself - UpdateBlenderObjectMatrix(m_objArma); - BKE_pose_where_is(m_scene, m_objArma); // XXX - // restore ourself - memcpy(m_objArma->obmat, m_obmat, sizeof(m_obmat)); - // restore active targets - for (cit.begin(); !cit.end(); ++cit) { - (*cit)->RestoreTarget(); - } - m_lastapplyframe = m_lastframe; - } -#endif -} - -void BL_ArmatureObject::RestorePose() -{ - m_objArma->pose = m_armpose; - m_armpose = NULL; -} - -void BL_ArmatureObject::SetPose(bPose *pose) -{ - extract_pose_from_pose(m_pose, pose); - m_lastapplyframe = -1.0; -} - -void BL_ArmatureObject::SetPoseByAction(bAction *action, float localtime) -{ - Object *arm = GetArmatureObject(); - - PointerRNA ptrrna; - RNA_id_pointer_create(&arm->id, &ptrrna); - - animsys_evaluate_action(&ptrrna, action, NULL, localtime); -} - -void BL_ArmatureObject::BlendInPose(bPose *blend_pose, float weight, short mode) -{ - game_blend_poses(m_pose, blend_pose, weight, mode); -} - -bool BL_ArmatureObject::UpdateTimestep(double curtime) -{ - if (curtime != m_lastframe) { - // compute the timestep for the underlying IK algorithm - m_timestep = curtime-m_lastframe; - m_lastframe= curtime; - } - - return false; -} - -void BL_ArmatureObject::GetPose(bPose **pose) -{ - /* If the caller supplies a null pose, create a new one. */ - /* Otherwise, copy the armature's pose channels into the caller-supplied pose */ - - if (!*pose) { - /* probably not to good of an idea to - * duplicate everything, but it clears up - * a crash and memory leakage when - * &BL_ActionActuator::m_pose is freed - */ - game_copy_pose(pose, m_pose, 0); - } - else { - if (*pose == m_pose) - // no need to copy if the pointers are the same - return; - - extract_pose_from_pose(*pose, m_pose); - } -} - -double BL_ArmatureObject::GetLastFrame() -{ - return m_lastframe; -} - -bool BL_ArmatureObject::GetBoneMatrix(Bone* bone, MT_Matrix4x4& matrix) -{ - bPoseChannel *pchan; - - ApplyPose(); - pchan = BKE_pose_channel_find_name(m_objArma->pose, bone->name); - if (pchan) - matrix.setValue(&pchan->pose_mat[0][0]); - RestorePose(); - - return (pchan != NULL); -} - -float BL_ArmatureObject::GetBoneLength(Bone* bone) const -{ - return (float)(MT_Point3(bone->head) - MT_Point3(bone->tail)).length(); -} - -#ifdef WITH_PYTHON - -// PYTHON - -PyTypeObject BL_ArmatureObject::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "BL_ArmatureObject", - 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 BL_ArmatureObject::Methods[] = { - KX_PYMETHODTABLE_NOARGS(BL_ArmatureObject, update), - {NULL,NULL} //Sentinel -}; - -PyAttributeDef BL_ArmatureObject::Attributes[] = { - - KX_PYATTRIBUTE_RO_FUNCTION("constraints", BL_ArmatureObject, pyattr_get_constraints), - KX_PYATTRIBUTE_RO_FUNCTION("channels", BL_ArmatureObject, pyattr_get_channels), - {NULL} //Sentinel -}; - -static int bl_armature_object_get_constraints_size_cb(void *self_v) -{ - return ((BL_ArmatureObject *)self_v)->GetConstraintNumber(); -} - -static PyObject *bl_armature_object_get_constraints_item_cb(void *self_v, int index) -{ - return ((BL_ArmatureObject *)self_v)->GetConstraint(index)->GetProxy(); -} - -static const char *bl_armature_object_get_constraints_item_name_cb(void *self_v, int index) -{ - return ((BL_ArmatureObject *)self_v)->GetConstraint(index)->GetName(); -} - -PyObject *BL_ArmatureObject::pyattr_get_constraints(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - return (new CListWrapper(self_v, - ((BL_ArmatureObject *)self_v)->GetProxy(), - NULL, - bl_armature_object_get_constraints_size_cb, - bl_armature_object_get_constraints_item_cb, - bl_armature_object_get_constraints_item_name_cb, - NULL))->NewProxy(true); -} - -static int bl_armature_object_get_channels_size_cb(void *self_v) -{ - return ((BL_ArmatureObject *)self_v)->GetChannelNumber(); -} - -static PyObject *bl_armature_object_get_channels_item_cb(void *self_v, int index) -{ - return ((BL_ArmatureObject *)self_v)->GetChannel(index)->GetProxy(); -} - -static const char *bl_armature_object_get_channels_item_name_cb(void *self_v, int index) -{ - return ((BL_ArmatureObject *)self_v)->GetChannel(index)->GetName(); -} - -PyObject *BL_ArmatureObject::pyattr_get_channels(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - BL_ArmatureObject *self = static_cast(self_v); - self->LoadChannels(); // make sure we have the channels - return (new CListWrapper(self_v, - self->GetProxy(), - NULL, - bl_armature_object_get_channels_size_cb, - bl_armature_object_get_channels_item_cb, - bl_armature_object_get_channels_item_name_cb, - NULL))->NewProxy(true); -} - -KX_PYMETHODDEF_DOC_NOARGS(BL_ArmatureObject, update, - "update()\n" - "Make sure that the armature will be updated on next graphic frame.\n" - "This is automatically done if a KX_ArmatureActuator with mode run is active\n" - "or if an action is playing. This function is useful in other cases.\n") -{ - UpdateTimestep(KX_GetActiveEngine()->GetFrameTime()); - Py_RETURN_NONE; -} - -#endif // WITH_PYTHON diff --git a/source/gameengine/Converter/BL_ArmatureObject.h b/source/gameengine/Converter/BL_ArmatureObject.h deleted file mode 100644 index 691e73d6bde..00000000000 --- a/source/gameengine/Converter/BL_ArmatureObject.h +++ /dev/null @@ -1,145 +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 BL_ArmatureObject.h - * \ingroup bgeconv - */ - -#ifndef __BL_ARMATUREOBJECT_H__ -#define __BL_ARMATUREOBJECT_H__ - -#include "KX_GameObject.h" -#include "BL_ArmatureConstraint.h" -#include "BL_ArmatureChannel.h" - -#include "SG_IObject.h" -#include -#include - -struct bArmature; -struct Bone; -struct bConstraint; -class BL_ActionActuator; -class BL_ArmatureActuator; -class MT_Matrix4x4; -struct Object; -class KX_BlenderSceneConverter; - -class BL_ArmatureObject : public KX_GameObject -{ - Py_Header -public: - - double GetLastFrame (); - virtual void ProcessReplica(); - virtual void ReParentLogic(); - virtual void Relink(CTR_Map *obj_map); - virtual bool UnlinkObject(SCA_IObject* clientobj); - - BL_ArmatureObject( - void* sgReplicationInfo, - SG_Callbacks callbacks, - Object *armature, - Scene *scene, - int vert_deform_type - ); - virtual ~BL_ArmatureObject(); - - virtual CValue* GetReplica(); - void GetPose(struct bPose **pose); - void SetPose (struct bPose *pose); - struct bPose *GetOrigPose() {return m_pose;} // never edit this, only for accessing names - - void ApplyPose(); - void SetPoseByAction(struct bAction* action, float localtime); - void BlendInPose(struct bPose *blend_pose, float weight, short mode); - void RestorePose(); - - bool UpdateTimestep(double curtime); - - struct bArmature *GetArmature() { return (bArmature*)m_objArma->data; } - const struct bArmature * GetArmature() const { return (bArmature*)m_objArma->data; } - const struct Scene * GetScene() const { return m_scene; } - - Object* GetArmatureObject() {return m_objArma;} - Object* GetOrigArmatureObject() {return m_origObjArma;} - - int GetVertDeformType() {return m_vert_deform_type;} - - // for constraint python API - void LoadConstraints(KX_BlenderSceneConverter* converter); - size_t GetConstraintNumber() const { return m_constraintNumber; } - BL_ArmatureConstraint* GetConstraint(const char* posechannel, const char* constraint); - BL_ArmatureConstraint* GetConstraint(const char* posechannelconstraint); - BL_ArmatureConstraint* GetConstraint(int index); - // for pose channel python API - void LoadChannels(); - size_t GetChannelNumber() const { return m_channelNumber; } - BL_ArmatureChannel* GetChannel(bPoseChannel* channel); - BL_ArmatureChannel* GetChannel(const char* channel); - BL_ArmatureChannel* GetChannel(int index); - - /// Retrieve the pose matrix for the specified bone. - /// Returns true on success. - bool GetBoneMatrix(Bone* bone, MT_Matrix4x4& matrix); - - /// Returns the bone length. The end of the bone is in the local y direction. - float GetBoneLength(Bone* bone) const; - - virtual int GetGameObjectType() { return OBJ_ARMATURE; } - -#ifdef WITH_PYTHON - - // PYTHON - static PyObject *pyattr_get_constraints(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_channels(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - KX_PYMETHOD_DOC_NOARGS(BL_ArmatureObject, update); - -#endif /* WITH_PYTHON */ - -protected: - /* list element: BL_ArmatureConstraint. Use SG_DListHead to have automatic list replication */ - SG_DListHead m_controlledConstraints; - /* list element: BL_ArmatureChannel. Use SG_DList to avoid list replication */ - SG_DList m_poseChannels; - Object *m_objArma; - Object *m_origObjArma; - struct bPose *m_pose; - struct bPose *m_armpose; - struct Scene *m_scene; // need for BKE_pose_where_is - double m_lastframe; - double m_timestep; // delta since last pose evaluation. - int m_vert_deform_type; - size_t m_constraintNumber; - size_t m_channelNumber; - // store the original armature object matrix - float m_obmat[4][4]; - - double m_lastapplyframe; -}; - -#endif /* __BL_ARMATUREOBJECT_H__ */ diff --git a/source/gameengine/Converter/BL_BlenderDataConversion.cpp b/source/gameengine/Converter/BL_BlenderDataConversion.cpp deleted file mode 100644 index 39f517e03e8..00000000000 --- a/source/gameengine/Converter/BL_BlenderDataConversion.cpp +++ /dev/null @@ -1,2473 +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 ***** - * Convert blender data to ketsji - */ - -/** \file gameengine/Converter/BL_BlenderDataConversion.cpp - * \ingroup bgeconv - */ - -#ifdef _MSC_VER -# pragma warning (disable:4786) -#endif - -/* Since threaded object update we've disabled in-place - * curve evaluation (in cases when applying curve modifier - * with target curve non-evaluated yet). - * - * This requires game engine to take care of DAG and object - * evaluation (currently it's designed to export only objects - * it able to render). - * - * This workaround will make sure that curve_cache for curves - * is up-to-date. - */ - -/* TODO: Disabled for now, because of eval_ctx. */ -//#define THREADED_DAG_WORKAROUND - -#include -#include -#include - -#include "BL_BlenderDataConversion.h" - -#include "MT_Transform.h" -#include "MT_MinMax.h" - -#include "PHY_Pro.h" -#include "PHY_IPhysicsEnvironment.h" - -#include "RAS_MeshObject.h" -#include "RAS_IRasterizer.h" -#include "RAS_ILightObject.h" - -#include "KX_ConvertActuators.h" -#include "KX_ConvertControllers.h" -#include "KX_ConvertSensors.h" -#include "SCA_LogicManager.h" -#include "SCA_TimeEventManager.h" - -#include "KX_ClientObjectInfo.h" -#include "KX_Scene.h" -#include "KX_GameObject.h" -#include "KX_Light.h" -#include "KX_Camera.h" -#include "KX_EmptyObject.h" -#include "KX_FontObject.h" - -#include "RAS_TexMatrix.h" -#include "RAS_ICanvas.h" -#include "RAS_Polygon.h" -#include "RAS_TexVert.h" -#include "RAS_BucketManager.h" -#include "RAS_IPolygonMaterial.h" -#include "BL_Material.h" -#include "KX_BlenderMaterial.h" -#include "BL_Texture.h" - -#include "BKE_main.h" -#include "BKE_global.h" -#include "BKE_object.h" -#include "BL_ModifierDeformer.h" -#include "BL_ShapeDeformer.h" -#include "BL_SkinDeformer.h" -#include "BL_MeshDeformer.h" -#include "KX_SoftBodyDeformer.h" -#include "BLI_utildefines.h" -#include "BLI_listbase.h" - -#include "KX_WorldInfo.h" - -#include "KX_KetsjiEngine.h" -#include "KX_BlenderSceneConverter.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_object_types.h" -#include "DNA_material_types.h" -#include "DNA_texture_types.h" -#include "DNA_image_types.h" -#include "DNA_lamp_types.h" -#include "DNA_group_types.h" -#include "DNA_scene_types.h" -#include "DNA_camera_types.h" -#include "DNA_property_types.h" -#include "DNA_text_types.h" -#include "DNA_sensor_types.h" -#include "DNA_controller_types.h" -#include "DNA_actuator_types.h" -#include "DNA_mesh_types.h" -#include "DNA_meshdata_types.h" -#include "DNA_view3d_types.h" -#include "DNA_world_types.h" -#include "DNA_sound_types.h" -#include "DNA_key_types.h" -#include "DNA_armature_types.h" -#include "DNA_action_types.h" -#include "DNA_object_force_types.h" -#include "DNA_constraint_types.h" - -#include "MEM_guardedalloc.h" - -#include "BKE_key.h" -#include "BKE_mesh.h" - -#include "BLI_math.h" - -extern "C" { -#include "BKE_scene.h" -#include "BKE_customdata.h" -#include "BKE_cdderivedmesh.h" -#include "BKE_DerivedMesh.h" -#include "BKE_group.h" -#include "BKE_layer.h" -#include "BKE_material.h" /* give_current_material */ -#include "BKE_image.h" -#include "IMB_imbuf_types.h" -#include "BKE_displist.h" - -extern Material defmaterial; /* material.c */ -} - -/* end of blender include block */ - -#include "KX_BlenderInputDevice.h" -#include "KX_ConvertProperties.h" - -#include "SG_Node.h" -#include "SG_BBox.h" -#include "SG_Tree.h" -#include "KX_SG_NodeRelationships.h" -#include "KX_SG_BoneParentNodeRelationship.h" - -#ifdef WITH_BULLET -#include "CcdPhysicsEnvironment.h" -#include "CcdGraphicController.h" -#endif - -#include "KX_MotionState.h" - -#include "BL_ArmatureObject.h" -#include "BL_DeformableGameObject.h" - -#include "KX_NavMeshObject.h" -#include "KX_ObstacleSimulation.h" - -#include "BLI_threads.h" - - -static bool default_light_mode = 0; - -static std::map create_translate_table() -{ - std::map m; - - /* The reverse table. In order to not confuse ourselves, we */ - /* immediately convert all events that come in to KX codes. */ - m[LEFTMOUSE ] = SCA_IInputDevice::KX_LEFTMOUSE; - m[MIDDLEMOUSE ] = SCA_IInputDevice::KX_MIDDLEMOUSE; - m[RIGHTMOUSE ] = SCA_IInputDevice::KX_RIGHTMOUSE; - m[WHEELUPMOUSE ] = SCA_IInputDevice::KX_WHEELUPMOUSE; - m[WHEELDOWNMOUSE ] = SCA_IInputDevice::KX_WHEELDOWNMOUSE; - m[MOUSEX ] = SCA_IInputDevice::KX_MOUSEX; - m[MOUSEY ] = SCA_IInputDevice::KX_MOUSEY; - - // TIMERS - - m[TIMER0 ] = SCA_IInputDevice::KX_TIMER0; - m[TIMER1 ] = SCA_IInputDevice::KX_TIMER1; - m[TIMER2 ] = SCA_IInputDevice::KX_TIMER2; - - // SYSTEM - -#if 0 - /* **** XXX **** */ - m[KEYBD ] = SCA_IInputDevice::KX_KEYBD; - m[RAWKEYBD ] = SCA_IInputDevice::KX_RAWKEYBD; - m[REDRAW ] = SCA_IInputDevice::KX_REDRAW; - m[INPUTCHANGE ] = SCA_IInputDevice::KX_INPUTCHANGE; - m[QFULL ] = SCA_IInputDevice::KX_QFULL; - m[WINFREEZE ] = SCA_IInputDevice::KX_WINFREEZE; - m[WINTHAW ] = SCA_IInputDevice::KX_WINTHAW; - m[WINCLOSE ] = SCA_IInputDevice::KX_WINCLOSE; - m[WINQUIT ] = SCA_IInputDevice::KX_WINQUIT; - m[Q_FIRSTTIME ] = SCA_IInputDevice::KX_Q_FIRSTTIME; - /* **** XXX **** */ -#endif - - // standard keyboard - - m[AKEY ] = SCA_IInputDevice::KX_AKEY; - m[BKEY ] = SCA_IInputDevice::KX_BKEY; - m[CKEY ] = SCA_IInputDevice::KX_CKEY; - m[DKEY ] = SCA_IInputDevice::KX_DKEY; - m[EKEY ] = SCA_IInputDevice::KX_EKEY; - m[FKEY ] = SCA_IInputDevice::KX_FKEY; - m[GKEY ] = SCA_IInputDevice::KX_GKEY; - m[HKEY ] = SCA_IInputDevice::KX_HKEY; - m[IKEY ] = SCA_IInputDevice::KX_IKEY; - m[JKEY ] = SCA_IInputDevice::KX_JKEY; - m[KKEY ] = SCA_IInputDevice::KX_KKEY; - m[LKEY ] = SCA_IInputDevice::KX_LKEY; - m[MKEY ] = SCA_IInputDevice::KX_MKEY; - m[NKEY ] = SCA_IInputDevice::KX_NKEY; - m[OKEY ] = SCA_IInputDevice::KX_OKEY; - m[PKEY ] = SCA_IInputDevice::KX_PKEY; - m[QKEY ] = SCA_IInputDevice::KX_QKEY; - m[RKEY ] = SCA_IInputDevice::KX_RKEY; - m[SKEY ] = SCA_IInputDevice::KX_SKEY; - m[TKEY ] = SCA_IInputDevice::KX_TKEY; - m[UKEY ] = SCA_IInputDevice::KX_UKEY; - m[VKEY ] = SCA_IInputDevice::KX_VKEY; - m[WKEY ] = SCA_IInputDevice::KX_WKEY; - m[XKEY ] = SCA_IInputDevice::KX_XKEY; - m[YKEY ] = SCA_IInputDevice::KX_YKEY; - m[ZKEY ] = SCA_IInputDevice::KX_ZKEY; - - m[ZEROKEY ] = SCA_IInputDevice::KX_ZEROKEY; - m[ONEKEY ] = SCA_IInputDevice::KX_ONEKEY; - m[TWOKEY ] = SCA_IInputDevice::KX_TWOKEY; - m[THREEKEY ] = SCA_IInputDevice::KX_THREEKEY; - m[FOURKEY ] = SCA_IInputDevice::KX_FOURKEY; - m[FIVEKEY ] = SCA_IInputDevice::KX_FIVEKEY; - m[SIXKEY ] = SCA_IInputDevice::KX_SIXKEY; - m[SEVENKEY ] = SCA_IInputDevice::KX_SEVENKEY; - m[EIGHTKEY ] = SCA_IInputDevice::KX_EIGHTKEY; - m[NINEKEY ] = SCA_IInputDevice::KX_NINEKEY; - - m[CAPSLOCKKEY ] = SCA_IInputDevice::KX_CAPSLOCKKEY; - - m[LEFTCTRLKEY ] = SCA_IInputDevice::KX_LEFTCTRLKEY; - m[LEFTALTKEY ] = SCA_IInputDevice::KX_LEFTALTKEY; - m[RIGHTALTKEY ] = SCA_IInputDevice::KX_RIGHTALTKEY; - m[RIGHTCTRLKEY ] = SCA_IInputDevice::KX_RIGHTCTRLKEY; - m[RIGHTSHIFTKEY ] = SCA_IInputDevice::KX_RIGHTSHIFTKEY; - m[LEFTSHIFTKEY ] = SCA_IInputDevice::KX_LEFTSHIFTKEY; - - m[ESCKEY ] = SCA_IInputDevice::KX_ESCKEY; - m[TABKEY ] = SCA_IInputDevice::KX_TABKEY; - m[RETKEY ] = SCA_IInputDevice::KX_RETKEY; - m[SPACEKEY ] = SCA_IInputDevice::KX_SPACEKEY; - m[LINEFEEDKEY ] = SCA_IInputDevice::KX_LINEFEEDKEY; - m[BACKSPACEKEY ] = SCA_IInputDevice::KX_BACKSPACEKEY; - m[DELKEY ] = SCA_IInputDevice::KX_DELKEY; - m[SEMICOLONKEY ] = SCA_IInputDevice::KX_SEMICOLONKEY; - m[PERIODKEY ] = SCA_IInputDevice::KX_PERIODKEY; - m[COMMAKEY ] = SCA_IInputDevice::KX_COMMAKEY; - m[QUOTEKEY ] = SCA_IInputDevice::KX_QUOTEKEY; - m[ACCENTGRAVEKEY ] = SCA_IInputDevice::KX_ACCENTGRAVEKEY; - m[MINUSKEY ] = SCA_IInputDevice::KX_MINUSKEY; - m[PLUSKEY ] = SCA_IInputDevice::KX_PLUSKEY; - m[SLASHKEY ] = SCA_IInputDevice::KX_SLASHKEY; - m[BACKSLASHKEY ] = SCA_IInputDevice::KX_BACKSLASHKEY; - m[EQUALKEY ] = SCA_IInputDevice::KX_EQUALKEY; - m[LEFTBRACKETKEY ] = SCA_IInputDevice::KX_LEFTBRACKETKEY; - m[RIGHTBRACKETKEY ] = SCA_IInputDevice::KX_RIGHTBRACKETKEY; - - m[LEFTARROWKEY ] = SCA_IInputDevice::KX_LEFTARROWKEY; - m[DOWNARROWKEY ] = SCA_IInputDevice::KX_DOWNARROWKEY; - m[RIGHTARROWKEY ] = SCA_IInputDevice::KX_RIGHTARROWKEY; - m[UPARROWKEY ] = SCA_IInputDevice::KX_UPARROWKEY; - - m[PAD2 ] = SCA_IInputDevice::KX_PAD2; - m[PAD4 ] = SCA_IInputDevice::KX_PAD4; - m[PAD6 ] = SCA_IInputDevice::KX_PAD6; - m[PAD8 ] = SCA_IInputDevice::KX_PAD8; - - m[PAD1 ] = SCA_IInputDevice::KX_PAD1; - m[PAD3 ] = SCA_IInputDevice::KX_PAD3; - m[PAD5 ] = SCA_IInputDevice::KX_PAD5; - m[PAD7 ] = SCA_IInputDevice::KX_PAD7; - m[PAD9 ] = SCA_IInputDevice::KX_PAD9; - - m[PADPERIOD ] = SCA_IInputDevice::KX_PADPERIOD; - m[PADSLASHKEY ] = SCA_IInputDevice::KX_PADSLASHKEY; - m[PADASTERKEY ] = SCA_IInputDevice::KX_PADASTERKEY; - - m[PAD0 ] = SCA_IInputDevice::KX_PAD0; - m[PADMINUS ] = SCA_IInputDevice::KX_PADMINUS; - m[PADENTER ] = SCA_IInputDevice::KX_PADENTER; - m[PADPLUSKEY ] = SCA_IInputDevice::KX_PADPLUSKEY; - - - m[F1KEY ] = SCA_IInputDevice::KX_F1KEY; - m[F2KEY ] = SCA_IInputDevice::KX_F2KEY; - m[F3KEY ] = SCA_IInputDevice::KX_F3KEY; - m[F4KEY ] = SCA_IInputDevice::KX_F4KEY; - m[F5KEY ] = SCA_IInputDevice::KX_F5KEY; - m[F6KEY ] = SCA_IInputDevice::KX_F6KEY; - m[F7KEY ] = SCA_IInputDevice::KX_F7KEY; - m[F8KEY ] = SCA_IInputDevice::KX_F8KEY; - m[F9KEY ] = SCA_IInputDevice::KX_F9KEY; - m[F10KEY ] = SCA_IInputDevice::KX_F10KEY; - m[F11KEY ] = SCA_IInputDevice::KX_F11KEY; - m[F12KEY ] = SCA_IInputDevice::KX_F12KEY; - m[F13KEY ] = SCA_IInputDevice::KX_F13KEY; - m[F14KEY ] = SCA_IInputDevice::KX_F14KEY; - m[F15KEY ] = SCA_IInputDevice::KX_F15KEY; - m[F16KEY ] = SCA_IInputDevice::KX_F16KEY; - m[F17KEY ] = SCA_IInputDevice::KX_F17KEY; - m[F18KEY ] = SCA_IInputDevice::KX_F18KEY; - m[F19KEY ] = SCA_IInputDevice::KX_F19KEY; - - m[OSKEY ] = SCA_IInputDevice::KX_OSKEY; - - m[PAUSEKEY ] = SCA_IInputDevice::KX_PAUSEKEY; - m[INSERTKEY ] = SCA_IInputDevice::KX_INSERTKEY; - m[HOMEKEY ] = SCA_IInputDevice::KX_HOMEKEY; - m[PAGEUPKEY ] = SCA_IInputDevice::KX_PAGEUPKEY; - m[PAGEDOWNKEY ] = SCA_IInputDevice::KX_PAGEDOWNKEY; - m[ENDKEY ] = SCA_IInputDevice::KX_ENDKEY; - - return m; -} - -static std::map gReverseKeyTranslateTable = create_translate_table(); - -SCA_IInputDevice::KX_EnumInputs ConvertKeyCode(int key_code) -{ - return gReverseKeyTranslateTable[key_code]; -} - -static unsigned int KX_rgbaint2uint_new(unsigned int icol) -{ - union - { - unsigned int integer; - unsigned char cp[4]; - } out_color, in_color; - - in_color.integer = icol; - out_color.cp[0] = in_color.cp[3]; // red - out_color.cp[1] = in_color.cp[2]; // green - out_color.cp[2] = in_color.cp[1]; // blue - out_color.cp[3] = in_color.cp[0]; // alpha - - return out_color.integer; -} - -/* Now the real converting starts... */ -static unsigned int KX_Mcol2uint_new(MCol col) -{ - /* color has to be converted without endian sensitivity. So no shifting! */ - union - { - MCol col; - unsigned int integer; - unsigned char cp[4]; - } out_color, in_color; - - in_color.col = col; - out_color.cp[0] = in_color.cp[3]; // red - out_color.cp[1] = in_color.cp[2]; // green - out_color.cp[2] = in_color.cp[1]; // blue - out_color.cp[3] = in_color.cp[0]; // alpha - - return out_color.integer; -} - -static void SetDefaultLightMode(Scene* scene) -{ - default_light_mode = false; - Scene *sce_iter; - Base *base; - - for (SETLOOPER(scene, sce_iter, base)) - { - if (base->object->type == OB_LAMP) - { - default_light_mode = true; - return; - } - } -} - - -static bool GetMaterialUseVColor(Material *ma, const bool glslmat) -{ - if (ma) { - /* glsl uses vertex colors, otherwise use material setting - * defmaterial doesn't have VERTEXCOLP as default [#34505] */ - return (glslmat || ma == &defmaterial || (ma->mode & MA_VERTEXCOLP) != 0); - } - else { - /* no material, use vertex colors */ - return true; - } -} - -// -- -static void GetRGB( - const bool use_vcol, - MFace* mface, - MCol* mmcol, - Material *mat, - unsigned int c[4]) -{ - unsigned int color = 0xFFFFFFFFL; - if (use_vcol == true) { - if (mmcol) { - c[0] = KX_Mcol2uint_new(mmcol[0]); - c[1] = KX_Mcol2uint_new(mmcol[1]); - c[2] = KX_Mcol2uint_new(mmcol[2]); - if (mface->v4) - c[3] = KX_Mcol2uint_new(mmcol[3]); - } - else { // backup white - c[0] = KX_rgbaint2uint_new(color); - c[1] = KX_rgbaint2uint_new(color); - c[2] = KX_rgbaint2uint_new(color); - if (mface->v4) - c[3] = KX_rgbaint2uint_new( color ); - } - } - else { - /* material rgba */ - if (mat) { - union { - unsigned char cp[4]; - unsigned int integer; - } col_converter; - col_converter.cp[3] = (unsigned char) (mat->r * 255.0f); - col_converter.cp[2] = (unsigned char) (mat->g * 255.0f); - col_converter.cp[1] = (unsigned char) (mat->b * 255.0f); - col_converter.cp[0] = (unsigned char) (mat->alpha * 255.0f); - color = col_converter.integer; - } - c[0] = KX_rgbaint2uint_new(color); - c[1] = KX_rgbaint2uint_new(color); - c[2] = KX_rgbaint2uint_new(color); - if (mface->v4) { - c[3] = KX_rgbaint2uint_new(color); - } - } - -#if 0 /* white, unused */ - { - c[0] = KX_rgbaint2uint_new(color); - c[1] = KX_rgbaint2uint_new(color); - c[2] = KX_rgbaint2uint_new(color); - if (mface->v4) - c[3] = KX_rgbaint2uint_new(color); - } -#endif -} - -typedef struct MTF_localLayer { - MTFace *face; - const char *name; -} MTF_localLayer; - -static void GetUVs(BL_Material *material, MTF_localLayer *layers, MFace *mface, MTFace *tface, MT_Point2 uvs[4][MAXTEX]) -{ - int unit = 0; - if (tface) - { - - uvs[0][0].setValue(tface->uv[0]); - uvs[1][0].setValue(tface->uv[1]); - uvs[2][0].setValue(tface->uv[2]); - - if (mface->v4) - uvs[3][0].setValue(tface->uv[3]); - } - else - { - uvs[0][0] = uvs[1][0] = uvs[2][0] = uvs[3][0] = MT_Point2(0.f, 0.f); - } - - vector found_layers; - - for (int vind = 0; vindmapping[vind]; - - if (!(map.mapping & USEUV)) continue; - - if (std::find(found_layers.begin(), found_layers.end(), map.uvCoName) != found_layers.end()) - continue; - - //If no UVSet is specified, try grabbing one from the UV/Image editor - if (map.uvCoName.IsEmpty() && tface) - { - uvs[0][unit].setValue(tface->uv[0]); - uvs[1][unit].setValue(tface->uv[1]); - uvs[2][unit].setValue(tface->uv[2]); - - if (mface->v4) - uvs[3][unit].setValue(tface->uv[3]); - - ++unit; - continue; - } - - - for (int lay=0; layuv[0]); - uvs[1][unit].setValue(layer.face->uv[1]); - uvs[2][unit].setValue(layer.face->uv[2]); - - if (mface->v4) - uvs[3][unit].setValue(layer.face->uv[3]); - else - uvs[3][unit].setValue(0.0f, 0.0f); - - ++unit; - found_layers.push_back(map.uvCoName); - break; - } - } - } -} - -// ------------------------------------ -static bool ConvertMaterial( - BL_Material *material, - Material *mat, - MTFace *tface, - const char *tfaceName, - MFace *mface, - MCol *mmcol, - bool glslmat) -{ - material->Initialize(); - int texalpha = 0; - const bool validmat = (mat != NULL); - const bool validface = (tface != NULL); - const bool use_vcol = GetMaterialUseVColor(mat, glslmat); - - material->IdMode = DEFAULT_BLENDER; - material->glslmat = (validmat) ? glslmat: false; - material->materialindex = mface->mat_nr; - - // -------------------------------- - if (validmat) { - - // use lighting? - material->ras_mode |= (mat->mode & MA_SHLESS) ? 0 : USE_LIGHT; - material->ras_mode |= (mat->game.flag & GEMAT_BACKCULL) ? 0 : TWOSIDED; - - // cast shadows? - material->ras_mode |= ((mat->mode2 & MA_CASTSHADOW) && (mat->mode & MA_SHADBUF)) ? CAST_SHADOW : 0; - - // only shadows? - material->ras_mode |= (mat->mode & MA_ONLYCAST) ? ONLY_SHADOW : 0; - - MTex *mttmp = NULL; - int valid_index = 0; - - /* In Multitexture use the face texture if and only if - * it is set in the buttons - * In GLSL is not working yet :/ 3.2011 */ - - // foreach MTex - for (int i = 0; i < MAXTEX; i++) { - // use face tex - if (i == 0) { -#if 0 - Image *tmp = (Image *)(tface->tpage); -#else - /* weak but better then nothing */ - Image *tmp = mat ? mat->edit_image : NULL; -#endif - - if (tmp) { - material->img[i] = tmp; - material->texname[i] = material->img[i]->id.name; - material->flag[i] |= MIPMAP; - - material->flag[i] |= (mat->game.alpha_blend & GEMAT_ALPHA_SORT) ? USEALPHA : 0; - material->flag[i] |= (mat->game.alpha_blend & GEMAT_ALPHA) ? USEALPHA : 0; - material->flag[i] |= (mat->game.alpha_blend & GEMAT_ADD) ? CALCALPHA : 0; - - if (material->img[i]->flag & IMA_REFLECT) { - material->mapping[i].mapping |= USEREFL; - } - else { - mttmp = getMTexFromMaterial(mat, i); - if (mttmp && (mttmp->texco & TEXCO_UV)) { - /* string may be "" but thats detected as empty after */ - material->mapping[i].uvCoName = mttmp->uvname; - } - material->mapping[i].mapping |= USEUV; - } - - valid_index++; - } - else { - material->img[i] = 0; - material->texname[i] = ""; - } - continue; - } - - mttmp = getMTexFromMaterial(mat, i); - if (mttmp) { - if (mttmp->tex) { - if (mttmp->tex->type == TEX_IMAGE) { - material->mtexname[i] = mttmp->tex->id.name; - material->img[i] = mttmp->tex->ima; - if (material->img[i]) { - - material->texname[i] = material->img[i]->id.name; - material->flag[i] |= (mttmp->tex->imaflag &TEX_MIPMAP) ? MIPMAP : 0; - if (material->img[i] && (material->img[i]->flag & IMA_IGNORE_ALPHA) == 0) { - material->flag[i] |= USEALPHA; - } - if (mttmp->tex->imaflag & TEX_CALCALPHA) { - material->flag[i] |= CALCALPHA; - } - else if (mttmp->tex->flag & TEX_NEGALPHA) { - material->flag[i] |= USENEGALPHA; - } - - material->color_blend[i] = mttmp->colfac; - material->flag[i] |= (mttmp->mapto & MAP_ALPHA) ? TEXALPHA : 0; - material->flag[i] |= (mttmp->texflag & MTEX_NEGATIVE) ? TEXNEG : 0; - - if (!glslmat && (material->flag[i] & TEXALPHA)) { - texalpha = 1; - } - } - } - else if (mttmp->tex->type == TEX_ENVMAP) { - if (mttmp->tex->env->stype == ENV_LOAD) { - material->mtexname[i] = mttmp->tex->id.name; - EnvMap *env = mttmp->tex->env; - env->ima = mttmp->tex->ima; - material->cubemap[i] = env; - - if (material->cubemap[i]) { - if (!material->cubemap[i]->cube[0]) { - BL_Texture::SplitEnvMap(material->cubemap[i]); - } - - material->texname[i] = material->cubemap[i]->ima->id.name; - material->mapping[i].mapping |= USEENV; - } - } - } -#if 0 /* this flag isn't used anymore */ - material->flag[i] |= (BKE_animdata_from_id(mat->id) != NULL) ? HASIPO : 0; -#endif - /// -------------------------------- - // mapping methods - if (mat->septex & (1 << i)) { - // If this texture slot isn't in use, set it to disabled to prevent multi-uv problems - material->mapping[i].mapping = DISABLE; - } - else { - material->mapping[i].mapping |= (mttmp->texco & TEXCO_REFL) ? USEREFL : 0; - - if (mttmp->texco & TEXCO_OBJECT) { - material->mapping[i].mapping |= USEOBJ; - if (mttmp->object) { - material->mapping[i].objconame = mttmp->object->id.name; - } - } - else if (mttmp->texco & TEXCO_REFL) { - material->mapping[i].mapping |= USEREFL; - } - else if (mttmp->texco & (TEXCO_ORCO | TEXCO_GLOB)) { - material->mapping[i].mapping |= USEORCO; - } - else if (mttmp->texco & TEXCO_UV) { - /* string may be "" but thats detected as empty after */ - material->mapping[i].uvCoName = mttmp->uvname; - material->mapping[i].mapping |= USEUV; - } - else if (mttmp->texco & TEXCO_NORM) { - material->mapping[i].mapping |= USENORM; - } - else if (mttmp->texco & TEXCO_TANGENT) { - material->mapping[i].mapping |= USETANG; - } - else { - material->mapping[i].mapping |= DISABLE; - } - - material->mapping[i].scale[0] = mttmp->size[0]; - material->mapping[i].scale[1] = mttmp->size[1]; - material->mapping[i].scale[2] = mttmp->size[2]; - material->mapping[i].offsets[0] = mttmp->ofs[0]; - material->mapping[i].offsets[1] = mttmp->ofs[1]; - material->mapping[i].offsets[2] = mttmp->ofs[2]; - - material->mapping[i].projplane[0] = mttmp->projx; - material->mapping[i].projplane[1] = mttmp->projy; - material->mapping[i].projplane[2] = mttmp->projz; - } - /// -------------------------------- - - switch (mttmp->blendtype) { - case MTEX_BLEND: - material->blend_mode[i] = BLEND_MIX; - break; - case MTEX_MUL: - material->blend_mode[i] = BLEND_MUL; - break; - case MTEX_ADD: - material->blend_mode[i] = BLEND_ADD; - break; - case MTEX_SUB: - material->blend_mode[i] = BLEND_SUB; - break; - case MTEX_SCREEN: - material->blend_mode[i] = BLEND_SCR; - break; - } - valid_index++; - } - } - } - - // above one tex the switches here - // are not used - switch (valid_index) { - case 0: - material->IdMode = DEFAULT_BLENDER; - break; - case 1: - material->IdMode = ONETEX; - break; - default: - material->IdMode = GREATERTHAN2; - break; - } - material->SetUsers(mat->id.us); - - material->num_enabled = valid_index; - - material->speccolor[0] = mat->specr; - material->speccolor[1] = mat->specg; - material->speccolor[2] = mat->specb; - material->hard = (float)mat->har / 4.0f; - material->matcolor[0] = mat->r; - material->matcolor[1] = mat->g; - material->matcolor[2] = mat->b; - material->matcolor[3] = mat->alpha; - material->alpha = mat->alpha; - material->emit = mat->emit; - material->spec_f = mat->spec; - material->ref = mat->ref; - material->amb = mat->amb; - - material->ras_mode |= (mat->material_type == MA_TYPE_WIRE) ? WIRE : 0; - } - else { // No Material - int valid = 0; - - // check for tface tex to fallback on - if (validface) { -#if 0 - material->img[0] = (Image *)(tface->tpage); -#else - material->img[0] = mat ? mat->edit_image : NULL; -#endif - // ------------------------ - if (material->img[0]) { - material->texname[0] = material->img[0]->id.name; - material->mapping[0].mapping |= ((material->img[0]->flag & IMA_REFLECT) != 0) ? USEREFL : 0; - - /* see if depth of the image is 32bits */ - if (BKE_image_has_alpha(material->img[0])) { - material->flag[0] |= USEALPHA; - material->alphablend = GEMAT_ALPHA; - } - else { - material->alphablend = GEMAT_SOLID; - } - valid++; - } - } - else { - material->alphablend = GEMAT_SOLID; - } - - material->SetUsers(-1); - material->num_enabled = valid; - material->IdMode = TEXFACE; - material->speccolor[0] = 1.0f; - material->speccolor[1] = 1.0f; - material->speccolor[2] = 1.0f; - material->hard = 35.0f; - material->matcolor[0] = 0.5f; - material->matcolor[1] = 0.5f; - material->matcolor[2] = 0.5f; - material->spec_f = 0.5f; - material->ref = 0.8f; - - // No material - old default TexFace properties - material->ras_mode |= USE_LIGHT; - } - - /* No material, what to do? let's see what is in the UV and set the material accordingly - * light and visible is always on */ - if (validface) { - /* nop */ - } - else { - // nothing at all - material->alphablend = GEMAT_SOLID; - material->tile = 0; - } - - if (validmat && validface) { - material->alphablend = mat->game.alpha_blend; - } - - // with ztransp enabled, enforce alpha blending mode - if (validmat && (mat->mode & MA_TRANSP) && (mat->mode & MA_ZTRANSP) && (material->alphablend == GEMAT_SOLID)) { - material->alphablend = GEMAT_ALPHA; - } - - // always zsort alpha + add - if ((ELEM(material->alphablend, GEMAT_ALPHA, GEMAT_ALPHA_SORT, GEMAT_ADD) || texalpha) && (material->alphablend != GEMAT_CLIP)) { - material->ras_mode |= ALPHA; - material->ras_mode |= (mat && (mat->game.alpha_blend & GEMAT_ALPHA_SORT)) ? ZSORT : 0; - } - - // XXX The RGB values here were meant to be temporary storage for the conversion process, - // but fonts now make use of them too, so we leave them in for now. - unsigned int rgb[4]; - GetRGB(use_vcol, mface, mmcol, mat, rgb); - - // swap the material color, so MCol on bitmap font works - if (validmat && (use_vcol == false) && (mat->game.flag & GEMAT_TEXT)) { - material->rgb[0] = KX_rgbaint2uint_new(rgb[0]); - material->rgb[1] = KX_rgbaint2uint_new(rgb[1]); - material->rgb[2] = KX_rgbaint2uint_new(rgb[2]); - material->rgb[3] = KX_rgbaint2uint_new(rgb[3]); - } - - if (validmat) { - material->matname =(mat->id.name); - } - material->material = mat; - return true; -} - -static RAS_MaterialBucket *material_from_mesh(Material *ma, MFace *mface, MTFace *tface, MCol *mcol, MTF_localLayer *layers, int lightlayer, unsigned int *rgb, MT_Point2 uvs[4][RAS_TexVert::MAX_UNIT], const char *tfaceName, KX_Scene* scene, KX_BlenderSceneConverter *converter) -{ - RAS_IPolyMaterial* polymat = converter->FindCachedPolyMaterial(scene, ma); - BL_Material* bl_mat = converter->FindCachedBlenderMaterial(scene, ma); - KX_BlenderMaterial* kx_blmat = NULL; - - /* first is the BL_Material */ - if (!bl_mat) - { - bl_mat = new BL_Material(); - - ConvertMaterial(bl_mat, ma, tface, tfaceName, mface, mcol, - converter->GetGLSLMaterials()); - - if (ma) - converter->CacheBlenderMaterial(scene, ma, bl_mat); - } - - const bool use_vcol = GetMaterialUseVColor(ma, bl_mat->glslmat); - GetRGB(use_vcol, mface, mcol, ma, rgb); - - GetUVs(bl_mat, layers, mface, tface, uvs); - - /* then the KX_BlenderMaterial */ - if (polymat == NULL) - { - kx_blmat = new KX_BlenderMaterial(); - - kx_blmat->Initialize(scene, bl_mat, (ma?&ma->game:NULL), lightlayer); - polymat = static_cast(kx_blmat); - if (ma) - converter->CachePolyMaterial(scene, ma, polymat); - } - - // see if a bucket was reused or a new one was created - // this way only one KX_BlenderMaterial object has to exist per bucket - bool bucketCreated; - RAS_MaterialBucket* bucket = scene->FindBucket(polymat, bucketCreated); - - // this is needed to free up memory afterwards. - // the converter will also prevent duplicates from being registered, - // so just register everything. - converter->RegisterPolyMaterial(polymat); - converter->RegisterBlenderMaterial(bl_mat); - - return bucket; -} - -/* blenderobj can be NULL, make sure its checked for */ -RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, KX_Scene* scene, KX_BlenderSceneConverter *converter, bool libloading) -{ - RAS_MeshObject *meshobj; - int lightlayer = blenderobj ? blenderobj->lay:(1<<20)-1; // all layers if no object. - - // Without checking names, we get some reuse we don't want that can cause - // problems with material LoDs. - if (blenderobj && ((meshobj = converter->FindGameMesh(mesh/*, ob->lay*/)) != NULL)) { - const char *bge_name = meshobj->GetName().ReadPtr(); - const char *blender_name = ((ID *)blenderobj->data)->name + 2; - if (STREQ(bge_name, blender_name)) { - return meshobj; - } - } - - // Get DerivedMesh data - DerivedMesh *dm = CDDM_from_mesh(mesh); - DM_ensure_tessface(dm); - - MVert *mvert = dm->getVertArray(dm); - int totvert = dm->getNumVerts(dm); - - MFace *mface = dm->getTessFaceArray(dm); - MTFace *tface = static_cast(dm->getTessFaceDataArray(dm, CD_MTFACE)); - MCol *mcol = static_cast(dm->getTessFaceDataArray(dm, CD_MCOL)); - float (*tangent)[4] = NULL; - int totface = dm->getNumTessFaces(dm); - const char *tfaceName = ""; - - /* needs to be rewritten for loopdata */ - if (tface) { - if (CustomData_get_layer_index(&dm->faceData, CD_TANGENT) == -1) { - bool generate_data = false; - if (CustomData_get_layer_index(&dm->loopData, CD_TANGENT) == -1) { - DM_calc_loop_tangents(dm, true, NULL, 0); - generate_data = true; - } - DM_generate_tangent_tessface_data(dm, generate_data); - } - tangent = (float(*)[4])dm->getTessFaceDataArray(dm, CD_TANGENT); - } - - meshobj = new RAS_MeshObject(mesh); - - // Extract avaiable layers - MTF_localLayer *layers = new MTF_localLayer[MAX_MTFACE]; - for (int lay=0; layfaceData.totlayer; i++) - { - if (dm->faceData.layers[i].type == CD_MTFACE) - { - if (validLayers >= MAX_MTFACE) { - printf("%s: corrupted mesh %s - too many CD_MTFACE layers\n", __func__, mesh->id.name); - break; - } - - layers[validLayers].face = (MTFace*)(dm->faceData.layers[i].data); - layers[validLayers].name = dm->faceData.layers[i].name; - if (tface == layers[validLayers].face) - tfaceName = layers[validLayers].name; - validLayers++; - } - } - - meshobj->SetName(mesh->id.name + 2); - meshobj->m_sharedvertex_map.resize(totvert); - - Material* ma = 0; - MT_Point2 uvs[4][RAS_TexVert::MAX_UNIT]; - unsigned int rgb[4] = {0}; - - MT_Point3 pt[4]; - MT_Vector3 no[4]; - MT_Vector4 tan[4]; - - /* ugh, if there is a less annoying way to do this please use that. - * since these are converted from floats to floats, theres no real - * advantage to use MT_ types - campbell */ - for (unsigned int i = 0; i < 4; i++) { - const float zero_vec[4] = {0.0f}; - pt[i].setValue(zero_vec); - no[i].setValue(zero_vec); - tan[i].setValue(zero_vec); - } - - /* we need to manually initialize the uvs (MoTo doesn't do that) [#34550] */ - for (unsigned int i = 0; i < RAS_TexVert::MAX_UNIT; i++) { - uvs[0][i] = uvs[1][i] = uvs[2][i] = uvs[3][i] = MT_Point2(0.f, 0.f); - } - - for (int f=0;fv1].co); - pt[1].setValue(mvert[mface->v2].co); - pt[2].setValue(mvert[mface->v3].co); - if (mface->v4) pt[3].setValue(mvert[mface->v4].co); - - if (mface->flag & ME_SMOOTH) { - float n0[3], n1[3], n2[3], n3[3]; - - normal_short_to_float_v3(n0, mvert[mface->v1].no); - normal_short_to_float_v3(n1, mvert[mface->v2].no); - normal_short_to_float_v3(n2, mvert[mface->v3].no); - no[0] = n0; - no[1] = n1; - no[2] = n2; - - if (mface->v4) { - normal_short_to_float_v3(n3, mvert[mface->v4].no); - no[3] = n3; - } - } - else { - float fno[3]; - - if (mface->v4) - normal_quad_v3(fno,mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co, mvert[mface->v4].co); - else - normal_tri_v3(fno,mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co); - - no[0] = no[1] = no[2] = no[3] = MT_Vector3(fno); - } - - if (tangent) { - tan[0] = tangent[f*4 + 0]; - tan[1] = tangent[f*4 + 1]; - tan[2] = tangent[f*4 + 2]; - - if (mface->v4) - tan[3] = tangent[f*4 + 3]; - } - if (blenderobj) - ma = give_current_material(blenderobj, mface->mat_nr+1); - else - ma = mesh->mat ? mesh->mat[mface->mat_nr]:NULL; - - // Check for blender material - if (ma == NULL) { - ma= &defmaterial; - } - - { - - RAS_MaterialBucket* bucket = material_from_mesh(ma, mface, tface, mcol, layers, lightlayer, rgb, uvs, tfaceName, scene, converter); - - // set render flags - bool visible = ((ma->game.flag & GEMAT_INVISIBLE)==0); - bool twoside = ((ma->game.flag & GEMAT_BACKCULL)==0); - bool collider = ((ma->game.flag & GEMAT_NOPHYSICS)==0); - - /* mark face as flat, so vertices are split */ - bool flat = (mface->flag & ME_SMOOTH) == 0; - - int nverts = (mface->v4)? 4: 3; - - RAS_Polygon *poly = meshobj->AddPolygon(bucket, nverts); - - poly->SetVisible(visible); - poly->SetCollider(collider); - poly->SetTwoside(twoside); - //poly->SetEdgeCode(mface->edcode); - - meshobj->AddVertex(poly,0,pt[0],uvs[0],tan[0],rgb[0],no[0],flat,mface->v1); - meshobj->AddVertex(poly,1,pt[1],uvs[1],tan[1],rgb[1],no[1],flat,mface->v2); - meshobj->AddVertex(poly,2,pt[2],uvs[2],tan[2],rgb[2],no[2],flat,mface->v3); - - if (nverts==4) - meshobj->AddVertex(poly,3,pt[3],uvs[3],tan[3],rgb[3],no[3],flat,mface->v4); - } - - if (tface) - tface++; - if (mcol) - mcol+=4; - - for (int lay=0; laym_sharedvertex_map for reinstance phys mesh. - // 2.49a and before it did: meshobj->m_sharedvertex_map.clear(); - // but this didnt save much ram. - Campbell - meshobj->EndConversion(); - - // pre calculate texture generation - // However, we want to delay this if we're libloading so we can make sure we have the right scene. - if (!libloading) { - for (list::iterator mit = meshobj->GetFirstMaterial(); - mit != meshobj->GetLastMaterial(); ++ mit) { - mit->m_bucket->GetPolyMaterial()->OnConstruction(); - } - } - - if (layers) - delete []layers; - - dm->release(dm); - - converter->RegisterGameMesh(meshobj, mesh); - return meshobj; -} - - - -static PHY_MaterialProps *CreateMaterialFromBlenderObject(struct Object* blenderobject) -{ - PHY_MaterialProps *materialProps = new PHY_MaterialProps; - - MT_assert(materialProps && "Create physics material properties failed"); - - Material* blendermat = give_current_material(blenderobject, 1); - - if (blendermat) - { - MT_assert(0.0f <= blendermat->reflect && blendermat->reflect <= 1.0f); - - materialProps->m_restitution = blendermat->reflect; - materialProps->m_friction = blendermat->friction; - materialProps->m_fh_spring = blendermat->fh; - materialProps->m_fh_damping = blendermat->xyfrict; - materialProps->m_fh_distance = blendermat->fhdist; - materialProps->m_fh_normal = (blendermat->dynamode & MA_FH_NOR) != 0; - } - else { - //give some defaults - materialProps->m_restitution = 0.f; - materialProps->m_friction = 0.5; - materialProps->m_fh_spring = 0.f; - materialProps->m_fh_damping = 0.f; - materialProps->m_fh_distance = 0.f; - materialProps->m_fh_normal = false; - - } - - return materialProps; -} - -static PHY_ShapeProps *CreateShapePropsFromBlenderObject(struct Object* blenderobject) -{ - PHY_ShapeProps *shapeProps = new PHY_ShapeProps; - - MT_assert(shapeProps); - - shapeProps->m_mass = blenderobject->mass; - -// This needs to be fixed in blender. For now, we use: - -// in Blender, inertia stands for the size value which is equivalent to -// the sphere radius - shapeProps->m_inertia = blenderobject->formfactor; - - MT_assert(0.0f <= blenderobject->damping && blenderobject->damping <= 1.0f); - MT_assert(0.0f <= blenderobject->rdamping && blenderobject->rdamping <= 1.0f); - - shapeProps->m_lin_drag = 1.0f - blenderobject->damping; - shapeProps->m_ang_drag = 1.0f - blenderobject->rdamping; - - shapeProps->m_friction_scaling[0] = blenderobject->anisotropicFriction[0]; - shapeProps->m_friction_scaling[1] = blenderobject->anisotropicFriction[1]; - shapeProps->m_friction_scaling[2] = blenderobject->anisotropicFriction[2]; - shapeProps->m_do_anisotropic = ((blenderobject->gameflag & OB_ANISOTROPIC_FRICTION) != 0); - - shapeProps->m_do_fh = (blenderobject->gameflag & OB_DO_FH) != 0; - shapeProps->m_do_rot_fh = (blenderobject->gameflag & OB_ROT_FH) != 0; - -// velocity clamping XXX - shapeProps->m_clamp_vel_min = blenderobject->min_vel; - shapeProps->m_clamp_vel_max = blenderobject->max_vel; - shapeProps->m_clamp_angvel_min = blenderobject->min_angvel; - shapeProps->m_clamp_angvel_max = blenderobject->max_angvel; - -// Character physics properties - shapeProps->m_step_height = blenderobject->step_height; - shapeProps->m_jump_speed = blenderobject->jump_speed; - shapeProps->m_fall_speed = blenderobject->fall_speed; - shapeProps->m_max_jumps = blenderobject->max_jumps; - - return shapeProps; -} - - - - - -////////////////////////////////////////////////////////// - - - -static float my_boundbox_mesh(Mesh *me, float *loc, float *size) -{ - MVert *mvert; - BoundBox *bb; - float min[3], max[3]; - float mloc[3], msize[3]; - float radius_sq=0.0f, vert_radius_sq, *co; - int a; - - if (me->bb==0) { - me->bb = BKE_boundbox_alloc_unit(); - } - bb= me->bb; - - INIT_MINMAX(min, max); - - if (!loc) loc= mloc; - if (!size) size= msize; - - mvert= me->mvert; - for (a = 0; atotvert; a++, mvert++) { - co = mvert->co; - - /* bounds */ - minmax_v3v3_v3(min, max, co); - - /* radius */ - - vert_radius_sq = len_squared_v3(co); - if (vert_radius_sq > radius_sq) - radius_sq = vert_radius_sq; - } - - if (me->totvert) { - loc[0] = (min[0] + max[0]) / 2.0f; - loc[1] = (min[1] + max[1]) / 2.0f; - loc[2] = (min[2] + max[2]) / 2.0f; - - size[0] = (max[0] - min[0]) / 2.0f; - size[1] = (max[1] - min[1]) / 2.0f; - size[2] = (max[2] - min[2]) / 2.0f; - } - else { - loc[0] = loc[1] = loc[2] = 0.0f; - size[0] = size[1] = size[2] = 0.0f; - } - - bb->vec[0][0] = bb->vec[1][0] = bb->vec[2][0] = bb->vec[3][0] = loc[0]-size[0]; - bb->vec[4][0] = bb->vec[5][0] = bb->vec[6][0] = bb->vec[7][0] = loc[0]+size[0]; - - bb->vec[0][1] = bb->vec[1][1] = bb->vec[4][1] = bb->vec[5][1] = loc[1]-size[1]; - bb->vec[2][1] = bb->vec[3][1] = bb->vec[6][1] = bb->vec[7][1] = loc[1]+size[1]; - - bb->vec[0][2] = bb->vec[3][2] = bb->vec[4][2] = bb->vec[7][2] = loc[2]-size[2]; - bb->vec[1][2] = bb->vec[2][2] = bb->vec[5][2] = bb->vec[6][2] = loc[2]+size[2]; - - return sqrtf_signed(radius_sq); -} - -////////////////////////////////////////////////////// - - -static void BL_CreateGraphicObjectNew(KX_GameObject* gameobj, - const MT_Point3& localAabbMin, - const MT_Point3& localAabbMax, - KX_Scene* kxscene, - bool isActive, - e_PhysicsEngine physics_engine) -{ - if (gameobj->GetMeshCount() > 0) - { - switch (physics_engine) - { -#ifdef WITH_BULLET - case UseBullet: - { - CcdPhysicsEnvironment* env = (CcdPhysicsEnvironment*)kxscene->GetPhysicsEnvironment(); - assert(env); - PHY_IMotionState* motionstate = new KX_MotionState(gameobj->GetSGNode()); - CcdGraphicController* ctrl = new CcdGraphicController(env, motionstate); - gameobj->SetGraphicController(ctrl); - ctrl->SetNewClientInfo(gameobj->getClientInfo()); - ctrl->SetLocalAabb(localAabbMin, localAabbMax); - if (isActive) { - // add first, this will create the proxy handle, only if the object is visible - if (gameobj->GetVisible()) - env->AddCcdGraphicController(ctrl); - // update the mesh if there is a deformer, this will also update the bounding box for modifiers - RAS_Deformer* deformer = gameobj->GetDeformer(); - if (deformer) - deformer->UpdateBuckets(); - } - } - break; -#endif - default: - break; - } - } -} - -static void BL_CreatePhysicsObjectNew(KX_GameObject* gameobj, - struct Object* blenderobject, - RAS_MeshObject* meshobj, - KX_Scene* kxscene, - int activeLayerBitInfo, - KX_BlenderSceneConverter *converter, - bool processCompoundChildren - ) - -{ - //SYS_SystemHandle syshandle = SYS_GetSystem(); /*unused*/ - //int userigidbody = SYS_GetCommandLineInt(syshandle,"norigidbody",0); - //bool bRigidBody = (userigidbody == 0); - - // object has physics representation? - if (!(blenderobject->gameflag & OB_COLLISION)) { - // Respond to all collisions so that Near sensors work on No Collision - // objects. - gameobj->SetUserCollisionGroup(0xffff); - gameobj->SetUserCollisionMask(0xffff); - return; - } - - gameobj->SetUserCollisionGroup(blenderobject->col_group); - gameobj->SetUserCollisionMask(blenderobject->col_mask); - - // get Root Parent of blenderobject - struct Object* parent= blenderobject->parent; - while (parent && parent->parent) { - parent= parent->parent; - } - - bool isCompoundChild = false; - bool hasCompoundChildren = !parent && (blenderobject->gameflag & OB_CHILD) && !(blenderobject->gameflag & OB_SOFT_BODY); - - /* When the parent is not OB_DYNAMIC and has no OB_COLLISION then it gets no bullet controller - * and cant be apart of the parents compound shape, same goes for OB_SOFT_BODY */ - if (parent && (parent->gameflag & (OB_DYNAMIC | OB_COLLISION))) { - if ((parent->gameflag & OB_CHILD)!=0 && (blenderobject->gameflag & OB_CHILD) && !(parent->gameflag & OB_SOFT_BODY)) { - isCompoundChild = true; - } - } - if (processCompoundChildren != isCompoundChild) - return; - - - PHY_ShapeProps* shapeprops = - CreateShapePropsFromBlenderObject(blenderobject); - - - PHY_MaterialProps* smmaterial = - CreateMaterialFromBlenderObject(blenderobject); - - DerivedMesh* dm = NULL; - if (gameobj->GetDeformer()) - dm = gameobj->GetDeformer()->GetPhysicsMesh(); - - class PHY_IMotionState* motionstate = new KX_MotionState(gameobj->GetSGNode()); - - kxscene->GetPhysicsEnvironment()->ConvertObject(gameobj, meshobj, dm, kxscene, shapeprops, smmaterial, motionstate, activeLayerBitInfo, isCompoundChild, hasCompoundChildren); - - bool isActor = (blenderobject->gameflag & OB_ACTOR)!=0; - bool isSensor = (blenderobject->gameflag & OB_SENSOR) != 0; - gameobj->getClientInfo()->m_type = - (isSensor) ? ((isActor) ? KX_ClientObjectInfo::OBACTORSENSOR : KX_ClientObjectInfo::OBSENSOR) : - (isActor) ? KX_ClientObjectInfo::ACTOR : KX_ClientObjectInfo::STATIC; - - // should we record animation for this object? - if ((blenderobject->gameflag & OB_RECORD_ANIMATION) != 0) - gameobj->SetRecordAnimation(true); - - delete shapeprops; - delete smmaterial; - if (dm) { - dm->needsFree = 1; - dm->release(dm); - } -} - - - - - -static KX_LightObject *gamelight_from_blamp(Object *ob, Lamp *la, unsigned int layerflag, KX_Scene *kxscene, RAS_IRasterizer *rasterizer, KX_BlenderSceneConverter *converter) -{ - RAS_ILightObject *lightobj = rasterizer->CreateLight(); - KX_LightObject *gamelight; - - lightobj->m_att1 = la->att1; - lightobj->m_att2 = (la->mode & LA_QUAD) ? la->att2 : 0.0f; - lightobj->m_coeff_const = la->coeff_const; - lightobj->m_coeff_lin = la->coeff_lin; - lightobj->m_coeff_quad = la->coeff_quad; - lightobj->m_color[0] = la->r; - lightobj->m_color[1] = la->g; - lightobj->m_color[2] = la->b; - lightobj->m_distance = la->dist; - lightobj->m_energy = la->energy; - lightobj->m_shadowclipstart = la->clipsta; - lightobj->m_shadowclipend = la->clipend; - lightobj->m_shadowbias = la->bias; - lightobj->m_shadowbleedbias = la->bleedbias; - lightobj->m_shadowmaptype = la->shadowmap_type; - lightobj->m_shadowfrustumsize = la->shadow_frustum_size; - lightobj->m_shadowcolor[0] = la->shdwr; - lightobj->m_shadowcolor[1] = la->shdwg; - lightobj->m_shadowcolor[2] = la->shdwb; - lightobj->m_layer = layerflag; - lightobj->m_spotblend = la->spotblend; - lightobj->m_spotsize = la->spotsize; - - lightobj->m_nodiffuse = (la->mode & LA_NO_DIFF) != 0; - lightobj->m_nospecular = (la->mode & LA_NO_SPEC) != 0; - - bool glslmat = converter->GetGLSLMaterials(); - - // in GLSL NEGATIVE LAMP is handled inside the lamp update function - if (glslmat==0) { - if (la->mode & LA_NEG) - { - lightobj->m_color[0] = -lightobj->m_color[0]; - lightobj->m_color[1] = -lightobj->m_color[1]; - lightobj->m_color[2] = -lightobj->m_color[2]; - } - } - - if (la->type==LA_SUN) { - lightobj->m_type = RAS_ILightObject::LIGHT_SUN; - } else if (la->type==LA_SPOT) { - lightobj->m_type = RAS_ILightObject::LIGHT_SPOT; - } else { - lightobj->m_type = RAS_ILightObject::LIGHT_NORMAL; - } - - gamelight = new KX_LightObject(kxscene, KX_Scene::m_callbacks, rasterizer, - lightobj, glslmat); - - return gamelight; -} - -static KX_Camera *gamecamera_from_bcamera(Object *ob, KX_Scene *kxscene, KX_BlenderSceneConverter *converter) -{ - Camera* ca = static_cast(ob->data); - RAS_CameraData camdata(ca->lens, ca->ortho_scale, ca->sensor_x, ca->sensor_y, ca->sensor_fit, ca->shiftx, ca->shifty, ca->clipsta, ca->clipend, ca->type == CAM_PERSP, ca->YF_dofdist); - KX_Camera *gamecamera; - - gamecamera= new KX_Camera(kxscene, KX_Scene::m_callbacks, camdata); - gamecamera->SetName(ca->id.name + 2); - - return gamecamera; -} - -static KX_GameObject *gameobject_from_blenderobject( - Object *ob, - KX_Scene *kxscene, - RAS_IRasterizer *rendertools, - KX_BlenderSceneConverter *converter, - bool libloading) -{ - KX_GameObject *gameobj = NULL; - Scene *blenderscene = kxscene->GetBlenderScene(); - - switch (ob->type) { - case OB_LAMP: - { - KX_LightObject* gamelight = gamelight_from_blamp(ob, static_cast(ob->data), ob->lay, kxscene, rendertools, converter); - gameobj = gamelight; - - if (blenderscene->lay & ob->lay) - { - gamelight->AddRef(); - kxscene->GetLightList()->Add(gamelight); - } - - break; - } - - case OB_CAMERA: - { - KX_Camera* gamecamera = gamecamera_from_bcamera(ob, kxscene, converter); - gameobj = gamecamera; - - //don't add a reference: the camera list in kxscene->m_cameras is not released at the end - //gamecamera->AddRef(); - kxscene->AddCamera(gamecamera); - - break; - } - - case OB_MESH: - { - Mesh* mesh = static_cast(ob->data); - float center[3], extents[3]; - float radius = my_boundbox_mesh((Mesh*) ob->data, center, extents); - RAS_MeshObject* meshobj = BL_ConvertMesh(mesh,ob,kxscene,converter, libloading); - - // needed for python scripting - kxscene->GetLogicManager()->RegisterMeshName(meshobj->GetName(),meshobj); - - if (ob->gameflag & OB_NAVMESH) - { - gameobj = new KX_NavMeshObject(kxscene,KX_Scene::m_callbacks); - gameobj->AddMesh(meshobj); - break; - } - - gameobj = new BL_DeformableGameObject(ob,kxscene,KX_Scene::m_callbacks); - - // set transformation - gameobj->AddMesh(meshobj); - - // gather levels of detail - if (BLI_listbase_count_at_most(&ob->lodlevels, 2) > 1) { - LodLevel *lod = ((LodLevel*)ob->lodlevels.first)->next; - Mesh* lodmesh = mesh; - Object* lodmatob = ob; - gameobj->AddLodMesh(meshobj); - for (; lod; lod = lod->next) { - if (!lod->source || lod->source->type != OB_MESH) continue; - if (lod->flags & OB_LOD_USE_MESH) { - lodmesh = static_cast(lod->source->data); - } - if (lod->flags & OB_LOD_USE_MAT) { - lodmatob = lod->source; - } - gameobj->AddLodMesh(BL_ConvertMesh(lodmesh, lodmatob, kxscene, converter, libloading)); - } - if (blenderscene->gm.lodflag & SCE_LOD_USE_HYST) { - kxscene->SetLodHysteresis(true); - kxscene->SetLodHysteresisValue(blenderscene->gm.scehysteresis); - } - } - - // for all objects: check whether they want to - // respond to updates - bool ignoreActivityCulling = - ((ob->gameflag2 & OB_NEVER_DO_ACTIVITY_CULLING)!=0); - gameobj->SetIgnoreActivityCulling(ignoreActivityCulling); - gameobj->SetOccluder((ob->gameflag & OB_OCCLUDER) != 0, false); - - // we only want obcolor used if there is a material in the mesh - // that requires it - Material *mat= NULL; - bool bUseObjectColor=false; - - for (int i=0;itotcol;i++) { - mat=mesh->mat[i]; - if (!mat) break; - if ((mat->shade_flag & MA_OBCOLOR)) { - bUseObjectColor = true; - break; - } - } - if (bUseObjectColor) - gameobj->SetObjectColor(ob->col); - - // two options exists for deform: shape keys and armature - // only support relative shape key - bool bHasShapeKey = mesh->key != NULL && mesh->key->type==KEY_RELATIVE; - bool bHasDvert = mesh->dvert != NULL && ob->defbase.first; - bool bHasArmature = (BL_ModifierDeformer::HasArmatureDeformer(ob) && ob->parent && ob->parent->type == OB_ARMATURE && bHasDvert); - bool bHasModifier = BL_ModifierDeformer::HasCompatibleDeformer(ob); -#ifdef WITH_BULLET - bool bHasSoftBody = (!ob->parent && (ob->gameflag & OB_SOFT_BODY)); -#endif - if (bHasModifier) { - BL_ModifierDeformer *dcont = new BL_ModifierDeformer((BL_DeformableGameObject *)gameobj, - kxscene->GetBlenderScene(), ob, meshobj); - ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont); - } else if (bHasShapeKey) { - // not that we can have shape keys without dvert! - BL_ShapeDeformer *dcont = new BL_ShapeDeformer((BL_DeformableGameObject*)gameobj, - ob, meshobj); - ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont); - } else if (bHasArmature) { - BL_SkinDeformer *dcont = new BL_SkinDeformer((BL_DeformableGameObject*)gameobj, - ob, meshobj); - ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont); - } else if (bHasDvert) { - // this case correspond to a mesh that can potentially deform but not with the - // object to which it is attached for the moment. A skin mesh was created in - // BL_ConvertMesh() so must create a deformer too! - BL_MeshDeformer *dcont = new BL_MeshDeformer((BL_DeformableGameObject*)gameobj, - ob, meshobj); - ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont); -#ifdef WITH_BULLET - } else if (bHasSoftBody) { - KX_SoftBodyDeformer *dcont = new KX_SoftBodyDeformer(meshobj, (BL_DeformableGameObject*)gameobj); - ((BL_DeformableGameObject*)gameobj)->SetDeformer(dcont); -#endif - } - - MT_Point3 min = MT_Point3(center) - MT_Vector3(extents); - MT_Point3 max = MT_Point3(center) + MT_Vector3(extents); - SG_BBox bbox = SG_BBox(min, max); - gameobj->GetSGNode()->SetBBox(bbox); - gameobj->GetSGNode()->SetRadius(radius); - - break; - } - - case OB_ARMATURE: - { - bArmature *arm = (bArmature*)ob->data; - gameobj = new BL_ArmatureObject( - kxscene, - KX_Scene::m_callbacks, - ob, - kxscene->GetBlenderScene(), // handle - arm->gevertdeformer - ); - /* Get the current pose from the armature object and apply it as the rest pose */ - break; - } - - case OB_EMPTY: - { - gameobj = new KX_EmptyObject(kxscene,KX_Scene::m_callbacks); - // set transformation - break; - } - - case OB_FONT: - { - bool do_color_management = BKE_scene_check_color_management_enabled(blenderscene); - /* font objects have no bounding box */ - gameobj = new KX_FontObject(kxscene,KX_Scene::m_callbacks, rendertools, ob, do_color_management); - - /* add to the list only the visible fonts */ - if ((ob->lay & kxscene->GetBlenderScene()->lay) != 0) - kxscene->AddFont(static_cast(gameobj)); - break; - } - -#ifdef THREADED_DAG_WORKAROUND - case OB_CURVE: - { - if (ob->curve_cache == NULL) { - BKE_displist_make_curveTypes(blenderscene, ob, false); - } - } -#endif - - } - if (gameobj) - { - gameobj->SetLayer(ob->lay); - gameobj->SetBlenderObject(ob); - /* set the visibility state based on the objects render option in the outliner */ - if (ob->restrictflag & OB_RESTRICT_RENDER) gameobj->SetVisible(0, 0); - } - return gameobj; -} - -struct parentChildLink { - struct Object* m_blenderchild; - SG_Node* m_gamechildnode; -}; - -#if 0 -static bPoseChannel *get_active_posechannel2(Object *ob) -{ - bArmature *arm= (bArmature*)ob->data; - bPoseChannel *pchan; - - /* find active */ - for (pchan= (bPoseChannel *)ob->pose->chanbase.first; pchan; pchan= pchan->next) { - if (pchan->bone && (pchan->bone == arm->act_bone) && (pchan->bone->layer & arm->layer)) - return pchan; - } - - return NULL; -} -#endif - -static ListBase *get_active_constraints2(Object *ob) -{ - if (!ob) - return NULL; - - // XXX - shouldnt we care about the pose data and not the mode??? -#if 0 - if (ob->mode & OB_MODE_POSE) { - bPoseChannel *pchan; - - pchan = get_active_posechannel2(ob); - if (pchan) - return &pchan->constraints; - } - else -#endif - { - return &ob->constraints; - } - - return NULL; -} - -static void UNUSED_FUNCTION(print_active_constraints2)(Object *ob) //not used, use to debug -{ - bConstraint* curcon; - ListBase* conlist = get_active_constraints2(ob); - - if (conlist) { - for (curcon = (bConstraint *)conlist->first; curcon; curcon = (bConstraint *)curcon->next) { - printf("%i\n",curcon->type); - } - } -} - -// Copy base layer to object layer like in BKE_scene_set_background -static void blenderSceneSetBackground(Scene *blenderscene) -{ - Scene *it; - Base *base; - - for (SETLOOPER(blenderscene, it, base)) { - base->object->lay = base->lay; - BKE_scene_object_base_flag_sync_from_base(base); - } -} - -static KX_GameObject* getGameOb(STR_String busc,CListValue* sumolist) -{ - - for (int j=0;jGetCount();j++) - { - KX_GameObject* gameobje = (KX_GameObject*) sumolist->GetValue(j); - if (gameobje->GetName()==busc) - return gameobje; - } - - return 0; - -} - -static bool bl_isConstraintInList(KX_GameObject *gameobj, set convertedlist) -{ - set::iterator gobit; - for (gobit = convertedlist.begin(); gobit != convertedlist.end(); gobit++) { - if ((*gobit)->GetName() == gameobj->GetName()) - return true; - } - return false; -} - -/* helper for BL_ConvertBlenderObjects, avoids code duplication - * note: all var names match args are passed from the caller */ -static void bl_ConvertBlenderObject_Single( - KX_BlenderSceneConverter *converter, - Object *blenderobject, - vector &vec_parent_child, - CListValue* logicbrick_conversionlist, - CListValue* objectlist, CListValue* inactivelist, CListValue* sumolist, - KX_Scene* kxscene, KX_GameObject* gameobj, - SCA_LogicManager* logicmgr, SCA_TimeEventManager* timemgr, - bool isInActiveLayer - ) -{ - MT_Point3 pos( - blenderobject->loc[0]+blenderobject->dloc[0], - blenderobject->loc[1]+blenderobject->dloc[1], - blenderobject->loc[2]+blenderobject->dloc[2] - ); - - MT_Matrix3x3 rotation; - float rotmat[3][3]; - BKE_object_rot_to_mat3(blenderobject, rotmat, false); - rotation.setValue3x3((float*)rotmat); - - MT_Vector3 scale(blenderobject->size); - - gameobj->NodeSetLocalPosition(pos); - gameobj->NodeSetLocalOrientation(rotation); - gameobj->NodeSetLocalScale(scale); - gameobj->NodeUpdateGS(0); - - sumolist->Add(gameobj->AddRef()); - - BL_ConvertProperties(blenderobject,gameobj,timemgr,kxscene,isInActiveLayer); - - gameobj->SetName(blenderobject->id.name + 2); - - // update children/parent hierarchy - if (blenderobject->parent != 0) - { - // blender has an additional 'parentinverse' offset in each object - SG_Callbacks callback(NULL,NULL,NULL,KX_Scene::KX_ScenegraphUpdateFunc,KX_Scene::KX_ScenegraphRescheduleFunc); - SG_Node* parentinversenode = new SG_Node(NULL,kxscene,callback); - - // define a normal parent relationship for this node. - KX_NormalParentRelation * parent_relation = KX_NormalParentRelation::New(); - parentinversenode->SetParentRelation(parent_relation); - - parentChildLink pclink; - pclink.m_blenderchild = blenderobject; - pclink.m_gamechildnode = parentinversenode; - vec_parent_child.push_back(pclink); - - float* fl = (float*) blenderobject->parentinv; - MT_Transform parinvtrans(fl); - parentinversenode->SetLocalPosition(parinvtrans.getOrigin()); - // problem here: the parent inverse transform combines scaling and rotation - // in the basis but the scenegraph needs separate rotation and scaling. - // This is not important for OpenGL (it uses 4x4 matrix) but it is important - // for the physic engine that needs a separate scaling - //parentinversenode->SetLocalOrientation(parinvtrans.getBasis()); - - // Extract the rotation and the scaling from the basis - MT_Matrix3x3 ori(parinvtrans.getBasis()); - MT_Vector3 x(ori.getColumn(0)); - MT_Vector3 y(ori.getColumn(1)); - MT_Vector3 z(ori.getColumn(2)); - MT_Vector3 parscale(x.length(), y.length(), z.length()); - if (!MT_fuzzyZero(parscale[0])) - x /= parscale[0]; - if (!MT_fuzzyZero(parscale[1])) - y /= parscale[1]; - if (!MT_fuzzyZero(parscale[2])) - z /= parscale[2]; - ori.setColumn(0, x); - ori.setColumn(1, y); - ori.setColumn(2, z); - parentinversenode->SetLocalOrientation(ori); - parentinversenode->SetLocalScale(parscale); - - parentinversenode->AddChild(gameobj->GetSGNode()); - } - - // needed for python scripting - logicmgr->RegisterGameObjectName(gameobj->GetName(),gameobj); - - // needed for group duplication - logicmgr->RegisterGameObj(blenderobject, gameobj); - for (int i = 0; i < gameobj->GetMeshCount(); i++) - logicmgr->RegisterGameMeshName(gameobj->GetMesh(i)->GetName(), blenderobject); - - converter->RegisterGameObject(gameobj, blenderobject); - // this was put in rapidly, needs to be looked at more closely - // only draw/use objects in active 'blender' layers - - logicbrick_conversionlist->Add(gameobj->AddRef()); - - if (isInActiveLayer) - { - objectlist->Add(gameobj->AddRef()); - //tf.Add(gameobj->GetSGNode()); - - gameobj->NodeUpdateGS(0); - gameobj->AddMeshUser(); - } - else - { - //we must store this object otherwise it will be deleted - //at the end of this function if it is not a root object - inactivelist->Add(gameobj->AddRef()); - } -} - - -// convert blender objects into ketsji gameobjects -void BL_ConvertBlenderObjects(struct Main* maggie, - KX_Scene* kxscene, - KX_KetsjiEngine* ketsjiEngine, - e_PhysicsEngine physics_engine, - RAS_IRasterizer* rendertools, - RAS_ICanvas* canvas, - KX_BlenderSceneConverter* converter, - bool alwaysUseExpandFraming, - bool libloading - ) -{ - -#define BL_CONVERTBLENDEROBJECT_SINGLE \ - bl_ConvertBlenderObject_Single(converter, \ - blenderobject, \ - vec_parent_child, \ - logicbrick_conversionlist, \ - objectlist, inactivelist, sumolist, \ - kxscene, gameobj, \ - logicmgr, timemgr, \ - isInActiveLayer \ - ) - - - - Scene *blenderscene = kxscene->GetBlenderScene(); - // for SETLOOPER - Scene *sce_iter; - Base *base; - - // Get the frame settings of the canvas. - // Get the aspect ratio of the canvas as designed by the user. - - RAS_FrameSettings::RAS_FrameType frame_type; - int aspect_width; - int aspect_height; - set grouplist; // list of groups to be converted - set allblobj; // all objects converted - set groupobj; // objects from groups (never in active layer) - - // This is bad, but we use this to make sure the first time this is called - // is not in a separate thread. - BL_Texture::GetMaxUnits(); - - /* We have to ensure that group definitions are only converted once - * push all converted group members to this set. - * This will happen when a group instance is made from a linked group instance - * and both are on the active layer. */ - set convertedlist; - - if (alwaysUseExpandFraming) { - frame_type = RAS_FrameSettings::e_frame_extend; - aspect_width = canvas->GetWidth(); - aspect_height = canvas->GetHeight(); - } else { - if (blenderscene->gm.framing.type == SCE_GAMEFRAMING_BARS) { - frame_type = RAS_FrameSettings::e_frame_bars; - } else if (blenderscene->gm.framing.type == SCE_GAMEFRAMING_EXTEND) { - frame_type = RAS_FrameSettings::e_frame_extend; - } else { - frame_type = RAS_FrameSettings::e_frame_scale; - } - - aspect_width = (int)(blenderscene->r.xsch * blenderscene->r.xasp); - aspect_height = (int)(blenderscene->r.ysch * blenderscene->r.yasp); - } - - RAS_FrameSettings frame_settings( - frame_type, - blenderscene->gm.framing.col[0], - blenderscene->gm.framing.col[1], - blenderscene->gm.framing.col[2], - aspect_width, - aspect_height - ); - kxscene->SetFramingType(frame_settings); - - kxscene->SetGravity(MT_Vector3(0,0, -blenderscene->gm.gravity)); - - /* set activity culling parameters */ - kxscene->SetActivityCulling( (blenderscene->gm.mode & WO_ACTIVITY_CULLING) != 0); - kxscene->SetActivityCullingRadius(blenderscene->gm.activityBoxRadius); - kxscene->SetDbvtCulling((blenderscene->gm.mode & WO_DBVT_CULLING) != 0); - - // no occlusion culling by default - kxscene->SetDbvtOcclusionRes(0); - - int activeLayerBitInfo = blenderscene->lay; - - // list of all object converted, active and inactive - CListValue* sumolist = new CListValue(); - - vector vec_parent_child; - - CListValue* objectlist = kxscene->GetObjectList(); - CListValue* inactivelist = kxscene->GetInactiveList(); - CListValue* parentlist = kxscene->GetRootParentList(); - - SCA_LogicManager* logicmgr = kxscene->GetLogicManager(); - SCA_TimeEventManager* timemgr = kxscene->GetTimeEventManager(); - - CListValue* logicbrick_conversionlist = new CListValue(); - - //SG_TreeFactory tf; - - // Convert actions to actionmap - bAction *curAct; - for (curAct = (bAction*)maggie->action.first; curAct; curAct=(bAction*)curAct->id.next) - { - logicmgr->RegisterActionName(curAct->id.name + 2, curAct); - } - - SetDefaultLightMode(blenderscene); - - blenderSceneSetBackground(blenderscene); - - // Let's support scene set. - // Beware of name conflict in linked data, it will not crash but will create confusion - // in Python scripting and in certain actuators (replace mesh). Linked scene *should* have - // no conflicting name for Object, Object data and Action. - for (SETLOOPER(blenderscene, sce_iter, base)) - { - Object* blenderobject = base->object; - allblobj.insert(blenderobject); - - KX_GameObject* gameobj = gameobject_from_blenderobject( - base->object, - kxscene, - rendertools, - converter, - libloading); - - bool isInActiveLayer = (blenderobject->lay & activeLayerBitInfo) !=0; - if (gameobj) - { - /* macro calls object conversion funcs */ - BL_CONVERTBLENDEROBJECT_SINGLE; - - if (gameobj->IsDupliGroup()) { - grouplist.insert(blenderobject->dup_group); - } - - /* Note about memory leak issues: - * When a CValue derived class is created, m_refcount is initialized to 1 - * so the class must be released after being used to make sure that it won't - * hang in memory. If the object needs to be stored for a long time, - * use AddRef() so that this Release() does not free the object. - * Make sure that for any AddRef() there is a Release()!!!! - * Do the same for any object derived from CValue, CExpression and NG_NetworkMessage - */ - gameobj->Release(); - } - } - - if (!grouplist.empty()) - { - // now convert the group referenced by dupli group object - // keep track of all groups already converted - set allgrouplist = grouplist; - set tempglist; - // recurse - while (!grouplist.empty()) - { - set::iterator git; - tempglist.clear(); - tempglist.swap(grouplist); - for (git=tempglist.begin(); git!=tempglist.end(); git++) - { - Group* group = *git; - FOREACH_GROUP_OBJECT_BEGIN(group, blenderobject) - { - if (converter->FindGameObject(blenderobject) == NULL) - { - allblobj.insert(blenderobject); - groupobj.insert(blenderobject); - KX_GameObject* gameobj = gameobject_from_blenderobject( - blenderobject, - kxscene, - rendertools, - converter, - libloading); - - bool isInActiveLayer = false; - if (gameobj) { - /* Insert object to the constraint game object list - * so we can check later if there is a instance in the scene or - * an instance and its actual group definition. */ - convertedlist.insert((KX_GameObject*)gameobj->AddRef()); - - /* macro calls object conversion funcs */ - BL_CONVERTBLENDEROBJECT_SINGLE; - - if (gameobj->IsDupliGroup()) - { - if (allgrouplist.insert(blenderobject->dup_group).second) - { - grouplist.insert(blenderobject->dup_group); - } - } - - /* see comment above re: mem leaks */ - gameobj->Release(); - } - } - } - FOREACH_GROUP_OBJECT_END; - } - } - } - - // non-camera objects not supported as camera currently - if (blenderscene->camera && blenderscene->camera->type == OB_CAMERA) { - KX_Camera *gamecamera= (KX_Camera*) converter->FindGameObject(blenderscene->camera); - - if (gamecamera) - kxscene->SetActiveCamera(gamecamera); - } - - // Set up armatures - set::iterator oit; - for (oit=allblobj.begin(); oit!=allblobj.end(); oit++) - { - Object* blenderobj = *oit; - if (blenderobj->type==OB_MESH) { - Mesh *me = (Mesh*)blenderobj->data; - - if (me->dvert) { - BL_DeformableGameObject *obj = (BL_DeformableGameObject*)converter->FindGameObject(blenderobj); - - if (obj && BL_ModifierDeformer::HasArmatureDeformer(blenderobj) && blenderobj->parent && blenderobj->parent->type==OB_ARMATURE) { - KX_GameObject *par = converter->FindGameObject(blenderobj->parent); - if (par && obj->GetDeformer()) - ((BL_SkinDeformer*)obj->GetDeformer())->SetArmature((BL_ArmatureObject*) par); - } - } - } - } - - // create hierarchy information - int i; - vector::iterator pcit; - - for (pcit = vec_parent_child.begin();!(pcit==vec_parent_child.end());++pcit) - { - - struct Object* blenderchild = pcit->m_blenderchild; - struct Object* blenderparent = blenderchild->parent; - KX_GameObject* parentobj = converter->FindGameObject(blenderparent); - KX_GameObject* childobj = converter->FindGameObject(blenderchild); - - assert(childobj); - - if (!parentobj || objectlist->SearchValue(childobj) != objectlist->SearchValue(parentobj)) - { - // special case: the parent and child object are not in the same layer. - // This weird situation is used in Apricot for test purposes. - // Resolve it by not converting the child - childobj->GetSGNode()->DisconnectFromParent(); - delete pcit->m_gamechildnode; - // Now destroy the child object but also all its descendent that may already be linked - // Remove the child reference in the local list! - // Note: there may be descendents already if the children of the child were processed - // by this loop before the child. In that case, we must remove the children also - CListValue* childrenlist = childobj->GetChildrenRecursive(); - childrenlist->Add(childobj->AddRef()); - for ( i=0;iGetCount();i++) - { - KX_GameObject* obj = static_cast(childrenlist->GetValue(i)); - if (sumolist->RemoveValue(obj)) - obj->Release(); - if (logicbrick_conversionlist->RemoveValue(obj)) - obj->Release(); - } - childrenlist->Release(); - - // now destroy recursively - converter->UnregisterGameObject(childobj); // removing objects during conversion make sure this runs too - kxscene->RemoveObject(childobj); - - continue; - } - - switch (blenderchild->partype) - { - case PARVERT1: - { - // creat a new vertex parent relationship for this node. - KX_VertexParentRelation * vertex_parent_relation = KX_VertexParentRelation::New(); - pcit->m_gamechildnode->SetParentRelation(vertex_parent_relation); - break; - } - case PARSLOW: - { - // creat a new slow parent relationship for this node. - KX_SlowParentRelation * slow_parent_relation = KX_SlowParentRelation::New(blenderchild->sf); - pcit->m_gamechildnode->SetParentRelation(slow_parent_relation); - break; - } - case PARBONE: - { - // parent this to a bone - Bone *parent_bone = BKE_armature_find_bone_name(BKE_armature_from_object(blenderchild->parent), - blenderchild->parsubstr); - - if (parent_bone) { - KX_BoneParentRelation *bone_parent_relation = KX_BoneParentRelation::New(parent_bone); - pcit->m_gamechildnode->SetParentRelation(bone_parent_relation); - } - - break; - } - case PARSKEL: // skinned - ignore - break; - case PAROBJECT: - case PARVERT3: - default: - // unhandled - break; - } - - parentobj-> GetSGNode()->AddChild(pcit->m_gamechildnode); - } - vec_parent_child.clear(); - - // find 'root' parents (object that has not parents in SceneGraph) - for (i=0;iGetCount();++i) - { - KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i); - if (gameobj->GetSGNode()->GetSGParent() == 0) - { - parentlist->Add(gameobj->AddRef()); - gameobj->NodeUpdateGS(0); - } - } - - // create graphic controller for culling - if (kxscene->GetDbvtCulling()) - { - bool occlusion = false; - for (i=0; iGetCount();i++) - { - KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i); - if (gameobj->GetMeshCount() > 0) - { - MT_Point3 box[2]; - gameobj->GetSGNode()->BBox().getmm(box, MT_Transform::Identity()); - // box[0] is the min, box[1] is the max - bool isactive = objectlist->SearchValue(gameobj); - BL_CreateGraphicObjectNew(gameobj,box[0],box[1],kxscene,isactive,physics_engine); - if (gameobj->GetOccluder()) - occlusion = true; - } - } - if (occlusion) - kxscene->SetDbvtOcclusionRes(blenderscene->gm.occlusionRes); - } - if (blenderscene->world) - kxscene->GetPhysicsEnvironment()->SetNumTimeSubSteps(blenderscene->gm.physubstep); - - // now that the scenegraph is complete, let's instantiate the deformers. - // We need that to create reusable derived mesh and physic shapes - for (i=0;iGetCount();++i) - { - KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i); - if (gameobj->GetDeformer()) - gameobj->GetDeformer()->UpdateBuckets(); - } - - // Set up armature constraints and shapekey drivers - for (i=0;iGetCount();++i) - { - KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i); - if (gameobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE) - { - BL_ArmatureObject *armobj = (BL_ArmatureObject*)gameobj; - armobj->LoadConstraints(converter); - - CListValue *children = armobj->GetChildren(); - for (int j=0; jGetCount();++j) - { - BL_ShapeDeformer *deform = dynamic_cast(((KX_GameObject*)children->GetValue(j))->GetDeformer()); - if (deform) - deform->LoadShapeDrivers(armobj); - } - - children->Release(); - } - } - - bool processCompoundChildren = false; - // create physics information - for (i=0;iGetCount();i++) - { - KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i); - struct Object* blenderobject = gameobj->GetBlenderObject(); - int nummeshes = gameobj->GetMeshCount(); - RAS_MeshObject* meshobj = 0; - if (nummeshes > 0) - { - meshobj = gameobj->GetMesh(0); - } - int layerMask = (groupobj.find(blenderobject) == groupobj.end()) ? activeLayerBitInfo : 0; - BL_CreatePhysicsObjectNew(gameobj,blenderobject,meshobj,kxscene,layerMask,converter,processCompoundChildren); - } - - processCompoundChildren = true; - // create physics information - for (i=0;iGetCount();i++) - { - KX_GameObject* gameobj = (KX_GameObject*) sumolist->GetValue(i); - struct Object* blenderobject = gameobj->GetBlenderObject(); - int nummeshes = gameobj->GetMeshCount(); - RAS_MeshObject* meshobj = 0; - if (nummeshes > 0) - { - meshobj = gameobj->GetMesh(0); - } - int layerMask = (groupobj.find(blenderobject) == groupobj.end()) ? activeLayerBitInfo : 0; - BL_CreatePhysicsObjectNew(gameobj,blenderobject,meshobj,kxscene,layerMask,converter,processCompoundChildren); - } - - // create physics joints - for (i=0;iGetCount();i++) - { - PHY_IPhysicsEnvironment *physEnv = kxscene->GetPhysicsEnvironment(); - KX_GameObject *gameobj = (KX_GameObject *)sumolist->GetValue(i); - struct Object *blenderobject = gameobj->GetBlenderObject(); - ListBase *conlist = get_active_constraints2(blenderobject); - bConstraint *curcon; - - if (!conlist) - continue; - - for (curcon = (bConstraint *)conlist->first; curcon; curcon = (bConstraint *)curcon->next) { - if (curcon->type != CONSTRAINT_TYPE_RIGIDBODYJOINT) - continue; - - bRigidBodyJointConstraint *dat = (bRigidBodyJointConstraint *)curcon->data; - - /* Skip if no target or a child object is selected or constraints are deactivated */ - if (!dat->tar || dat->child || (curcon->flag & CONSTRAINT_OFF)) - continue; - - /* Store constraints of grouped and instanced objects for all layers */ - gameobj->AddConstraint(dat); - - /** if it's during libload we only add constraints in the object but - * doesn't create it. Constraint will be replicated later in scene->MergeScene - */ - if (libloading) - continue; - - /* Skipped already converted constraints. - * This will happen when a group instance is made from a linked group instance - * and both are on the active layer. */ - if (bl_isConstraintInList(gameobj, convertedlist)) - continue; - - KX_GameObject *gotar = getGameOb(dat->tar->id.name + 2, sumolist); - - if (gotar && (gotar->GetLayer()&activeLayerBitInfo) && gotar->GetPhysicsController() && - (gameobj->GetLayer()&activeLayerBitInfo) && gameobj->GetPhysicsController()) - { - physEnv->SetupObjectConstraints(gameobj, gotar, dat); - } - } - } - - /* cleanup converted set of group objects */ - set::iterator gobit; - for (gobit = convertedlist.begin(); gobit != convertedlist.end(); gobit++) - (*gobit)->Release(); - - convertedlist.clear(); - sumolist->Release(); - - // convert world - KX_WorldInfo* worldinfo = new KX_WorldInfo(blenderscene, blenderscene->world); - converter->RegisterWorldInfo(worldinfo); - kxscene->SetWorldInfo(worldinfo); - - //create object representations for obstacle simulation - KX_ObstacleSimulation* obssimulation = kxscene->GetObstacleSimulation(); - if (obssimulation) - { - for ( i=0;iGetCount();i++) - { - KX_GameObject* gameobj = static_cast(objectlist->GetValue(i)); - struct Object* blenderobject = gameobj->GetBlenderObject(); - if (blenderobject->gameflag & OB_HASOBSTACLE) - { - obssimulation->AddObstacleForObj(gameobj); - } - } - } - - //process navigation mesh objects - for ( i=0; iGetCount();i++) - { - KX_GameObject* gameobj = static_cast(objectlist->GetValue(i)); - struct Object* blenderobject = gameobj->GetBlenderObject(); - if (blenderobject->type==OB_MESH && (blenderobject->gameflag & OB_NAVMESH)) - { - KX_NavMeshObject* navmesh = static_cast(gameobj); - navmesh->SetVisible(0, true); - navmesh->BuildNavMesh(); - if (obssimulation) - obssimulation->AddObstaclesForNavMesh(navmesh); - } - } - for ( i=0; iGetCount();i++) - { - KX_GameObject* gameobj = static_cast(inactivelist->GetValue(i)); - struct Object* blenderobject = gameobj->GetBlenderObject(); - if (blenderobject->type==OB_MESH && (blenderobject->gameflag & OB_NAVMESH)) - { - KX_NavMeshObject* navmesh = static_cast(gameobj); - navmesh->SetVisible(0, true); - } - } - - // convert logic bricks, sensors, controllers and actuators - for (i=0;iGetCount();i++) - { - KX_GameObject* gameobj = static_cast(logicbrick_conversionlist->GetValue(i)); - struct Object* blenderobj = gameobj->GetBlenderObject(); - int layerMask = (groupobj.find(blenderobj) == groupobj.end()) ? activeLayerBitInfo : 0; - bool isInActiveLayer = (blenderobj->lay & layerMask)!=0; - BL_ConvertActuators(maggie->name, blenderobj,gameobj,logicmgr,kxscene,ketsjiEngine,layerMask,isInActiveLayer,converter); - } - for ( i=0;iGetCount();i++) - { - KX_GameObject* gameobj = static_cast(logicbrick_conversionlist->GetValue(i)); - struct Object* blenderobj = gameobj->GetBlenderObject(); - int layerMask = (groupobj.find(blenderobj) == groupobj.end()) ? activeLayerBitInfo : 0; - bool isInActiveLayer = (blenderobj->lay & layerMask)!=0; - BL_ConvertControllers(blenderobj,gameobj,logicmgr, layerMask,isInActiveLayer,converter, libloading); - } - for ( i=0;iGetCount();i++) - { - KX_GameObject* gameobj = static_cast(logicbrick_conversionlist->GetValue(i)); - struct Object* blenderobj = gameobj->GetBlenderObject(); - int layerMask = (groupobj.find(blenderobj) == groupobj.end()) ? activeLayerBitInfo : 0; - bool isInActiveLayer = (blenderobj->lay & layerMask)!=0; - BL_ConvertSensors(blenderobj,gameobj,logicmgr,kxscene,ketsjiEngine,layerMask,isInActiveLayer,canvas,converter); - // set the init state to all objects - gameobj->SetInitState((blenderobj->init_state)?blenderobj->init_state:blenderobj->state); - } - // apply the initial state to controllers, only on the active objects as this registers the sensors - for ( i=0;iGetCount();i++) - { - KX_GameObject* gameobj = static_cast(objectlist->GetValue(i)); - gameobj->ResetState(); - } - - logicbrick_conversionlist->Release(); - - // Calculate the scene btree - - // too slow - commented out. - //kxscene->SetNodeTree(tf.MakeTree()); - - // instantiate dupli group, we will loop trough the object - // that are in active layers. Note that duplicating group - // has the effect of adding objects at the end of objectlist. - // Only loop through the first part of the list. - int objcount = objectlist->GetCount(); - for (i=0;iGetValue(i); - if (gameobj->IsDupliGroup()) - { - kxscene->DupliGroupRecurse(gameobj, 0); - } - } - - KX_Camera *activecam = kxscene->GetActiveCamera(); - MT_Scalar distance = (activecam)? activecam->GetCameraFar() - activecam->GetCameraNear(): 100.0f; - RAS_BucketManager *bucketmanager = kxscene->GetBucketManager(); - bucketmanager->OptimizeBuckets(distance); -} - diff --git a/source/gameengine/Converter/BL_BlenderDataConversion.h b/source/gameengine/Converter/BL_BlenderDataConversion.h deleted file mode 100644 index 22210cc6035..00000000000 --- a/source/gameengine/Converter/BL_BlenderDataConversion.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 BL_BlenderDataConversion.h - * \ingroup bgeconv - */ - -#ifndef __BL_BLENDERDATACONVERSION_H__ -#define __BL_BLENDERDATACONVERSION_H__ - -#include "CTR_HashedPtr.h" -#include "STR_String.h" -#include "EXP_Python.h" -#include "KX_PhysicsEngineEnums.h" -#include "SCA_IInputDevice.h" - -class RAS_MeshObject* BL_ConvertMesh(struct Mesh* mesh,struct Object* lightobj,class KX_Scene* scene, class KX_BlenderSceneConverter *converter, bool libloading); - -void BL_ConvertBlenderObjects(struct Main* maggie, - class KX_Scene* kxscene, - class KX_KetsjiEngine* ketsjiEngine, - e_PhysicsEngine physics_engine, - class RAS_IRasterizer* rendertools, - class RAS_ICanvas* canvas, - class KX_BlenderSceneConverter* sceneconverter, - bool alwaysUseExpandFraming, - bool libloading=false - ); - -SCA_IInputDevice::KX_EnumInputs ConvertKeyCode(int key_code); - -#endif /* __BL_BLENDERDATACONVERSION_H__ */ diff --git a/source/gameengine/Converter/BL_DeformableGameObject.cpp b/source/gameengine/Converter/BL_DeformableGameObject.cpp deleted file mode 100644 index 3a4a27a6722..00000000000 --- a/source/gameengine/Converter/BL_DeformableGameObject.cpp +++ /dev/null @@ -1,116 +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/Converter/BL_DeformableGameObject.cpp - * \ingroup bgeconv - */ - - -#include "BL_DeformableGameObject.h" -#include "BL_ShapeDeformer.h" -#include "BL_ShapeActionActuator.h" -#include "RAS_MaterialBucket.h" - - -BL_DeformableGameObject::~BL_DeformableGameObject() -{ - if (m_pDeformer) - delete m_pDeformer; // __NLA : Temporary until we decide where to put this -} - -void BL_DeformableGameObject::ProcessReplica() -{ - KX_GameObject::ProcessReplica(); - - if (m_pDeformer) - m_pDeformer= (BL_MeshDeformer*)m_pDeformer->GetReplica(); -} - -CValue* BL_DeformableGameObject::GetReplica() -{ - - BL_DeformableGameObject* replica = new BL_DeformableGameObject(*this);//m_float,GetName()); - replica->ProcessReplica(); - return replica; -} - -bool BL_DeformableGameObject::SetActiveAction(BL_ShapeActionActuator *act, short priority, double curtime) -{ - if (curtime != m_lastframe) { - m_activePriority = 9999; - m_lastframe= curtime; - m_activeAct = NULL; - } - - if (priority<=m_activePriority) - { - if (m_activeAct && (m_activeAct!=act)) - m_activeAct->SetBlendTime(0.0f); /* Reset the blend timer */ - m_activeAct = act; - m_activePriority = priority; - m_lastframe = curtime; - - return true; - } - else { - act->SetBlendTime(0.0f); - return false; - } -} - -bool BL_DeformableGameObject::GetShape(vector &shape) -{ - shape.clear(); - BL_ShapeDeformer* shape_deformer = dynamic_cast(m_pDeformer); - if (shape_deformer) - { - // this check is normally superfluous: a shape deformer can only be created if the mesh - // has relative keys - Key* key = shape_deformer->GetKey(); - if (key && key->type==KEY_RELATIVE) - { - KeyBlock *kb; - for (kb = (KeyBlock *)key->block.first; kb; kb = (KeyBlock *)kb->next) - { - shape.push_back(kb->curval); - } - } - } - return !shape.empty(); -} - -void BL_DeformableGameObject::SetDeformer(class RAS_Deformer* deformer) -{ - m_pDeformer = deformer; - - SG_QList::iterator mit(m_meshSlots); - for (mit.begin(); !mit.end(); ++mit) - { - (*mit)->SetDeformer(deformer); - } -} - diff --git a/source/gameengine/Converter/BL_DeformableGameObject.h b/source/gameengine/Converter/BL_DeformableGameObject.h deleted file mode 100644 index 95e3b7c517d..00000000000 --- a/source/gameengine/Converter/BL_DeformableGameObject.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 BL_DeformableGameObject.h - * \ingroup bgeconv - */ - -#ifndef __BL_DEFORMABLEGAMEOBJECT_H__ -#define __BL_DEFORMABLEGAMEOBJECT_H__ - -#ifdef _MSC_VER -# pragma warning (disable:4786) // get rid of stupid stl-visual compiler debug warning -#endif - -#include "DNA_mesh_types.h" -#include "KX_GameObject.h" -#include "BL_MeshDeformer.h" -#include "KX_SoftBodyDeformer.h" -#include - -class BL_ShapeActionActuator; -struct Key; - -class BL_DeformableGameObject : public KX_GameObject -{ -public: - CValue* GetReplica(); - - double GetLastFrame () - { - return m_lastframe; - } - Object* GetBlendObject() - { - return m_blendobj; - } - virtual void Relink(CTR_Map*map) - { - if (m_pDeformer) - m_pDeformer->Relink (map); - KX_GameObject::Relink(map); - }; - void ProcessReplica(); - - BL_DeformableGameObject(Object* blendobj, void* sgReplicationInfo, SG_Callbacks callbacks) : - KX_GameObject(sgReplicationInfo,callbacks), - m_pDeformer(NULL), - m_activeAct(NULL), - m_lastframe(0.0), - m_blendobj(blendobj), - m_activePriority(9999) - { - m_isDeformable = true; - }; - virtual ~BL_DeformableGameObject(); - bool SetActiveAction(class BL_ShapeActionActuator *act, short priority, double curtime); - - bool GetShape(vector &shape); - - virtual void SetDeformer(class RAS_Deformer* deformer); - virtual class RAS_Deformer* GetDeformer() - { - return m_pDeformer; - } - -public: - -protected: - - RAS_Deformer *m_pDeformer; - - class BL_ShapeActionActuator *m_activeAct; - double m_lastframe; - Object* m_blendobj; - short m_activePriority; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_DeformableGameObject") -#endif -}; - -#endif /* __BL_DEFORMABLEGAMEOBJECT_H__ */ diff --git a/source/gameengine/Converter/BL_MeshDeformer.cpp b/source/gameengine/Converter/BL_MeshDeformer.cpp deleted file mode 100644 index 911ff245ab4..00000000000 --- a/source/gameengine/Converter/BL_MeshDeformer.cpp +++ /dev/null @@ -1,239 +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 ***** - * Simple deformation controller that restores a mesh to its rest position - */ - -/** \file gameengine/Converter/BL_MeshDeformer.cpp - * \ingroup bgeconv - */ - -#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 "BL_DeformableGameObject.h" -#include "BL_MeshDeformer.h" -#include "RAS_MeshObject.h" -#include "DNA_mesh_types.h" -#include "DNA_meshdata_types.h" - -#include "CTR_Map.h" -#include "STR_HashedString.h" -#include "BLI_math.h" - -bool BL_MeshDeformer::Apply(RAS_IPolyMaterial*) -{ - size_t i; - - // only apply once per frame if the mesh is actually modified - if (m_pMeshObject->MeshModified() && - m_lastDeformUpdate != m_gameobj->GetLastFrame()) - { - // For each material - for (list::iterator mit= m_pMeshObject->GetFirstMaterial(); - mit != m_pMeshObject->GetLastMaterial(); ++ mit) { - if (!mit->m_slots[(void*)m_gameobj]) - continue; - - RAS_MeshSlot *slot = *mit->m_slots[(void*)m_gameobj]; - RAS_MeshSlot::iterator it; - - // for each array - for (slot->begin(it); !slot->end(it); slot->next(it)) { - // For each vertex - for (i=it.startvertex; imvert[v.getOrigIndex()].co); - } - } - } - - m_lastDeformUpdate = m_gameobj->GetLastFrame(); - - return true; - } - - return false; -} - -BL_MeshDeformer::~BL_MeshDeformer() -{ - if (m_transverts) - delete [] m_transverts; - if (m_transnors) - delete [] m_transnors; -} - -void BL_MeshDeformer::ProcessReplica() -{ - m_transverts = NULL; - m_transnors = NULL; - m_tvtot = 0; - m_bDynamic=false; - m_lastDeformUpdate = -1; -} - -void BL_MeshDeformer::Relink(CTR_Map*map) -{ - void **h_obj = (*map)[m_gameobj]; - - if (h_obj) - m_gameobj = (BL_DeformableGameObject*)(*h_obj); - else - m_gameobj = NULL; -} - -/** - * \warning This function is expensive! - */ -void BL_MeshDeformer::RecalcNormals() -{ - /* We don't normalize for performance, not doing it for faces normals - * gives area-weight normals which often look better anyway, and use - * GL_NORMALIZE so we don't have to do per vertex normalization either - * since the GPU can do it faster */ - list::iterator mit; - RAS_MeshSlot::iterator it; - size_t i; - - /* set vertex normals to zero */ - memset(m_transnors, 0, sizeof(float)*3*m_bmesh->totvert); - - /* add face normals to vertices. */ - for (mit = m_pMeshObject->GetFirstMaterial(); - mit != m_pMeshObject->GetLastMaterial(); ++ mit) { - if (!mit->m_slots[(void*)m_gameobj]) - continue; - - RAS_MeshSlot *slot = *mit->m_slots[(void*)m_gameobj]; - - for (slot->begin(it); !slot->end(it); slot->next(it)) { - int nvert = (int)it.array->m_type; - - for (i=0; igetOrigIndex()]; - - n1[0] = co1[0] - co3[0]; - n1[1] = co1[1] - co3[1]; - n1[2] = co1[2] - co3[2]; - - n2[0] = co2[0] - co4[0]; - n2[1] = co2[1] - co4[1]; - n2[2] = co2[2] - co4[2]; - } - else { - n1[0] = co1[0] - co2[0]; - n2[0] = co2[0] - co3[0]; - n1[1] = co1[1] - co2[1]; - - n2[1] = co2[1] - co3[1]; - n1[2] = co1[2] - co2[2]; - n2[2] = co2[2] - co3[2]; - } - - fnor[0] = n1[1] * n2[2] - n1[2] * n2[1]; - fnor[1] = n1[2] * n2[0] - n1[0] * n2[2]; - fnor[2] = n1[0] * n2[1] - n1[1] * n2[0]; - normalize_v3(fnor); - - /* add to vertices for smooth normals */ - float *vn1 = m_transnors[v1.getOrigIndex()]; - float *vn2 = m_transnors[v2.getOrigIndex()]; - float *vn3 = m_transnors[v3.getOrigIndex()]; - - vn1[0] += fnor[0]; vn1[1] += fnor[1]; vn1[2] += fnor[2]; - vn2[0] += fnor[0]; vn2[1] += fnor[1]; vn2[2] += fnor[2]; - vn3[0] += fnor[0]; vn3[1] += fnor[1]; vn3[2] += fnor[2]; - - if (v4) { - float *vn4 = m_transnors[v4->getOrigIndex()]; - vn4[0] += fnor[0]; vn4[1] += fnor[1]; vn4[2] += fnor[2]; - } - - /* in case of flat - just assign, the vertices are split */ - if (v1.getFlag() & RAS_TexVert::FLAT) { - v1.SetNormal(fnor); - v2.SetNormal(fnor); - v3.SetNormal(fnor); - if (v4) - v4->SetNormal(fnor); - } - } - } - } - - /* assign smooth vertex normals */ - for (mit = m_pMeshObject->GetFirstMaterial(); - mit != m_pMeshObject->GetLastMaterial(); ++ mit) { - if (!mit->m_slots[(void*)m_gameobj]) - continue; - - RAS_MeshSlot *slot = *mit->m_slots[(void*)m_gameobj]; - - for (slot->begin(it); !slot->end(it); slot->next(it)) { - for (i=it.startvertex; itotvert) { - if (m_transverts) - delete [] m_transverts; - if (m_transnors) - delete [] m_transnors; - - m_transverts=new float[m_bmesh->totvert][3]; - m_transnors=new float[m_bmesh->totvert][3]; - m_tvtot = m_bmesh->totvert; - } -} - diff --git a/source/gameengine/Converter/BL_MeshDeformer.h b/source/gameengine/Converter/BL_MeshDeformer.h deleted file mode 100644 index 6e84cdf03f8..00000000000 --- a/source/gameengine/Converter/BL_MeshDeformer.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 BL_MeshDeformer.h - * \ingroup bgeconv - */ - -#ifndef __BL_MESHDEFORMER_H__ -#define __BL_MESHDEFORMER_H__ - -#include "RAS_Deformer.h" -#include "DNA_object_types.h" -#include "DNA_key_types.h" -#include "MT_Point3.h" -#include - -#ifdef _MSC_VER -# pragma warning (disable:4786) /* get rid of stupid stl-visual compiler debug warning */ -#endif - -class BL_DeformableGameObject; - -class BL_MeshDeformer : public RAS_Deformer -{ -public: - void VerifyStorage(); - void RecalcNormals(); - virtual void Relink(CTR_Map*map); - BL_MeshDeformer(BL_DeformableGameObject *gameobj, - struct Object* obj, - class RAS_MeshObject *meshobj ): - m_pMeshObject(meshobj), - m_bmesh((struct Mesh*)(obj->data)), - m_transverts(0), - m_transnors(0), - m_objMesh(obj), - m_tvtot(0), - m_gameobj(gameobj), - m_lastDeformUpdate(-1) - {}; - virtual ~BL_MeshDeformer(); - virtual void SetSimulatedTime(double time) {} - virtual bool Apply(class RAS_IPolyMaterial *mat); - virtual bool Update(void) { return false; } - virtual bool UpdateBuckets(void) { return false; } - virtual RAS_Deformer* GetReplica() {return NULL;} - virtual void ProcessReplica(); - struct Mesh* GetMesh() { return m_bmesh; } - virtual class RAS_MeshObject* GetRasMesh() { return m_pMeshObject; } - virtual float (* GetTransVerts(int *tot))[3] { *tot= m_tvtot; return m_transverts; } - // virtual void InitDeform(double time) {} - -protected: - class RAS_MeshObject* m_pMeshObject; - struct Mesh* m_bmesh; - - // this is so m_transverts doesn't need to be converted - // before deformation - float (*m_transverts)[3]; - float (*m_transnors)[3]; - struct Object* m_objMesh; - // -- - int m_tvtot; - BL_DeformableGameObject* m_gameobj; - double m_lastDeformUpdate; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_MeshDeformer") -#endif -}; - -#endif - diff --git a/source/gameengine/Converter/BL_ModifierDeformer.cpp b/source/gameengine/Converter/BL_ModifierDeformer.cpp deleted file mode 100644 index 3be2c1aff43..00000000000 --- a/source/gameengine/Converter/BL_ModifierDeformer.cpp +++ /dev/null @@ -1,227 +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/Converter/BL_ModifierDeformer.cpp - * \ingroup bgeconv - */ - -#ifdef _MSC_VER -# pragma warning (disable:4786) -#endif - -#include "MEM_guardedalloc.h" -#include "BL_ModifierDeformer.h" -#include "CTR_Map.h" -#include "STR_HashedString.h" -#include "RAS_IPolygonMaterial.h" -#include "RAS_MeshObject.h" -#include "PHY_IGraphicController.h" - -#include "DNA_armature_types.h" -#include "DNA_action_types.h" -#include "DNA_key_types.h" -#include "DNA_mesh_types.h" -#include "DNA_meshdata_types.h" -#include "DNA_curve_types.h" -#include "DNA_modifier_types.h" -#include "DNA_scene_types.h" -#include "BLI_utildefines.h" -#include "BKE_armature.h" -#include "BKE_action.h" -#include "BKE_key.h" -#include "BKE_ipo.h" -#include "MT_Point3.h" - -extern "C"{ - #include "BKE_customdata.h" - #include "BKE_DerivedMesh.h" - #include "BKE_lattice.h" - #include "BKE_modifier.h" -} - -#include "BLI_blenlib.h" -#include "BLI_math.h" - -BL_ModifierDeformer::~BL_ModifierDeformer() -{ - if (m_dm) { - // deformedOnly is used as a user counter - if (--m_dm->deformedOnly == 0) { - m_dm->needsFree = 1; - m_dm->release(m_dm); - } - } -}; - -RAS_Deformer *BL_ModifierDeformer::GetReplica() -{ - BL_ModifierDeformer *result; - - result = new BL_ModifierDeformer(*this); - result->ProcessReplica(); - return result; -} - -void BL_ModifierDeformer::ProcessReplica() -{ - /* Note! - This is not inherited from PyObjectPlus */ - BL_ShapeDeformer::ProcessReplica(); - if (m_dm) - // by default try to reuse mesh, deformedOnly is used as a user count - m_dm->deformedOnly++; - // this will force an update and if the mesh cannot be reused, a new one will be created - m_lastModifierUpdate = -1; -} - -bool BL_ModifierDeformer::HasCompatibleDeformer(Object *ob) -{ - if (!ob->modifiers.first) - return false; - // soft body cannot use mesh modifiers - if ((ob->gameflag & OB_SOFT_BODY) != 0) - return false; - ModifierData* md; - for (md = (ModifierData *)ob->modifiers.first; md; md = md->next) { - if (modifier_dependsOnTime(md)) - continue; - if (!(md->mode & eModifierMode_Realtime)) - continue; - /* armature modifier are handled by SkinDeformer, not ModifierDeformer */ - if (md->type == eModifierType_Armature ) - continue; - return true; - } - return false; -} - -bool BL_ModifierDeformer::HasArmatureDeformer(Object *ob) -{ - if (!ob->modifiers.first) - return false; - - ModifierData* md = (ModifierData*)ob->modifiers.first; - if (md->type == eModifierType_Armature ) - return true; - - return false; -} - -// return a deformed mesh that supports mapping (with a valid CD_ORIGINDEX layer) -struct DerivedMesh* BL_ModifierDeformer::GetPhysicsMesh() -{ - /* TODO: This doesn't work currently because of eval_ctx. */ -#if 0 - /* we need to compute the deformed mesh taking into account the current - * shape and skin deformers, we cannot just call mesh_create_derived_physics() - * because that would use the m_transvers already deformed previously by BL_ModifierDeformer::Update(), - * so restart from scratch by forcing a full update the shape/skin deformers - * (will do nothing if there is no such deformer) */ - BL_ShapeDeformer::ForceUpdate(); - BL_ShapeDeformer::Update(); - // now apply the modifiers but without those that don't support mapping - Object* blendobj = m_gameobj->GetBlendObject(); - /* hack: the modifiers require that the mesh is attached to the object - * It may not be the case here because of replace mesh actuator */ - Mesh *oldmesh = (Mesh*)blendobj->data; - blendobj->data = m_bmesh; - DerivedMesh *dm = mesh_create_derived_physics(m_scene, blendobj, m_transverts, CD_MASK_MESH); - /* restore object data */ - blendobj->data = oldmesh; - /* m_transverts is correct here (takes into account deform only modifiers) */ - /* the derived mesh returned by this function must be released by the caller !!! */ - return dm; -#endif - return NULL; -} - -bool BL_ModifierDeformer::Update(void) -{ - /* TODO: This doesn't work currently because of eval_ctx. */ -#if 0 - bool bShapeUpdate = BL_ShapeDeformer::Update(); - - if (bShapeUpdate || m_lastModifierUpdate != m_gameobj->GetLastFrame()) { - // static derived mesh are not updated - if (m_dm == NULL || m_bDynamic) { - /* execute the modifiers */ - Object* blendobj = m_gameobj->GetBlendObject(); - /* hack: the modifiers require that the mesh is attached to the object - * It may not be the case here because of replace mesh actuator */ - Mesh *oldmesh = (Mesh*)blendobj->data; - blendobj->data = m_bmesh; - /* execute the modifiers */ - DerivedMesh *dm = mesh_create_derived_no_virtual(m_scene, blendobj, m_transverts, CD_MASK_MESH); - /* restore object data */ - blendobj->data = oldmesh; - /* free the current derived mesh and replace, (dm should never be NULL) */ - if (m_dm != NULL) { - // HACK! use deformedOnly as a user counter - if (--m_dm->deformedOnly == 0) { - m_dm->needsFree = 1; - m_dm->release(m_dm); - } - } - m_dm = dm; - // get rid of temporary data - m_dm->needsFree = 0; - m_dm->release(m_dm); - // HACK! use deformedOnly as a user counter - m_dm->deformedOnly = 1; - DM_update_materials(m_dm, blendobj); - /* update the graphic controller */ - PHY_IGraphicController *ctrl = m_gameobj->GetGraphicController(); - if (ctrl) { - float min[3], max[3]; - INIT_MINMAX(min, max); - m_dm->getMinMax(m_dm, min, max); - ctrl->SetLocalAabb(min, max); - } - } - m_lastModifierUpdate=m_gameobj->GetLastFrame(); - bShapeUpdate = true; - - int nmat = m_pMeshObject->NumMaterials(); - for (int imat=0; imatGetMeshMaterial(imat); - RAS_MeshSlot **slot = mmat->m_slots[(void*)m_gameobj]; - if (!slot || !*slot) - continue; - (*slot)->m_pDerivedMesh = m_dm; - } - } - return bShapeUpdate; -#endif - return false; -} - -bool BL_ModifierDeformer::Apply(RAS_IPolyMaterial *mat) -{ - if (!Update()) - return false; - - return true; -} diff --git a/source/gameengine/Converter/BL_ModifierDeformer.h b/source/gameengine/Converter/BL_ModifierDeformer.h deleted file mode 100644 index 4efe4ca5bfc..00000000000 --- a/source/gameengine/Converter/BL_ModifierDeformer.h +++ /dev/null @@ -1,115 +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 BL_ModifierDeformer.h - * \ingroup bgeconv - */ - -#ifndef __BL_MODIFIERDEFORMER_H__ -#define __BL_MODIFIERDEFORMER_H__ - -#ifdef _MSC_VER -# pragma warning (disable:4786) /* get rid of stupid stl-visual compiler debug warning */ -#endif - -#include "BL_ShapeDeformer.h" -#include "BL_DeformableGameObject.h" -#include - -struct DerivedMesh; -struct Object; - -class BL_ModifierDeformer : public BL_ShapeDeformer -{ -public: - static bool HasCompatibleDeformer(Object *ob); - static bool HasArmatureDeformer(Object *ob); - - - BL_ModifierDeformer(BL_DeformableGameObject *gameobj, - Scene *scene, - Object *bmeshobj, - RAS_MeshObject *mesh) - : - BL_ShapeDeformer(gameobj,bmeshobj, mesh), - m_lastModifierUpdate(-1), - m_scene(scene), - m_dm(NULL) - { - m_recalcNormal = false; - } - - /* this second constructor is needed for making a mesh deformable on the fly. */ - BL_ModifierDeformer(BL_DeformableGameObject *gameobj, - struct Scene *scene, - struct Object *bmeshobj_old, - struct Object *bmeshobj_new, - class RAS_MeshObject *mesh, - bool release_object, - BL_ArmatureObject* arma = NULL) - : - BL_ShapeDeformer(gameobj, bmeshobj_old, bmeshobj_new, mesh, release_object, false, arma), - m_lastModifierUpdate(-1), - m_scene(scene), - m_dm(NULL) - { - /* pass */ - } - - virtual void ProcessReplica(); - virtual RAS_Deformer *GetReplica(); - virtual ~BL_ModifierDeformer(); - virtual bool UseVertexArray() - { - return false; - } - - bool Update (void); - bool Apply(RAS_IPolyMaterial *mat); - void ForceUpdate() - { - m_lastModifierUpdate = -1.0; - }; - virtual struct DerivedMesh* GetFinalMesh() - { - return m_dm; - } - // The derived mesh returned by this function must be released! - virtual struct DerivedMesh* GetPhysicsMesh(); - -protected: - double m_lastModifierUpdate; - Scene *m_scene; - DerivedMesh *m_dm; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_ModifierDeformer") -#endif -}; - -#endif /* __BL_MODIFIERDEFORMER_H__ */ diff --git a/source/gameengine/Converter/BL_ShapeActionActuator.cpp b/source/gameengine/Converter/BL_ShapeActionActuator.cpp deleted file mode 100644 index f21db419ebc..00000000000 --- a/source/gameengine/Converter/BL_ShapeActionActuator.cpp +++ /dev/null @@ -1,563 +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/Converter/BL_ShapeActionActuator.cpp - * \ingroup bgeconv - */ - - -#include - -#include "SCA_LogicManager.h" -#include "BL_ShapeActionActuator.h" -#include "BL_ShapeDeformer.h" -#include "KX_GameObject.h" -#include "STR_HashedString.h" -#include "DNA_nla_types.h" -#include "DNA_action_types.h" -#include "DNA_anim_types.h" -#include "DNA_scene_types.h" -#include "BKE_action.h" -#include "DNA_armature_types.h" -#include "MEM_guardedalloc.h" -#include "BLI_blenlib.h" -#include "BLI_math.h" -#include "MT_Matrix4x4.h" - -#include "EXP_FloatValue.h" -#include "EXP_PyObjectPlus.h" - -extern "C" { - #include "BKE_animsys.h" - #include "BKE_key.h" - #include "RNA_access.h" -} - -BL_ShapeActionActuator::BL_ShapeActionActuator(SCA_IObject* gameobj, - const STR_String& propname, - const STR_String& framepropname, - float starttime, - float endtime, - struct bAction *action, - short playtype, - short blendin, - short priority, - float stride) - : SCA_IActuator(gameobj, KX_ACT_SHAPEACTION), - - m_lastpos(0, 0, 0), - m_blendframe(0), - m_flag(0), - m_startframe (starttime), - m_endframe(endtime) , - m_starttime(0), - m_localtime(starttime), - m_lastUpdate(-1), - m_blendin(blendin), - m_blendstart(0), - m_stridelength(stride), - m_playtype(playtype), - m_priority(priority), - m_action(action), - m_framepropname(framepropname), - m_propname(propname) -{ - m_idptr = new PointerRNA(); - BL_DeformableGameObject *obj = (BL_DeformableGameObject*)GetParent(); - BL_ShapeDeformer *shape_deformer = dynamic_cast(obj->GetDeformer()); - RNA_id_pointer_create(&shape_deformer->GetKey()->id, m_idptr); -}; - -BL_ShapeActionActuator::~BL_ShapeActionActuator() -{ - if (m_idptr) - delete m_idptr; -} - -void BL_ShapeActionActuator::ProcessReplica() -{ - SCA_IActuator::ProcessReplica(); - m_localtime=m_startframe; - m_lastUpdate=-1; -} - -void BL_ShapeActionActuator::SetBlendTime(float newtime) -{ - m_blendframe = newtime; -} - -CValue* BL_ShapeActionActuator::GetReplica() -{ - BL_ShapeActionActuator* replica = new BL_ShapeActionActuator(*this);//m_float,GetName()); - replica->ProcessReplica(); - return replica; -} - -bool BL_ShapeActionActuator::ClampLocalTime() -{ - if (m_startframe < m_endframe) { - if (m_localtime < m_startframe) - { - m_localtime = m_startframe; - return true; - } - else if (m_localtime > m_endframe) - { - m_localtime = m_endframe; - return true; - } - } else { - if (m_localtime > m_startframe) - { - m_localtime = m_startframe; - return true; - } - else if (m_localtime < m_endframe) - { - m_localtime = m_endframe; - return true; - } - } - return false; -} - -void BL_ShapeActionActuator::SetStartTime(float curtime) -{ - float direction = m_startframe < m_endframe ? 1.0 : -1.0; - - if (!(m_flag & ACT_FLAG_REVERSE)) - m_starttime = curtime - direction*(m_localtime - m_startframe)/KX_KetsjiEngine::GetAnimFrameRate(); - else - m_starttime = curtime - direction*(m_endframe - m_localtime)/KX_KetsjiEngine::GetAnimFrameRate(); -} - -void BL_ShapeActionActuator::SetLocalTime(float curtime) -{ - float delta_time = (curtime - m_starttime)*KX_KetsjiEngine::GetAnimFrameRate(); - - if (m_endframe < m_startframe) - delta_time = -delta_time; - - if (!(m_flag & ACT_FLAG_REVERSE)) - m_localtime = m_startframe + delta_time; - else - m_localtime = m_endframe - delta_time; -} - -void BL_ShapeActionActuator::BlendShape(Key* key, float srcweight) -{ - vector::const_iterator it; - float dstweight; - KeyBlock *kb; - - dstweight = 1.0F - srcweight; - - for (it=m_blendshape.begin(), kb = (KeyBlock *)key->block.first; - kb && it != m_blendshape.end(); - kb = (KeyBlock *)kb->next, it++) - { - kb->curval = kb->curval * dstweight + (*it) * srcweight; - } -} - -bool BL_ShapeActionActuator::Update(double curtime, bool frame) -{ - bool bNegativeEvent = false; - bool bPositiveEvent = false; - bool keepgoing = true; - bool wrap = false; - bool apply=true; - int priority; - float newweight; - - curtime -= KX_KetsjiEngine::GetSuspendedDelta(); - - // result = true if animation has to be continued, false if animation stops - // maybe there are events for us in the queue ! - if (frame) - { - bNegativeEvent = m_negevent; - bPositiveEvent = m_posevent; - RemoveAllEvents(); - - if (bPositiveEvent) - m_flag |= ACT_FLAG_ACTIVE; - - if (bNegativeEvent) - { - if (!(m_flag & ACT_FLAG_ACTIVE)) - return false; - m_flag &= ~ACT_FLAG_ACTIVE; - } - } - - /* This action can only be attached to a deform object */ - BL_DeformableGameObject *obj = (BL_DeformableGameObject*)GetParent(); - float length = m_endframe - m_startframe; - - priority = m_priority; - - /* Determine pre-incrementation behavior and set appropriate flags */ - switch (m_playtype) { - case ACT_ACTION_MOTION: - if (bNegativeEvent) { - keepgoing=false; - apply=false; - }; - break; - case ACT_ACTION_FROM_PROP: - if (bNegativeEvent) { - apply=false; - keepgoing=false; - } - break; - case ACT_ACTION_LOOP_END: - if (bPositiveEvent) { - if (!(m_flag & ACT_FLAG_LOCKINPUT)) { - m_flag &= ~ACT_FLAG_KEYUP; - m_flag &= ~ACT_FLAG_REVERSE; - m_flag |= ACT_FLAG_LOCKINPUT; - m_localtime = m_startframe; - m_starttime = curtime; - } - } - if (bNegativeEvent) { - m_flag |= ACT_FLAG_KEYUP; - } - break; - case ACT_ACTION_LOOP_STOP: - if (bPositiveEvent) { - if (!(m_flag & ACT_FLAG_LOCKINPUT)) { - m_flag &= ~ACT_FLAG_REVERSE; - m_flag &= ~ACT_FLAG_KEYUP; - m_flag |= ACT_FLAG_LOCKINPUT; - SetStartTime(curtime); - } - } - if (bNegativeEvent) { - m_flag |= ACT_FLAG_KEYUP; - m_flag &= ~ACT_FLAG_LOCKINPUT; - keepgoing=false; - apply=false; - } - break; - case ACT_ACTION_PINGPONG: - if (bPositiveEvent) { - if (!(m_flag & ACT_FLAG_LOCKINPUT)) { - m_flag &= ~ACT_FLAG_KEYUP; - m_localtime = m_starttime; - m_starttime = curtime; - m_flag |= ACT_FLAG_LOCKINPUT; - } - } - break; - case ACT_ACTION_FLIPPER: - if (bPositiveEvent) { - if (!(m_flag & ACT_FLAG_LOCKINPUT)) { - m_flag &= ~ACT_FLAG_REVERSE; - m_flag |= ACT_FLAG_LOCKINPUT; - SetStartTime(curtime); - } - } - else if (bNegativeEvent) { - m_flag |= ACT_FLAG_REVERSE; - m_flag &= ~ACT_FLAG_LOCKINPUT; - SetStartTime(curtime); - } - break; - case ACT_ACTION_PLAY: - if (bPositiveEvent) { - if (!(m_flag & ACT_FLAG_LOCKINPUT)) { - m_flag &= ~ACT_FLAG_REVERSE; - m_localtime = m_starttime; - m_starttime = curtime; - m_flag |= ACT_FLAG_LOCKINPUT; - } - } - break; - default: - break; - } - - /* Perform increment */ - if (keepgoing) { - if (m_playtype == ACT_ACTION_MOTION) { - MT_Point3 newpos; - MT_Point3 deltapos; - - newpos = obj->NodeGetWorldPosition(); - - /* Find displacement */ - deltapos = newpos-m_lastpos; - m_localtime += (length/m_stridelength) * deltapos.length(); - m_lastpos = newpos; - } - else { - SetLocalTime(curtime); - } - } - - /* Check if a wrapping response is needed */ - if (length) { - if (m_localtime < m_startframe || m_localtime > m_endframe) - { - m_localtime = m_startframe + fmod(m_localtime, length); - wrap = true; - } - } - else - m_localtime = m_startframe; - - /* Perform post-increment tasks */ - switch (m_playtype) { - case ACT_ACTION_FROM_PROP: - { - CValue* propval = GetParent()->GetProperty(m_propname); - if (propval) - m_localtime = propval->GetNumber(); - - if (bNegativeEvent) { - keepgoing=false; - } - } - break; - case ACT_ACTION_MOTION: - break; - case ACT_ACTION_LOOP_STOP: - break; - case ACT_ACTION_PINGPONG: - if (wrap) { - if (!(m_flag & ACT_FLAG_REVERSE)) - m_localtime = m_endframe; - else - m_localtime = m_startframe; - - m_flag &= ~ACT_FLAG_LOCKINPUT; - m_flag ^= ACT_FLAG_REVERSE; //flip direction - keepgoing = false; - } - break; - case ACT_ACTION_FLIPPER: - if (wrap) { - if (!(m_flag & ACT_FLAG_REVERSE)) { - m_localtime=m_endframe; - //keepgoing = false; - } - else { - m_localtime=m_startframe; - keepgoing = false; - } - } - break; - case ACT_ACTION_LOOP_END: - if (wrap) { - if (m_flag & ACT_FLAG_KEYUP) { - keepgoing = false; - m_localtime = m_endframe; - m_flag &= ~ACT_FLAG_LOCKINPUT; - } - SetStartTime(curtime); - } - break; - case ACT_ACTION_PLAY: - if (wrap) { - m_localtime = m_endframe; - keepgoing = false; - m_flag &= ~ACT_FLAG_LOCKINPUT; - } - break; - default: - keepgoing = false; - break; - } - - /* Set the property if its defined */ - if (m_framepropname[0] != '\0') { - CValue* propowner = GetParent(); - CValue* oldprop = propowner->GetProperty(m_framepropname); - CValue* newval = new CFloatValue(m_localtime); - if (oldprop) { - oldprop->SetValue(newval); - } else { - propowner->SetProperty(m_framepropname, newval); - } - newval->Release(); - } - - if (bNegativeEvent) - m_blendframe=0.0f; - - /* Apply the pose if necessary*/ - if (apply) { - - /* Priority test */ - if (obj->SetActiveAction(this, priority, curtime)) { - BL_ShapeDeformer *shape_deformer = dynamic_cast(obj->GetDeformer()); - Key *key = NULL; - - if (shape_deformer) - key = shape_deformer->GetKey(); - - if (!key) { - // this could happen if the mesh was changed in the middle of an action - // and the new mesh has no key, stop the action - keepgoing = false; - } - else { - ListBase tchanbase= {NULL, NULL}; - - if (m_blendin && m_blendframe==0.0f) { - // this is the start of the blending, remember the startup shape - obj->GetShape(m_blendshape); - m_blendstart = curtime; - } - - KeyBlock *kb; - // We go through and clear out the keyblocks so there isn't any interference - // from other shape actions - for (kb=(KeyBlock *)key->block.first; kb; kb=(KeyBlock *)kb->next) - kb->curval = 0.f; - - animsys_evaluate_action(m_idptr, m_action, NULL, m_localtime); - - // XXX - in 2.5 theres no way to do this. possibly not that important to support - Campbell - if (0) { // XXX !execute_ipochannels(&tchanbase)) { - // no update, this is possible if action does not match the keys, stop the action - keepgoing = false; - } - else { - // the key have changed, apply blending if needed - if (m_blendin && (m_blendframem_blendin) - m_blendframe = m_blendin; - } - m_lastUpdate = m_localtime; - } - BLI_freelistN(&tchanbase); - } - } - else { - m_blendframe = 0.0f; - } - } - - if (!keepgoing) { - m_blendframe = 0.0f; - } - return keepgoing; -}; - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ - -PyTypeObject BL_ShapeActionActuator::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "BL_ShapeActionActuator", - 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 BL_ShapeActionActuator::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef BL_ShapeActionActuator::Attributes[] = { - KX_PYATTRIBUTE_FLOAT_RW("frameStart", 0, MAXFRAMEF, BL_ShapeActionActuator, m_startframe), - KX_PYATTRIBUTE_FLOAT_RW("frameEnd", 0, MAXFRAMEF, BL_ShapeActionActuator, m_endframe), - KX_PYATTRIBUTE_FLOAT_RW("blendIn", 0, MAXFRAMEF, BL_ShapeActionActuator, m_blendin), - KX_PYATTRIBUTE_RW_FUNCTION("action", BL_ShapeActionActuator, pyattr_get_action, pyattr_set_action), - KX_PYATTRIBUTE_SHORT_RW("priority", 0, 100, false, BL_ShapeActionActuator, m_priority), - KX_PYATTRIBUTE_FLOAT_RW_CHECK("frame", 0, MAXFRAMEF, BL_ShapeActionActuator, m_localtime, CheckFrame), - KX_PYATTRIBUTE_STRING_RW("propName", 0, MAX_PROP_NAME, false, BL_ShapeActionActuator, m_propname), - KX_PYATTRIBUTE_STRING_RW("framePropName", 0, MAX_PROP_NAME, false, BL_ShapeActionActuator, m_framepropname), - KX_PYATTRIBUTE_FLOAT_RW_CHECK("blendTime", 0, MAXFRAMEF, BL_ShapeActionActuator, m_blendframe, CheckBlendTime), - KX_PYATTRIBUTE_SHORT_RW_CHECK("mode",0,100,false,BL_ShapeActionActuator,m_playtype,CheckType), - { NULL } //Sentinel -}; - -PyObject *BL_ShapeActionActuator::pyattr_get_action(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - BL_ShapeActionActuator* self = static_cast(self_v); - return PyUnicode_FromString(self->GetAction() ? self->GetAction()->id.name+2 : ""); -} - -int BL_ShapeActionActuator::pyattr_set_action(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - BL_ShapeActionActuator* self = static_cast(self_v); - /* exact copy of BL_ActionActuator's function from here down */ - if (!PyUnicode_Check(value)) - { - PyErr_SetString(PyExc_ValueError, "actuator.action = val: Shape Action Actuator, expected the string name of the action"); - return PY_SET_ATTR_FAIL; - } - - bAction *action= NULL; - STR_String val = _PyUnicode_AsString(value); - - if (val != "") - { - action= (bAction*)self->GetLogicManager()->GetActionByName(val); - if (action==NULL) - { - PyErr_SetString(PyExc_ValueError, "actuator.action = val: Shape Action Actuator, action not found!"); - return PY_SET_ATTR_FAIL; - } - } - - self->SetAction(action); - return PY_SET_ATTR_SUCCESS; - -} - -#endif // WITH_PYTHON diff --git a/source/gameengine/Converter/BL_ShapeActionActuator.h b/source/gameengine/Converter/BL_ShapeActionActuator.h deleted file mode 100644 index e96d0e0ebb4..00000000000 --- a/source/gameengine/Converter/BL_ShapeActionActuator.h +++ /dev/null @@ -1,144 +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 BL_ShapeActionActuator.h - * \ingroup bgeconv - */ - -#ifndef __BL_SHAPEACTIONACTUATOR_H__ -#define __BL_SHAPEACTIONACTUATOR_H__ - -#include "CTR_HashedPtr.h" -#include "SCA_IActuator.h" -#include "BL_ActionActuator.h" -#include "MT_Point3.h" -#include - -struct Key; -class BL_ShapeActionActuator : public SCA_IActuator -{ -public: - Py_Header - BL_ShapeActionActuator(SCA_IObject* gameobj, - const STR_String& propname, - const STR_String& framepropname, - float starttime, - float endtime, - struct bAction *action, - short playtype, - short blendin, - short priority, - float stride); - virtual ~BL_ShapeActionActuator(); - virtual bool Update(double curtime, bool frame); - virtual CValue* GetReplica(); - virtual void ProcessReplica(); - - void SetBlendTime (float newtime); - void BlendShape(struct Key* key, float weight); - - bAction* GetAction() { return m_action; } - void SetAction(bAction* act) { m_action= act; } - -#ifdef WITH_PYTHON - - static PyObject* pyattr_get_action(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_action(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - - static int CheckBlendTime(void *self, const PyAttributeDef*) - { - BL_ShapeActionActuator* act = reinterpret_cast(self); - - if (act->m_blendframe > act->m_blendin) - act->m_blendframe = act->m_blendin; - - return 0; - } - static int CheckFrame(void *self, const PyAttributeDef*) - { - BL_ShapeActionActuator* act = reinterpret_cast(self); - - if (act->m_localtime < act->m_startframe) - act->m_localtime = act->m_startframe; - else if (act->m_localtime > act->m_endframe) - act->m_localtime = act->m_endframe; - - return 0; - } - static int CheckType(void *self, const PyAttributeDef*) - { - BL_ShapeActionActuator* act = reinterpret_cast(self); - - switch (act->m_playtype) { - case ACT_ACTION_PLAY: - case ACT_ACTION_PINGPONG: - case ACT_ACTION_FLIPPER: - case ACT_ACTION_LOOP_STOP: - case ACT_ACTION_LOOP_END: - case ACT_ACTION_FROM_PROP: - return 0; - default: - PyErr_SetString(PyExc_ValueError, "Shape Action Actuator, invalid play type supplied"); - return 1; - } - - } - -#endif /* WITH_PYTHON */ - -protected: - - void SetStartTime(float curtime); - void SetLocalTime(float curtime); - bool ClampLocalTime(); - - MT_Point3 m_lastpos; - float m_blendframe; - int m_flag; - /** The frame this action starts */ - float m_startframe; - /** The frame this action ends */ - float m_endframe; - /** The time this action started */ - float m_starttime; - /** The current time of the action */ - float m_localtime; - - float m_lastUpdate; - float m_blendin; - float m_blendstart; - float m_stridelength; - short m_playtype; - short m_priority; - struct bAction *m_action; - STR_String m_framepropname; - STR_String m_propname; - vector m_blendshape; - struct PointerRNA *m_idptr; -}; - -#endif /* __BL_SHAPEACTIONACTUATOR_H__ */ diff --git a/source/gameengine/Converter/BL_ShapeDeformer.cpp b/source/gameengine/Converter/BL_ShapeDeformer.cpp deleted file mode 100644 index 94256a64d75..00000000000 --- a/source/gameengine/Converter/BL_ShapeDeformer.cpp +++ /dev/null @@ -1,237 +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/Converter/BL_ShapeDeformer.cpp - * \ingroup bgeconv - */ - -#ifdef _MSC_VER -# pragma warning (disable:4786) -#endif - -#include "MEM_guardedalloc.h" -#include "BL_ShapeDeformer.h" -#include "CTR_Map.h" -#include "STR_HashedString.h" -#include "RAS_IPolygonMaterial.h" -#include "RAS_MeshObject.h" - -#include "DNA_anim_types.h" -#include "DNA_armature_types.h" -#include "DNA_action_types.h" -#include "DNA_key_types.h" -#include "DNA_mesh_types.h" -#include "DNA_meshdata_types.h" -#include "BKE_armature.h" -#include "BKE_action.h" -#include "BKE_global.h" -#include "BKE_main.h" -#include "BKE_key.h" -#include "BKE_fcurve.h" -#include "BKE_ipo.h" -#include "BKE_library.h" -#include "MT_Point3.h" - -extern "C"{ - #include "BKE_lattice.h" - #include "BKE_animsys.h" -} - -#include "BLI_blenlib.h" -#include "BLI_math.h" - -#define __NLA_DEFNORMALS -//#undef __NLA_DEFNORMALS - -BL_ShapeDeformer::BL_ShapeDeformer(BL_DeformableGameObject *gameobj, - Object *bmeshobj, - RAS_MeshObject *mesh) - : - BL_SkinDeformer(gameobj,bmeshobj, mesh), - m_useShapeDrivers(false), - m_lastShapeUpdate(-1) -{ - m_key = m_bmesh->key ? BKE_key_copy(G.main, m_bmesh->key) : NULL; -}; - -/* this second constructor is needed for making a mesh deformable on the fly. */ -BL_ShapeDeformer::BL_ShapeDeformer(BL_DeformableGameObject *gameobj, - Object *bmeshobj_old, - Object *bmeshobj_new, - RAS_MeshObject *mesh, - bool release_object, - bool recalc_normal, - BL_ArmatureObject* arma) - : - BL_SkinDeformer(gameobj, bmeshobj_old, bmeshobj_new, mesh, release_object, recalc_normal, arma), - m_useShapeDrivers(false), - m_lastShapeUpdate(-1) -{ - m_key = m_bmesh->key ? BKE_key_copy(G.main, m_bmesh->key) : NULL; -}; - -BL_ShapeDeformer::~BL_ShapeDeformer() -{ - if (m_key) - { - BKE_libblock_free(G.main, m_key); - m_key = NULL; - } -}; - -RAS_Deformer *BL_ShapeDeformer::GetReplica() -{ - BL_ShapeDeformer *result; - - result = new BL_ShapeDeformer(*this); - result->ProcessReplica(); - return result; -} - -void BL_ShapeDeformer::ProcessReplica() -{ - BL_SkinDeformer::ProcessReplica(); - m_lastShapeUpdate = -1; - - m_key = m_key ? BKE_key_copy(G.main, m_key) : NULL; -} - -bool BL_ShapeDeformer::LoadShapeDrivers(KX_GameObject* parent) -{ - // Only load shape drivers if we have a key - if (GetKey() == NULL) { - m_useShapeDrivers = false; - return false; - } - - // Fix drivers since BL_ArmatureObject makes copies - if (parent->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE && GetKey()->adt) { - BL_ArmatureObject *arma = (BL_ArmatureObject*)parent; - FCurve *fcu; - - for (fcu = (FCurve*)GetKey()->adt->drivers.first; fcu; fcu = (FCurve*)fcu->next) { - - DriverVar *dvar; - for (dvar = (DriverVar*)fcu->driver->variables.first; dvar; dvar = (DriverVar*)dvar->next) { - DRIVER_TARGETS_USED_LOOPER(dvar) - { - if (dtar->id) { - if ((Object*)dtar->id == arma->GetOrigArmatureObject()) - dtar->id = (ID*)arma->GetArmatureObject(); - } - } - DRIVER_TARGETS_LOOPER_END - } - } - } - - // This used to check if we had drivers from this armature, - // now we just assume we want to use shape drivers - // and let the animsys handle things. - m_useShapeDrivers = true; - - return true; -} - -bool BL_ShapeDeformer::ExecuteShapeDrivers(void) -{ - if (m_useShapeDrivers && PoseUpdated()) { - // We don't need an actual time, just use 0 - BKE_animsys_evaluate_animdata(NULL, &GetKey()->id, GetKey()->adt, 0.f, ADT_RECALC_DRIVERS); - - ForceUpdate(); - m_bDynamic = true; - return true; - } - return false; -} - -bool BL_ShapeDeformer::Update(void) -{ - bool bShapeUpdate = false; - bool bSkinUpdate = false; - - ExecuteShapeDrivers(); - - /* See if the object shape has changed */ - if (m_lastShapeUpdate != m_gameobj->GetLastFrame()) { - /* the key coefficient have been set already, we just need to blend the keys */ - Object* blendobj = m_gameobj->GetBlendObject(); - - /* we will blend the key directly in m_transverts array: it is used by armature as the start position */ - /* m_key can be NULL in case of Modifier deformer */ - if (m_key) { - WeightsArrayCache cache = {0, NULL}; - float **per_keyblock_weights; - - /* store verts locally */ - VerifyStorage(); - - per_keyblock_weights = BKE_keyblock_get_per_block_weights(blendobj, m_key, &cache); - BKE_key_evaluate_relative(0, m_bmesh->totvert, m_bmesh->totvert, (char *)(float *)m_transverts, - m_key, NULL, per_keyblock_weights, 0); /* last arg is ignored */ - BKE_keyblock_free_per_block_weights(m_key, per_keyblock_weights, &cache); - - m_bDynamic = true; - } - - // Don't release the weight array as in Blender, it will most likely be reusable on next frame - // The weight array are ultimately deleted when the skin mesh is destroyed - - /* Update the current frame */ - m_lastShapeUpdate=m_gameobj->GetLastFrame(); - - // As we have changed, the mesh, the skin deformer must update as well. - // This will force the update - BL_SkinDeformer::ForceUpdate(); - bShapeUpdate = true; - } - // check for armature deform - bSkinUpdate = BL_SkinDeformer::UpdateInternal(bShapeUpdate && m_bDynamic); - - // non dynamic deformer = Modifer without armature and shape keys, no need to create storage - if (!bSkinUpdate && bShapeUpdate && m_bDynamic) { - // this means that there is no armature, we still need to - // update the normal (was not done after shape key calculation) - -#ifdef __NLA_DEFNORMALS - if (m_recalcNormal) - RecalcNormals(); -#endif - - // We also need to handle transverts now (used to be in BL_SkinDeformer::Apply()) - UpdateTransverts(); - bSkinUpdate = true; - } - - return bSkinUpdate; -} - -Key *BL_ShapeDeformer::GetKey() -{ - return m_key; -} diff --git a/source/gameengine/Converter/BL_ShapeDeformer.h b/source/gameengine/Converter/BL_ShapeDeformer.h deleted file mode 100644 index f6746dd2302..00000000000 --- a/source/gameengine/Converter/BL_ShapeDeformer.h +++ /dev/null @@ -1,86 +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 BL_ShapeDeformer.h - * \ingroup bgeconv - */ - -#ifndef __BL_SHAPEDEFORMER_H__ -#define __BL_SHAPEDEFORMER_H__ - -#ifdef _MSC_VER -# pragma warning (disable:4786) /* get rid of stupid stl-visual compiler debug warning */ -#endif - -#include "BL_SkinDeformer.h" -#include "BL_DeformableGameObject.h" -#include - -class BL_ShapeDeformer : public BL_SkinDeformer -{ -public: - BL_ShapeDeformer(BL_DeformableGameObject *gameobj, - Object *bmeshobj, - RAS_MeshObject *mesh); - - /* this second constructor is needed for making a mesh deformable on the fly. */ - BL_ShapeDeformer(BL_DeformableGameObject *gameobj, - struct Object *bmeshobj_old, - struct Object *bmeshobj_new, - class RAS_MeshObject *mesh, - bool release_object, - bool recalc_normal, - BL_ArmatureObject* arma = NULL); - - virtual RAS_Deformer *GetReplica(); - virtual void ProcessReplica(); - virtual ~BL_ShapeDeformer(); - - bool Update (void); - bool LoadShapeDrivers(KX_GameObject* parent); - bool ExecuteShapeDrivers(void); - - struct Key *GetKey(); - - void ForceUpdate() - { - m_lastShapeUpdate = -1.0; - }; - -protected: - bool m_useShapeDrivers; - double m_lastShapeUpdate; - struct Key* m_key; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_ShapeDeformer") -#endif -}; - -#endif - diff --git a/source/gameengine/Converter/BL_SkinDeformer.cpp b/source/gameengine/Converter/BL_SkinDeformer.cpp deleted file mode 100644 index 68da99f9fa5..00000000000 --- a/source/gameengine/Converter/BL_SkinDeformer.cpp +++ /dev/null @@ -1,384 +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/Converter/BL_SkinDeformer.cpp - * \ingroup bgeconv - */ - -#ifdef _MSC_VER -# pragma warning (disable:4786) -#endif - -// Eigen3 stuff used for BGEDeformVerts -#include -#include - -#include "BL_SkinDeformer.h" -#include "CTR_Map.h" -#include "STR_HashedString.h" -#include "RAS_IPolygonMaterial.h" -#include "RAS_MeshObject.h" - -//#include "BL_ArmatureController.h" -#include "DNA_armature_types.h" -#include "DNA_action_types.h" -#include "DNA_mesh_types.h" -#include "DNA_meshdata_types.h" -#include "DNA_modifier_types.h" -#include "BLI_utildefines.h" -#include "BKE_armature.h" -#include "BKE_action.h" -#include "MT_Point3.h" - -extern "C"{ - #include "BKE_lattice.h" - #include "BKE_deform.h" -} - - -#include "BLI_blenlib.h" -#include "BLI_math.h" - -#define __NLA_DEFNORMALS -//#undef __NLA_DEFNORMALS - -static short get_deformflags(struct Object *bmeshobj) -{ - short flags = ARM_DEF_VGROUP; - - ModifierData *md; - for (md = (ModifierData *)bmeshobj->modifiers.first; md; md = md->next) - { - if (md->type == eModifierType_Armature) - { - flags |= ((ArmatureModifierData*)md)->deformflag; - break; - } - } - - return flags; -} - -BL_SkinDeformer::BL_SkinDeformer(BL_DeformableGameObject *gameobj, - struct Object *bmeshobj, - class RAS_MeshObject *mesh, - BL_ArmatureObject* arma) - : // - BL_MeshDeformer(gameobj, bmeshobj, mesh), - m_armobj(arma), - m_lastArmaUpdate(-1), - //m_defbase(&bmeshobj->defbase), - m_releaseobject(false), - m_poseApplied(false), - m_recalcNormal(true), - m_copyNormals(false), - m_dfnrToPC(NULL) -{ - copy_m4_m4(m_obmat, bmeshobj->obmat); - m_deformflags = get_deformflags(bmeshobj); -}; - -BL_SkinDeformer::BL_SkinDeformer( - BL_DeformableGameObject *gameobj, - struct Object *bmeshobj_old, // Blender object that owns the new mesh - struct Object *bmeshobj_new, // Blender object that owns the original mesh - class RAS_MeshObject *mesh, - bool release_object, - bool recalc_normal, - BL_ArmatureObject* arma) : - BL_MeshDeformer(gameobj, bmeshobj_old, mesh), - m_armobj(arma), - m_lastArmaUpdate(-1), - //m_defbase(&bmeshobj_old->defbase), - m_releaseobject(release_object), - m_recalcNormal(recalc_normal), - m_copyNormals(false), - m_dfnrToPC(NULL) - { - // this is needed to ensure correct deformation of mesh: - // the deformation is done with Blender's armature_deform_verts() function - // that takes an object as parameter and not a mesh. The object matrice is used - // in the calculation, so we must use the matrix of the original object to - // simulate a pure replacement of the mesh. - copy_m4_m4(m_obmat, bmeshobj_new->obmat); - m_deformflags = get_deformflags(bmeshobj_new); - } - -BL_SkinDeformer::~BL_SkinDeformer() -{ - if (m_releaseobject && m_armobj) - m_armobj->Release(); - if (m_dfnrToPC) - delete [] m_dfnrToPC; -} - -void BL_SkinDeformer::Relink(CTR_Map*map) -{ - if (m_armobj) { - void **h_obj = (*map)[m_armobj]; - - if (h_obj) - m_armobj = (BL_ArmatureObject*)(*h_obj); - else - m_armobj=NULL; - } - - BL_MeshDeformer::Relink(map); -} - -bool BL_SkinDeformer::Apply(RAS_IPolyMaterial *mat) -{ - // We do everything in UpdateInternal() now so we can thread it. - // All that is left is telling the rasterizer if we've changed the mesh - bool retval = !m_poseApplied; - m_poseApplied = true; - return retval; -} - -RAS_Deformer *BL_SkinDeformer::GetReplica() -{ - BL_SkinDeformer *result; - - result = new BL_SkinDeformer(*this); - /* there is m_armobj that must be fixed but we cannot do it now, it will be done in Relink */ - result->ProcessReplica(); - return result; -} - -void BL_SkinDeformer::ProcessReplica() -{ - BL_MeshDeformer::ProcessReplica(); - m_lastArmaUpdate = -1; - m_releaseobject = false; - m_dfnrToPC = NULL; -} - -void BL_SkinDeformer::BlenderDeformVerts() -{ - float obmat[4][4]; // the original object matrix - Object* par_arma = m_armobj->GetArmatureObject(); - - // save matrix first - copy_m4_m4(obmat, m_objMesh->obmat); - // set reference matrix - copy_m4_m4(m_objMesh->obmat, m_obmat); - - armature_deform_verts( par_arma, m_objMesh, NULL, m_transverts, NULL, m_bmesh->totvert, m_deformflags, NULL, NULL ); - - // restore matrix - copy_m4_m4(m_objMesh->obmat, obmat); - -#ifdef __NLA_DEFNORMALS - if (m_recalcNormal) - RecalcNormals(); -#endif -} - -void BL_SkinDeformer::BGEDeformVerts() -{ - Object *par_arma = m_armobj->GetArmatureObject(); - MDeformVert *dverts = m_bmesh->dvert; - bDeformGroup *dg; - int defbase_tot; - Eigen::Matrix4f pre_mat, post_mat, chan_mat, norm_chan_mat; - - if (!dverts) - return; - - defbase_tot = BLI_listbase_count(&m_objMesh->defbase); - - if (m_dfnrToPC == NULL) - { - m_dfnrToPC = new bPoseChannel*[defbase_tot]; - int i; - for (i=0, dg=(bDeformGroup*)m_objMesh->defbase.first; - dg; - ++i, dg = dg->next) - { - m_dfnrToPC[i] = BKE_pose_channel_find_name(par_arma->pose, dg->name); - - if (m_dfnrToPC[i] && m_dfnrToPC[i]->bone->flag & BONE_NO_DEFORM) - m_dfnrToPC[i] = NULL; - } - } - - post_mat = Eigen::Matrix4f::Map((float*)m_obmat).inverse() * Eigen::Matrix4f::Map((float*)m_armobj->GetArmatureObject()->obmat); - pre_mat = post_mat.inverse(); - - MDeformVert *dv= dverts; - MDeformWeight *dw; - - for (int i=0; itotvert; ++i, dv++) - { - float contrib = 0.f, weight, max_weight=-1.f; - bPoseChannel *pchan=NULL; - Eigen::Map norm = Eigen::Vector3f::Map(m_transnors[i]); - Eigen::Vector4f vec(0, 0, 0, 1); - Eigen::Vector4f co(m_transverts[i][0], - m_transverts[i][1], - m_transverts[i][2], - 1.f); - - if (!dv->totweight) - continue; - - co = pre_mat * co; - - dw= dv->dw; - - for (unsigned int j= dv->totweight; j != 0; j--, dw++) - { - const int index = dw->def_nr; - - if (index < defbase_tot && (pchan=m_dfnrToPC[index])) - { - weight = dw->weight; - - if (weight) - { - chan_mat = Eigen::Matrix4f::Map((float*)pchan->chan_mat); - - // Update Vertex Position - vec.noalias() += (chan_mat*co - co)*weight; - - // Save the most influential channel so we can use it to update the vertex normal - if (weight > max_weight) - { - max_weight = weight; - norm_chan_mat = chan_mat; - } - - contrib += weight; - } - } - } - - // Update Vertex Normal - norm = norm_chan_mat.topLeftCorner<3, 3>()*norm; - - co.noalias() += vec/contrib; - co[3] = 1.f; // Make sure we have a 1 for the w component! - - co = post_mat * co; - - m_transverts[i][0] = co[0]; - m_transverts[i][1] = co[1]; - m_transverts[i][2] = co[2]; - } - m_copyNormals = true; -} - -void BL_SkinDeformer::UpdateTransverts() -{ - RAS_MeshSlot::iterator it; - RAS_MeshMaterial *mmat; - RAS_MeshSlot *slot; - size_t i, nmat, imat; - - if (m_transverts) { - // the vertex cache is unique to this deformer, no need to update it - // if it wasn't updated! We must update all the materials at once - // because we will not get here again for the other material - nmat = m_pMeshObject->NumMaterials(); - for (imat=0; imatGetMeshMaterial(imat); - if (!mmat->m_slots[(void*)m_gameobj]) - continue; - - slot = *mmat->m_slots[(void*)m_gameobj]; - - // for each array - for (slot->begin(it); !slot->end(it); slot->next(it)) { - // for each vertex - // copy the untransformed data from the original mvert - for (i=it.startvertex; itotvert; v++) - { - copy_v3_v3(m_transverts[v], m_bmesh->mvert[v].co); - normal_short_to_float_v3(m_transnors[v], m_bmesh->mvert[v].no); - } - } - - m_armobj->ApplyPose(); - - if (m_armobj->GetVertDeformType() == ARM_VDEF_BGE_CPU) - BGEDeformVerts(); - else - BlenderDeformVerts(); - - /* Update the current frame */ - m_lastArmaUpdate=m_armobj->GetLastFrame(); - - m_armobj->RestorePose(); - /* dynamic vertex, cannot use display list */ - m_bDynamic = true; - - UpdateTransverts(); - - m_poseApplied = false; - - /* indicate that the m_transverts and normals are up to date */ - return true; - } - - return false; -} - -bool BL_SkinDeformer::Update(void) -{ - return UpdateInternal(false); -} - -/* XXX note: I propose to drop this function */ -void BL_SkinDeformer::SetArmature(BL_ArmatureObject *armobj) -{ - // only used to set the object now - m_armobj = armobj; -} diff --git a/source/gameengine/Converter/BL_SkinDeformer.h b/source/gameengine/Converter/BL_SkinDeformer.h deleted file mode 100644 index 79043f60db8..00000000000 --- a/source/gameengine/Converter/BL_SkinDeformer.h +++ /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 BL_SkinDeformer.h - * \ingroup bgeconv - */ - -#ifndef __BL_SKINDEFORMER_H__ -#define __BL_SKINDEFORMER_H__ - -#ifdef _MSC_VER -# pragma warning (disable:4786) /* get rid of stupid stl-visual compiler debug warning */ -#endif /* WIN32 */ - -#include "CTR_HashedPtr.h" -#include "BL_MeshDeformer.h" -#include "BL_ArmatureObject.h" - -#include "DNA_mesh_types.h" -#include "DNA_meshdata_types.h" -#include "DNA_object_types.h" -#include "BKE_armature.h" - -#include "RAS_Deformer.h" - - -class BL_SkinDeformer : public BL_MeshDeformer -{ -public: -// void SetArmatureController (BL_ArmatureController *cont); - virtual void Relink(CTR_Map*map); - void SetArmature (class BL_ArmatureObject *armobj); - - BL_SkinDeformer(BL_DeformableGameObject *gameobj, - struct Object *bmeshobj, - class RAS_MeshObject *mesh, - BL_ArmatureObject* arma = NULL); - - /* this second constructor is needed for making a mesh deformable on the fly. */ - BL_SkinDeformer(BL_DeformableGameObject *gameobj, - struct Object *bmeshobj_old, - struct Object *bmeshobj_new, - class RAS_MeshObject *mesh, - bool release_object, - bool recalc_normal, - BL_ArmatureObject* arma = NULL); - - virtual RAS_Deformer *GetReplica(); - virtual void ProcessReplica(); - - virtual ~BL_SkinDeformer(); - bool Update (void); - bool UpdateInternal (bool shape_applied); - bool Apply (class RAS_IPolyMaterial *polymat); - bool UpdateBuckets(void) - { - // update the deformer and all the mesh slots; Apply() does it well, so just call it. - return Apply(NULL); - } - bool PoseUpdated(void) - { - if (m_armobj && m_lastArmaUpdate!=m_armobj->GetLastFrame()) { - return true; - } - return false; - } - - void ForceUpdate() - { - m_lastArmaUpdate = -1.0; - }; - virtual bool ShareVertexArray() - { - return false; - } - -protected: - BL_ArmatureObject* m_armobj; // Our parent object - float m_time; - double m_lastArmaUpdate; - //ListBase* m_defbase; - float m_obmat[4][4]; // the reference matrix for skeleton deform - bool m_releaseobject; - bool m_poseApplied; - bool m_recalcNormal; - bool m_copyNormals; // dirty flag so we know if Apply() needs to copy normal information (used for BGEDeformVerts()) - struct bPoseChannel** m_dfnrToPC; - short m_deformflags; - - void BlenderDeformVerts(); - void BGEDeformVerts(); - - void UpdateTransverts(); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_SkinDeformer") -#endif -}; - -#endif /* __BL_SKINDEFORMER_H__ */ diff --git a/source/gameengine/Converter/CMakeLists.txt b/source/gameengine/Converter/CMakeLists.txt deleted file mode 100644 index 7d6195e3c38..00000000000 --- a/source/gameengine/Converter/CMakeLists.txt +++ /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. -# -# 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 - . - ../BlenderRoutines - ../Expressions - ../GameLogic - ../Ketsji - ../Ketsji/KXNetwork - ../Network - ../Network/LoopBackNetwork - ../Physics/Bullet - ../Physics/Dummy - ../Physics/common - ../Rasterizer - ../Rasterizer/RAS_OpenGLRasterizer - ../SceneGraph - ../../blender - ../../blender/blenkernel - ../../blender/blenlib - ../../blender/blenloader - ../../blender/gpu - ../../blender/ikplugin - ../../blender/imbuf - ../../blender/makesdna - ../../blender/makesrna - ../../blender/windowmanager - ../../../intern/container - ../../../intern/guardedalloc - ../../../intern/string -) - -set(INC_SYS - ../../../intern/moto/include - ../../../extern/recastnavigation/Detour/Include - ${EIGEN3_INCLUDE_DIRS} - ${PTHREADS_INCLUDE_DIRS} - ${BOOST_INCLUDE_DIR} -) - -set(SRC - BL_ActionActuator.cpp - BL_ArmatureActuator.cpp - BL_ArmatureChannel.cpp - BL_ArmatureConstraint.cpp - BL_ArmatureObject.cpp - BL_BlenderDataConversion.cpp - BL_DeformableGameObject.cpp - BL_MeshDeformer.cpp - BL_ModifierDeformer.cpp - BL_ShapeActionActuator.cpp - BL_ShapeDeformer.cpp - BL_SkinDeformer.cpp - KX_BlenderScalarInterpolator.cpp - KX_BlenderSceneConverter.cpp - KX_ConvertActuators.cpp - KX_ConvertControllers.cpp - KX_ConvertProperties.cpp - KX_ConvertSensors.cpp - KX_LibLoadStatus.cpp - KX_SoftBodyDeformer.cpp - - BL_ActionActuator.h - BL_ArmatureActuator.h - BL_ArmatureChannel.h - BL_ArmatureConstraint.h - BL_ArmatureObject.h - BL_BlenderDataConversion.h - BL_DeformableGameObject.h - BL_MeshDeformer.h - BL_ModifierDeformer.h - BL_ShapeActionActuator.h - BL_ShapeDeformer.h - BL_SkinDeformer.h - KX_BlenderScalarInterpolator.h - KX_BlenderSceneConverter.h - KX_ConvertActuators.h - KX_ConvertControllers.h - KX_ConvertProperties.h - KX_ConvertSensors.h - KX_LibLoadStatus.h - KX_SoftBodyDeformer.h -) - -if(WITH_BULLET) - list(APPEND INC_SYS - ${BULLET_INCLUDE_DIRS} - ) - add_definitions(-DWITH_BULLET) -endif() - -if(WITH_AUDASPACE) - add_definitions(-DWITH_AUDASPACE) - - list(APPEND INC_SYS - ${AUDASPACE_C_INCLUDE_DIRS} - ) -endif() - -blender_add_lib(ge_converter "${SRC}" "${INC}" "${INC_SYS}") diff --git a/source/gameengine/Converter/KX_BlenderScalarInterpolator.cpp b/source/gameengine/Converter/KX_BlenderScalarInterpolator.cpp deleted file mode 100644 index 4d344cdf16a..00000000000 --- a/source/gameengine/Converter/KX_BlenderScalarInterpolator.cpp +++ /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 gameengine/Converter/KX_BlenderScalarInterpolator.cpp - * \ingroup bgeconv - */ - - -#include "KX_BlenderScalarInterpolator.h" - -#include - -extern "C" { -#include "DNA_action_types.h" -#include "DNA_anim_types.h" -#include "BKE_fcurve.h" -} - -float BL_ScalarInterpolator::GetValue(float currentTime) const -{ - // XXX 2.4x IPO_GetFloatValue(m_blender_adt, m_channel, currentTime); - return evaluate_fcurve(m_fcu, currentTime); -} - -BL_InterpolatorList::BL_InterpolatorList(bAction *action) -{ - if (action==NULL) - return; - - for (FCurve *fcu = (FCurve *)action->curves.first; fcu; fcu = fcu->next) { - if (fcu->rna_path) { - BL_ScalarInterpolator *new_ipo = new BL_ScalarInterpolator(fcu); - //assert(new_ipo); - push_back(new_ipo); - } - } -} - -BL_InterpolatorList::~BL_InterpolatorList() -{ - BL_InterpolatorList::iterator i; - for (i = begin(); !(i == end()); ++i) { - delete *i; - } -} - -KX_IScalarInterpolator *BL_InterpolatorList::GetScalarInterpolator(const char *rna_path, int array_index) -{ - for (BL_InterpolatorList::iterator i = begin(); (i != end()) ; i++ ) - { - FCurve *fcu= (static_cast(*i))->GetFCurve(); - if (array_index==fcu->array_index && strcmp(rna_path, fcu->rna_path)==0) - return *i; - } - return NULL; -} - diff --git a/source/gameengine/Converter/KX_BlenderScalarInterpolator.h b/source/gameengine/Converter/KX_BlenderScalarInterpolator.h deleted file mode 100644 index d828910233f..00000000000 --- a/source/gameengine/Converter/KX_BlenderScalarInterpolator.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): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file KX_BlenderScalarInterpolator.h - * \ingroup bgeconv - */ - -#ifndef __KX_BLENDERSCALARINTERPOLATOR_H__ -#define __KX_BLENDERSCALARINTERPOLATOR_H__ - -#include - -#include "KX_IScalarInterpolator.h" - -typedef unsigned short BL_IpoChannel; - -class BL_ScalarInterpolator : public KX_IScalarInterpolator { -public: - BL_ScalarInterpolator() {} // required for use in STL list - BL_ScalarInterpolator(struct FCurve* fcu) : - m_fcu(fcu) - {} - - virtual ~BL_ScalarInterpolator() {} - - virtual float GetValue(float currentTime) const; - struct FCurve *GetFCurve() { return m_fcu; } - -private: - struct FCurve *m_fcu; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_ScalarInterpolator") -#endif -}; - - -class BL_InterpolatorList : public std::vector { -public: - BL_InterpolatorList(struct bAction *action); - ~BL_InterpolatorList(); - - KX_IScalarInterpolator *GetScalarInterpolator(const char *rna_path, int array_index); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_InterpolatorList") -#endif -}; - -#endif /* __KX_BLENDERSCALARINTERPOLATOR_H__ */ diff --git a/source/gameengine/Converter/KX_BlenderSceneConverter.cpp b/source/gameengine/Converter/KX_BlenderSceneConverter.cpp deleted file mode 100644 index 08b569fa4c2..00000000000 --- a/source/gameengine/Converter/KX_BlenderSceneConverter.cpp +++ /dev/null @@ -1,1477 +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/Converter/KX_BlenderSceneConverter.cpp - * \ingroup bgeconv - */ - -#ifdef _MSC_VER -# pragma warning (disable:4786) /* suppress stl-MSVC debug info warning */ -#endif - -#include "KX_Scene.h" -#include "KX_GameObject.h" -#include "KX_IpoConvert.h" -#include "RAS_MeshObject.h" -#include "KX_PhysicsEngineEnums.h" -#include "PHY_IPhysicsEnvironment.h" -#include "KX_KetsjiEngine.h" -#include "KX_PythonInit.h" // So we can handle adding new text datablocks for Python to import -#include "BL_Material.h" -#include "BL_ActionActuator.h" -#include "KX_BlenderMaterial.h" - - -#include "BL_System.h" - -#include "DummyPhysicsEnvironment.h" - - -#ifdef WITH_BULLET -#include "CcdPhysicsEnvironment.h" -#endif - -#include "KX_LibLoadStatus.h" -#include "KX_BlenderScalarInterpolator.h" -#include "BL_BlenderDataConversion.h" -#include "KX_WorldInfo.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 "BKE_main.h" -#include "BKE_fcurve.h" - -#include "BLI_math.h" - -extern "C" -{ -#include "DNA_object_types.h" -#include "DNA_curve_types.h" -#include "DNA_mesh_types.h" -#include "DNA_material_types.h" -#include "BLI_blenlib.h" -#include "MEM_guardedalloc.h" -#include "BKE_global.h" -#include "BKE_animsys.h" -#include "BKE_library.h" -#include "BKE_material.h" // BKE_material_copy -#include "BKE_mesh.h" // BKE_mesh_copy -#include "DNA_space_types.h" -#include "DNA_anim_types.h" -#include "DNA_action_types.h" -#include "RNA_define.h" -#include "../../blender/editors/include/ED_keyframing.h" -} - -/* Only for dynamic loading and merging */ -#include "RAS_BucketManager.h" // XXX cant stay -#include "KX_BlenderSceneConverter.h" -#include "KX_MeshProxy.h" -extern "C" { - #include "PIL_time.h" - #include "BKE_context.h" - #include "BLO_readfile.h" - #include "BKE_idcode.h" - #include "BKE_report.h" - #include "DNA_space_types.h" - #include "DNA_windowmanager_types.h" /* report api */ - #include "../../blender/blenlib/BLI_linklist.h" -} - -#include "BLI_task.h" - -// This is used to avoid including BLI_task.h in KX_BlenderSceneConverter.h -typedef struct ThreadInfo { - TaskPool *m_pool; - ThreadMutex m_mutex; -} ThreadInfo; - -KX_BlenderSceneConverter::KX_BlenderSceneConverter( - Main *maggie, - KX_KetsjiEngine *engine) - :m_maggie(maggie), - m_ketsjiEngine(engine), - m_alwaysUseExpandFraming(false), - m_usemat(false), - m_useglslmat(false), - m_use_mat_cache(true) -{ - BKE_main_id_tag_all(maggie, LIB_TAG_DOIT, false); /* avoid re-tagging later on */ - m_newfilename = ""; - m_threadinfo = new ThreadInfo(); - m_threadinfo->m_pool = BLI_task_pool_create(engine->GetTaskScheduler(), NULL); - BLI_mutex_init(&m_threadinfo->m_mutex); -} - -KX_BlenderSceneConverter::~KX_BlenderSceneConverter() -{ - // clears meshes, and hashmaps from blender to gameengine data - // delete sumoshapes - - int numAdtLists = m_map_blender_to_gameAdtList.size(); - for (int i = 0; i < numAdtLists; i++) { - BL_InterpolatorList *adtList = *m_map_blender_to_gameAdtList.at(i); - - delete (adtList); - } - - vector >::iterator itw = m_worldinfos.begin(); - while (itw != m_worldinfos.end()) { - delete itw->second; - itw++; - } - m_worldinfos.clear(); - - vector >::iterator itp = m_polymaterials.begin(); - while (itp != m_polymaterials.end()) { - delete itp->second; - itp++; - } - m_polymaterials.clear(); - - // delete after RAS_IPolyMaterial - vector >::iterator itmat = m_materials.begin(); - while (itmat != m_materials.end()) { - delete itmat->second; - itmat++; - } - m_materials.clear(); - - vector >::iterator itm = m_meshobjects.begin(); - while (itm != m_meshobjects.end()) { - delete itm->second; - itm++; - } - m_meshobjects.clear(); - - /* free any data that was dynamically loaded */ - while (m_DynamicMaggie.size() != 0) { - FreeBlendFile(m_DynamicMaggie[0]); - } - - m_DynamicMaggie.clear(); - - if (m_threadinfo) { - /* Thread infos like mutex must be freed after FreeBlendFile function. - Because it needs to lock the mutex, even if there's no active task when it's - in the scene converter destructor. */ - BLI_task_pool_free(m_threadinfo->m_pool); - BLI_mutex_end(&m_threadinfo->m_mutex); - delete m_threadinfo; - } -} - -void KX_BlenderSceneConverter::SetNewFileName(const STR_String &filename) -{ - m_newfilename = filename; -} - -bool KX_BlenderSceneConverter::TryAndLoadNewFile() -{ - bool result = false; - - return result; -} - -Scene *KX_BlenderSceneConverter::GetBlenderSceneForName(const STR_String &name) -{ - Scene *sce; - - /** - * Find the specified scene by name, or NULL if nothing matches. - */ - if ((sce = (Scene *)BLI_findstring(&m_maggie->scene, name.ReadPtr(), offsetof(ID, name) + 2))) - return sce; - - for (vector
::iterator it=m_DynamicMaggie.begin(); !(it == m_DynamicMaggie.end()); it++) { - Main *main = *it; - - if ((sce= (Scene *)BLI_findstring(&main->scene, name.ReadPtr(), offsetof(ID, name) + 2))) - return sce; - } - - return NULL; -} - -void KX_BlenderSceneConverter::ConvertScene(KX_Scene *destinationscene, RAS_IRasterizer *rendertools, - RAS_ICanvas *canvas, bool libloading) -{ - //find out which physics engine - Scene *blenderscene = destinationscene->GetBlenderScene(); - - PHY_IPhysicsEnvironment *phy_env = NULL; - - e_PhysicsEngine physics_engine = UseBullet; - // hook for registration function during conversion. - m_currentScene = destinationscene; - destinationscene->SetSceneConverter(this); - - // This doesn't really seem to do anything except cause potential issues - // when doing threaded conversion, so it's disabled for now. - // SG_SetActiveStage(SG_STAGE_CONVERTER); - - switch (blenderscene->gm.physicsEngine) { -#ifdef WITH_BULLET - case WOPHY_BULLET: - { - SYS_SystemHandle syshandle = SYS_GetSystem(); /*unused*/ - int visualizePhysics = SYS_GetCommandLineInt(syshandle, "show_physics", 0); - - phy_env = CcdPhysicsEnvironment::Create(blenderscene, visualizePhysics); - physics_engine = UseBullet; - break; - } -#endif - default: - case WOPHY_NONE: - { - // We should probably use some sort of factory here - phy_env = new DummyPhysicsEnvironment(); - physics_engine = UseNone; - break; - } - } - - destinationscene->SetPhysicsEnvironment(phy_env); - - BL_ConvertBlenderObjects( - m_maggie, - destinationscene, - m_ketsjiEngine, - physics_engine, - rendertools, - canvas, - this, - m_alwaysUseExpandFraming, - libloading); - - //These lookup are not needed during game - m_map_blender_to_gameactuator.clear(); - m_map_blender_to_gamecontroller.clear(); - m_map_blender_to_gameobject.clear(); - - //Clearing this lookup table has the effect of disabling the cache of meshes - //between scenes, even if they are shared in the blend file. - //This cache mecanism is buggy so I leave it disable and the memory leak - //that would result from this is fixed in RemoveScene() - m_map_mesh_to_gamemesh.clear(); -} - -// This function removes all entities stored in the converter for that scene -// It should be used instead of direct delete scene -// Note that there was some provision for sharing entities (meshes...) between -// scenes but that is now disabled so all scene will have their own copy -// and we can delete them here. If the sharing is reactivated, change this code too.. -// (see KX_BlenderSceneConverter::ConvertScene) -void KX_BlenderSceneConverter::RemoveScene(KX_Scene *scene) -{ - int i, size; - // delete the scene first as it will stop the use of entities - delete scene; - // delete the entities of this scene - vector >::iterator worldit; - size = m_worldinfos.size(); - for (i = 0, worldit = m_worldinfos.begin(); i < size; ) { - if (worldit->first == scene) { - delete worldit->second; - *worldit = m_worldinfos.back(); - m_worldinfos.pop_back(); - size--; - } - else { - i++; - worldit++; - } - } - - vector >::iterator polymit; - size = m_polymaterials.size(); - for (i = 0, polymit = m_polymaterials.begin(); i < size; ) { - if (polymit->first == scene) { - m_polymat_cache[scene].erase(polymit->second->GetBlenderMaterial()); - delete polymit->second; - *polymit = m_polymaterials.back(); - m_polymaterials.pop_back(); - size--; - } - else { - i++; - polymit++; - } - } - - m_polymat_cache.erase(scene); - - vector >::iterator matit; - size = m_materials.size(); - for (i = 0, matit = m_materials.begin(); i < size; ) { - if (matit->first == scene) { - m_mat_cache[scene].erase(matit->second->material); - delete matit->second; - *matit = m_materials.back(); - m_materials.pop_back(); - size--; - } - else { - i++; - matit++; - } - } - - m_mat_cache.erase(scene); - - vector >::iterator meshit; - size = m_meshobjects.size(); - for (i = 0, meshit = m_meshobjects.begin(); i < size; ) { - if (meshit->first == scene) { - delete meshit->second; - *meshit = m_meshobjects.back(); - m_meshobjects.pop_back(); - size--; - } - else { - i++; - meshit++; - } - } -} - -// use blender materials -void KX_BlenderSceneConverter::SetMaterials(bool val) -{ - m_usemat = val; - m_useglslmat = false; -} - -void KX_BlenderSceneConverter::SetGLSLMaterials(bool val) -{ - m_usemat = val; - m_useglslmat = val; -} - -void KX_BlenderSceneConverter::SetCacheMaterials(bool val) -{ - m_use_mat_cache = val; -} - -bool KX_BlenderSceneConverter::GetMaterials() -{ - return m_usemat; -} - -bool KX_BlenderSceneConverter::GetGLSLMaterials() -{ - return m_useglslmat; -} - -bool KX_BlenderSceneConverter::GetCacheMaterials() -{ - return m_use_mat_cache; -} - -void KX_BlenderSceneConverter::RegisterBlenderMaterial(BL_Material *mat) -{ - // First make sure we don't register the material twice - vector >::iterator it; - for (it = m_materials.begin(); it != m_materials.end(); ++it) - if (it->second == mat) - return; - - m_materials.push_back(pair (m_currentScene, mat)); -} - -void KX_BlenderSceneConverter::SetAlwaysUseExpandFraming(bool to_what) -{ - m_alwaysUseExpandFraming= to_what; -} - -void KX_BlenderSceneConverter::RegisterGameObject(KX_GameObject *gameobject, Object *for_blenderobject) -{ - /* only maintained while converting, freed during game runtime */ - m_map_blender_to_gameobject.insert(CHashedPtr(for_blenderobject), gameobject); -} - -/* only need to run this during conversion since - * m_map_blender_to_gameobject is freed after conversion */ -void KX_BlenderSceneConverter::UnregisterGameObject(KX_GameObject *gameobject) -{ - Object *bobp = gameobject->GetBlenderObject(); - if (bobp) { - CHashedPtr bptr(bobp); - KX_GameObject **gobp = m_map_blender_to_gameobject[bptr]; - if (gobp && *gobp == gameobject) { - // also maintain m_map_blender_to_gameobject if the gameobject - // being removed is matching the blender object - m_map_blender_to_gameobject.remove(bptr); - } - } -} - -KX_GameObject *KX_BlenderSceneConverter::FindGameObject(Object *for_blenderobject) -{ - KX_GameObject **obp = m_map_blender_to_gameobject[CHashedPtr(for_blenderobject)]; - - return obp ? *obp : NULL; -} - -void KX_BlenderSceneConverter::RegisterGameMesh(RAS_MeshObject *gamemesh, Mesh *for_blendermesh) -{ - if (for_blendermesh) { /* dynamically loaded meshes we don't want to keep lookups for */ - m_map_mesh_to_gamemesh.insert(CHashedPtr(for_blendermesh),gamemesh); - } - m_meshobjects.push_back(pair (m_currentScene,gamemesh)); -} - -RAS_MeshObject *KX_BlenderSceneConverter::FindGameMesh(Mesh *for_blendermesh) -{ - RAS_MeshObject **meshp = m_map_mesh_to_gamemesh[CHashedPtr(for_blendermesh)]; - - if (meshp) { - return *meshp; - } - else { - return NULL; - } -} - -void KX_BlenderSceneConverter::RegisterPolyMaterial(RAS_IPolyMaterial *polymat) -{ - // First make sure we don't register the material twice - vector >::iterator it; - for (it = m_polymaterials.begin(); it != m_polymaterials.end(); ++it) - if (it->second == polymat) - return; - m_polymaterials.push_back(pair (m_currentScene, polymat)); -} - -void KX_BlenderSceneConverter::CachePolyMaterial(KX_Scene *scene, Material *mat, RAS_IPolyMaterial *polymat) -{ - if (m_use_mat_cache && mat) - m_polymat_cache[scene][mat] = polymat; -} - -RAS_IPolyMaterial *KX_BlenderSceneConverter::FindCachedPolyMaterial(KX_Scene *scene, Material *mat) -{ - return (m_use_mat_cache) ? m_polymat_cache[scene][mat] : NULL; -} - -void KX_BlenderSceneConverter::CacheBlenderMaterial(KX_Scene *scene, Material *mat, BL_Material *blmat) -{ - if (m_use_mat_cache && mat) - m_mat_cache[scene][mat] = blmat; -} - -BL_Material *KX_BlenderSceneConverter::FindCachedBlenderMaterial(KX_Scene *scene, Material *mat) -{ - return (m_use_mat_cache) ? m_mat_cache[scene][mat] : NULL; -} - -void KX_BlenderSceneConverter::RegisterInterpolatorList(BL_InterpolatorList *actList, bAction *for_act) -{ - m_map_blender_to_gameAdtList.insert(CHashedPtr(for_act), actList); -} - -BL_InterpolatorList *KX_BlenderSceneConverter::FindInterpolatorList(bAction *for_act) -{ - BL_InterpolatorList **listp = m_map_blender_to_gameAdtList[CHashedPtr(for_act)]; - return listp ? *listp : NULL; -} - -void KX_BlenderSceneConverter::RegisterGameActuator(SCA_IActuator *act, bActuator *for_actuator) -{ - m_map_blender_to_gameactuator.insert(CHashedPtr(for_actuator), act); -} - -SCA_IActuator *KX_BlenderSceneConverter::FindGameActuator(bActuator *for_actuator) -{ - SCA_IActuator **actp = m_map_blender_to_gameactuator[CHashedPtr(for_actuator)]; - return actp ? *actp : NULL; -} - -void KX_BlenderSceneConverter::RegisterGameController(SCA_IController *cont, bController *for_controller) -{ - m_map_blender_to_gamecontroller.insert(CHashedPtr(for_controller), cont); -} - -SCA_IController *KX_BlenderSceneConverter::FindGameController(bController *for_controller) -{ - SCA_IController **contp = m_map_blender_to_gamecontroller[CHashedPtr(for_controller)]; - return contp ? *contp : NULL; -} - -void KX_BlenderSceneConverter::RegisterWorldInfo(KX_WorldInfo *worldinfo) -{ - m_worldinfos.push_back(pair (m_currentScene, worldinfo)); -} - -void KX_BlenderSceneConverter::ResetPhysicsObjectsAnimationIpo(bool clearIpo) -{ - //TODO this entire function is deprecated, written for 2.4x - //the functionality should be rewritten, currently it does nothing - - KX_SceneList *scenes = m_ketsjiEngine->CurrentScenes(); - int numScenes = scenes->size(); - int i; - for (i = 0; i < numScenes; i++) { - KX_Scene *scene = scenes->at(i); - CListValue *parentList = scene->GetRootParentList(); - int numObjects = parentList->GetCount(); - int g; - for (g = 0; g < numObjects; g++) { - KX_GameObject *gameObj = (KX_GameObject *)parentList->GetValue(g); - if (gameObj->IsRecordAnimation()) { - Object *blenderObject = gameObj->GetBlenderObject(); - if (blenderObject) { -#if 0 - //erase existing ipo's - Ipo* ipo = blenderObject->ipo;//findIpoForName(blenderObject->id.name+2); - if (ipo) { //clear the curve data - if (clearIpo) {//rcruiz - IpoCurve *icu1; - - int numCurves = 0; - for ( icu1 = (IpoCurve*)ipo->curve.first; icu1; ) { - - IpoCurve* tmpicu = icu1; - - /*int i; - BezTriple *bezt; - for ( bezt = tmpicu->bezt, i = 0; i < tmpicu->totvert; i++, bezt++) { - printf("(%f,%f,%f),(%f,%f,%f),(%f,%f,%f)\n",bezt->vec[0][0],bezt->vec[0][1],bezt->vec[0][2],bezt->vec[1][0],bezt->vec[1][1],bezt->vec[1][2],bezt->vec[2][0],bezt->vec[2][1],bezt->vec[2][2]); - }*/ - - icu1 = icu1->next; - numCurves++; - - BLI_remlink( &( blenderObject->ipo->curve ), tmpicu ); - if ( tmpicu->bezt ) - MEM_freeN( tmpicu->bezt ); - MEM_freeN( tmpicu ); - localDel_ipoCurve( tmpicu ); - } - } - } - else { - ipo = NULL; // XXX add_ipo(blenderObject->id.name+2, ID_OB); - blenderObject->ipo = ipo; - } -#endif - } - } - } - } -} - -void KX_BlenderSceneConverter::resetNoneDynamicObjectToIpo() -{ - //TODO the functionality should be rewritten -} - -// this generates ipo curves for position, rotation, allowing to use game physics in animation -void KX_BlenderSceneConverter::WritePhysicsObjectToAnimationIpo(int frameNumber) -{ - KX_SceneList *scenes = m_ketsjiEngine->CurrentScenes(); - int numScenes = scenes->size(); - int i; - for (i = 0; i < numScenes; i++) { - KX_Scene *scene = scenes->at(i); - //PHY_IPhysicsEnvironment* physEnv = scene->GetPhysicsEnvironment(); - CListValue *parentList = scene->GetObjectList(); - int numObjects = parentList->GetCount(); - int g; - for (g = 0; g < numObjects; g++) { - KX_GameObject *gameObj = (KX_GameObject *)parentList->GetValue(g); - Object *blenderObject = gameObj->GetBlenderObject(); - if (blenderObject && blenderObject->parent == NULL && gameObj->IsRecordAnimation()) { - if (blenderObject->adt == NULL) - BKE_animdata_add_id(&blenderObject->id); - - if (blenderObject->adt) { - const MT_Point3 &position = gameObj->NodeGetWorldPosition(); - //const MT_Vector3& scale = gameObj->NodeGetWorldScaling(); - const MT_Matrix3x3 &orn = gameObj->NodeGetWorldOrientation(); - - position.getValue(blenderObject->loc); - - float tmat[3][3]; - for (int r = 0; r < 3; r++) - for (int c = 0; c < 3; c++) - tmat[r][c] = (float)orn[c][r]; - - mat3_to_compatible_eul(blenderObject->rot, blenderObject->rot, tmat); - - insert_keyframe(NULL, &blenderObject->id, NULL, NULL, "location", -1, (float)frameNumber, BEZT_KEYTYPE_JITTER, INSERTKEY_FAST); - insert_keyframe(NULL, &blenderObject->id, NULL, NULL, "rotation_euler", -1, (float)frameNumber, BEZT_KEYTYPE_JITTER, INSERTKEY_FAST); - -#if 0 - const MT_Point3& position = gameObj->NodeGetWorldPosition(); - //const MT_Vector3& scale = gameObj->NodeGetWorldScaling(); - const MT_Matrix3x3& orn = gameObj->NodeGetWorldOrientation(); - - float eulerAngles[3]; - float eulerAnglesOld[3] = {0.0f, 0.0f, 0.0f}; - float tmat[3][3]; - - // XXX animato - Ipo* ipo = blenderObject->ipo; - - //create the curves, if not existing, set linear if new - - IpoCurve *icu_lx = findIpoCurve((IpoCurve *)ipo->curve.first,"LocX"); - if (!icu_lx) { - icu_lx = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_X, 1); - if (icu_lx) icu_lx->ipo = IPO_LIN; - } - IpoCurve *icu_ly = findIpoCurve((IpoCurve *)ipo->curve.first,"LocY"); - if (!icu_ly) { - icu_ly = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_Y, 1); - if (icu_ly) icu_ly->ipo = IPO_LIN; - } - IpoCurve *icu_lz = findIpoCurve((IpoCurve *)ipo->curve.first,"LocZ"); - if (!icu_lz) { - icu_lz = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_Z, 1); - if (icu_lz) icu_lz->ipo = IPO_LIN; - } - IpoCurve *icu_rx = findIpoCurve((IpoCurve *)ipo->curve.first,"RotX"); - if (!icu_rx) { - icu_rx = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_X, 1); - if (icu_rx) icu_rx->ipo = IPO_LIN; - } - IpoCurve *icu_ry = findIpoCurve((IpoCurve *)ipo->curve.first,"RotY"); - if (!icu_ry) { - icu_ry = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_Y, 1); - if (icu_ry) icu_ry->ipo = IPO_LIN; - } - IpoCurve *icu_rz = findIpoCurve((IpoCurve *)ipo->curve.first,"RotZ"); - if (!icu_rz) { - icu_rz = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_Z, 1); - if (icu_rz) icu_rz->ipo = IPO_LIN; - } - - if (icu_rx) eulerAnglesOld[0] = eval_icu( icu_rx, frameNumber - 1 ) / ((180 / 3.14159265f) / 10); - if (icu_ry) eulerAnglesOld[1] = eval_icu( icu_ry, frameNumber - 1 ) / ((180 / 3.14159265f) / 10); - if (icu_rz) eulerAnglesOld[2] = eval_icu( icu_rz, frameNumber - 1 ) / ((180 / 3.14159265f) / 10); - - // orn.getValue((float *)tmat); // uses the wrong ordering, cant use this - for (int r = 0; r < 3; r++) - for (int c = 0; c < 3; c++) - tmat[r][c] = orn[c][r]; - - // mat3_to_eul( eulerAngles,tmat); // better to use Mat3ToCompatibleEul - mat3_to_compatible_eul( eulerAngles, eulerAnglesOld,tmat); - - //eval_icu - for (int x = 0; x < 3; x++) - eulerAngles[x] *= (float) ((180 / 3.14159265f) / 10.0); - - //fill the curves with data - if (icu_lx) insert_vert_icu(icu_lx, frameNumber, position.x(), 1); - if (icu_ly) insert_vert_icu(icu_ly, frameNumber, position.y(), 1); - if (icu_lz) insert_vert_icu(icu_lz, frameNumber, position.z(), 1); - if (icu_rx) insert_vert_icu(icu_rx, frameNumber, eulerAngles[0], 1); - if (icu_ry) insert_vert_icu(icu_ry, frameNumber, eulerAngles[1], 1); - if (icu_rz) insert_vert_icu(icu_rz, frameNumber, eulerAngles[2], 1); - - // Handles are corrected at the end, testhandles_ipocurve isn't needed yet -#endif - } - } - } - } -} - -void KX_BlenderSceneConverter::TestHandlesPhysicsObjectToAnimationIpo() -{ - KX_SceneList *scenes = m_ketsjiEngine->CurrentScenes(); - int numScenes = scenes->size(); - int i; - for (i = 0; i < numScenes; i++) { - KX_Scene *scene = scenes->at(i); - //PHY_IPhysicsEnvironment* physEnv = scene->GetPhysicsEnvironment(); - CListValue *parentList = scene->GetRootParentList(); - int numObjects = parentList->GetCount(); - int g; - for (g = 0; g < numObjects; g++) { - KX_GameObject *gameObj = (KX_GameObject *)parentList->GetValue(g); - if (gameObj->IsRecordAnimation()) { - Object *blenderObject = gameObj->GetBlenderObject(); - if (blenderObject && blenderObject->adt) { - bAction *act = verify_adt_action(&blenderObject->id, false); - FCurve *fcu; - - if (!act) { - continue; - } - - /* for now, not much choice but to run this on all curves... */ - for (fcu = (FCurve *)act->curves.first; fcu; fcu = fcu->next) { - /* Note: calling `sort_time_fcurve()` here is not needed, since - * all keys have been added in 'right' order. */ - calchandles_fcurve(fcu); - } -#if 0 - // XXX animato - Ipo* ipo = blenderObject->ipo; - - //create the curves, if not existing - //testhandles_ipocurve checks for NULL - testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"LocX")); - testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"LocY")); - testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"LocZ")); - testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"RotX")); - testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"RotY")); - testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"RotZ")); -#endif - } - } - } - } -} - -#ifdef WITH_PYTHON -PyObject *KX_BlenderSceneConverter::GetPyNamespace() -{ - return m_ketsjiEngine->GetPyNamespace(); -} -#endif - -vector
&KX_BlenderSceneConverter::GetMainDynamic() -{ - return m_DynamicMaggie; -} - -Main *KX_BlenderSceneConverter::GetMainDynamicPath(const char *path) -{ - for (vector
::iterator it = m_DynamicMaggie.begin(); !(it == m_DynamicMaggie.end()); it++) - if (BLI_path_cmp((*it)->name, path) == 0) - return *it; - - return NULL; -} - -void KX_BlenderSceneConverter::MergeAsyncLoads() -{ - vector *merge_scenes; - - vector::iterator mit; - vector::iterator sit; - - BLI_mutex_lock(&m_threadinfo->m_mutex); - - for (mit = m_mergequeue.begin(); mit != m_mergequeue.end(); ++mit) { - merge_scenes = (vector *)(*mit)->GetData(); - - for (sit=merge_scenes->begin(); sit!=merge_scenes->end(); ++sit) { - (*mit)->GetMergeScene()->MergeScene(*sit); - delete (*sit); - } - - delete merge_scenes; - (*mit)->SetData(NULL); - - (*mit)->Finish(); - } - - m_mergequeue.clear(); - - BLI_mutex_unlock(&m_threadinfo->m_mutex); -} - -void KX_BlenderSceneConverter::FinalizeAsyncLoads() -{ - // Finish all loading libraries. - if (m_threadinfo) { - BLI_task_pool_work_and_wait(m_threadinfo->m_pool); - } - // Merge all libraries data in the current scene, to avoid memory leak of unmerged scenes. - MergeAsyncLoads(); -} - -void KX_BlenderSceneConverter::AddScenesToMergeQueue(KX_LibLoadStatus *status) -{ - BLI_mutex_lock(&m_threadinfo->m_mutex); - m_mergequeue.push_back(status); - BLI_mutex_unlock(&m_threadinfo->m_mutex); -} - -static void async_convert(TaskPool *pool, void *ptr, int UNUSED(threadid)) -{ - KX_Scene *new_scene = NULL; - KX_LibLoadStatus *status = (KX_LibLoadStatus *)ptr; - vector *scenes = (vector *)status->GetData(); - vector *merge_scenes = new vector(); // Deleted in MergeAsyncLoads - - for (unsigned int i = 0; i < scenes->size(); ++i) { - new_scene = status->GetEngine()->CreateScene((*scenes)[i], true); - - if (new_scene) - merge_scenes->push_back(new_scene); - - status->AddProgress((1.0f / scenes->size()) * 0.9f); // We'll call conversion 90% and merging 10% for now - } - - delete scenes; - status->SetData(merge_scenes); - - status->GetConverter()->AddScenesToMergeQueue(status); -} - -KX_LibLoadStatus *KX_BlenderSceneConverter::LinkBlendFileMemory(void *data, int length, const char *path, char *group, KX_Scene *scene_merge, char **err_str, short options) -{ - BlendHandle *bpy_openlib = BLO_blendhandle_from_memory(data, length); - - // Error checking is done in LinkBlendFile - return LinkBlendFile(bpy_openlib, path, group, scene_merge, err_str, options); -} - -KX_LibLoadStatus *KX_BlenderSceneConverter::LinkBlendFilePath(const char *filepath, char *group, KX_Scene *scene_merge, char **err_str, short options) -{ - BlendHandle *bpy_openlib = BLO_blendhandle_from_file(filepath, NULL); - - // Error checking is done in LinkBlendFile - return LinkBlendFile(bpy_openlib, filepath, group, scene_merge, err_str, options); -} - -static void load_datablocks(Main *main_tmp, BlendHandle *bpy_openlib, const char *path, int idcode) -{ - LinkNode *names = NULL; - - int totnames_dummy; - names = BLO_blendhandle_get_datablock_names(bpy_openlib, idcode, &totnames_dummy); - - int i = 0; - LinkNode *n = names; - while (n) { - BLO_library_link_named_part(main_tmp, &bpy_openlib, idcode, (char *)n->link); - n = (LinkNode *)n->next; - i++; - } - BLI_linklist_free(names, free); /* free linklist *and* each node's data */ -} - -KX_LibLoadStatus *KX_BlenderSceneConverter::LinkBlendFile(BlendHandle *bpy_openlib, const char *path, char *group, KX_Scene *scene_merge, char **err_str, short options) -{ - Main *main_newlib; /* stored as a dynamic 'main' until we free it */ - const int idcode = BKE_idcode_from_name(group); - ReportList reports; - static char err_local[255]; - -// TIMEIT_START(bge_link_blend_file); - - KX_LibLoadStatus *status; - - /* only scene and mesh supported right now */ - if (idcode != ID_SCE && idcode != ID_ME && idcode != ID_AC) { - snprintf(err_local, sizeof(err_local), "invalid ID type given \"%s\"\n", group); - *err_str = err_local; - BLO_blendhandle_close(bpy_openlib); - return NULL; - } - - if (GetMainDynamicPath(path)) { - snprintf(err_local, sizeof(err_local), "blend file already open \"%s\"\n", path); - *err_str = err_local; - BLO_blendhandle_close(bpy_openlib); - return NULL; - } - - if (bpy_openlib == NULL) { - snprintf(err_local, sizeof(err_local), "could not open blendfile \"%s\"\n", path); - *err_str = err_local; - return NULL; - } - - main_newlib = BKE_main_new(); - BKE_reports_init(&reports, RPT_STORE); - - short flag = 0; /* don't need any special options */ - /* created only for linking, then freed */ - Main *main_tmp = BLO_library_link_begin(main_newlib, &bpy_openlib, (char *)path); - - load_datablocks(main_tmp, bpy_openlib, path, idcode); - - if (idcode == ID_SCE && options & LIB_LOAD_LOAD_SCRIPTS) { - load_datablocks(main_tmp, bpy_openlib, path, ID_TXT); - } - - /* now do another round of linking for Scenes so all actions are properly loaded */ - if (idcode == ID_SCE && options & LIB_LOAD_LOAD_ACTIONS) { - load_datablocks(main_tmp, bpy_openlib, path, ID_AC); - } - - BLO_library_link_end(main_tmp, &bpy_openlib, flag, NULL, NULL); - - BLO_blendhandle_close(bpy_openlib); - - BKE_reports_clear(&reports); - /* done linking */ - - /* needed for lookups*/ - GetMainDynamic().push_back(main_newlib); - BLI_strncpy(main_newlib->name, path, sizeof(main_newlib->name)); - - - status = new KX_LibLoadStatus(this, m_ketsjiEngine, scene_merge, path); - - if (idcode == ID_ME) { - /* Convert all new meshes into BGE meshes */ - ID *mesh; - - for (mesh = (ID *)main_newlib->mesh.first; mesh; mesh = (ID *)mesh->next ) { - if (options & LIB_LOAD_VERBOSE) - printf("MeshName: %s\n", mesh->name + 2); - RAS_MeshObject *meshobj = BL_ConvertMesh((Mesh *)mesh, NULL, scene_merge, this, false); // For now only use the libloading option for scenes, which need to handle materials/shaders - scene_merge->GetLogicManager()->RegisterMeshName(meshobj->GetName(), meshobj); - } - } - else if (idcode == ID_AC) { - /* Convert all actions */ - ID *action; - - for (action= (ID *)main_newlib->action.first; action; action = (ID *)action->next) { - if (options & LIB_LOAD_VERBOSE) - printf("ActionName: %s\n", action->name + 2); - scene_merge->GetLogicManager()->RegisterActionName(action->name + 2, action); - } - } - else if (idcode == ID_SCE) { - /* Merge all new linked in scene into the existing one */ - ID *scene; - // scenes gets deleted by the thread when it's done using it (look in async_convert()) - vector *scenes = (options & LIB_LOAD_ASYNC) ? new vector() : NULL; - - for (scene = (ID *)main_newlib->scene.first; scene; scene = (ID *)scene->next ) { - if (options & LIB_LOAD_VERBOSE) - printf("SceneName: %s\n", scene->name + 2); - - if (options & LIB_LOAD_ASYNC) { - scenes->push_back((Scene *)scene); - } - else { - /* merge into the base scene */ - KX_Scene* other = m_ketsjiEngine->CreateScene((Scene *)scene, true); - scene_merge->MergeScene(other); - - // RemoveScene(other); // Don't run this, it frees the entire scene converter data, just delete the scene - delete other; - } - } - - if (options & LIB_LOAD_ASYNC) { - status->SetData(scenes); - BLI_task_pool_push(m_threadinfo->m_pool, async_convert, (void *)status, false, TASK_PRIORITY_LOW); - } - -#ifdef WITH_PYTHON - /* Handle any text datablocks */ - if (options & LIB_LOAD_LOAD_SCRIPTS) - addImportMain(main_newlib); -#endif - - /* Now handle all the actions */ - if (options & LIB_LOAD_LOAD_ACTIONS) { - ID *action; - - for (action = (ID *)main_newlib->action.first; action; action = (ID *)action->next) { - if (options & LIB_LOAD_VERBOSE) - printf("ActionName: %s\n", action->name + 2); - scene_merge->GetLogicManager()->RegisterActionName(action->name + 2, action); - } - } - } - - if (!(options & LIB_LOAD_ASYNC)) - status->Finish(); - -// TIMEIT_END(bge_link_blend_file); - - m_status_map[main_newlib->name] = status; - return status; -} - -/* Note m_map_*** are all ok and don't need to be freed - * most are temp and NewRemoveObject frees m_map_gameobject_to_blender */ -bool KX_BlenderSceneConverter::FreeBlendFile(Main *maggie) -{ - int maggie_index = -1; - int i = 0; - - if (maggie == NULL) - return false; - - // If the given library is currently in loading, we do nothing. - if (m_status_map.count(maggie->name)) { - BLI_mutex_lock(&m_threadinfo->m_mutex); - const bool finished = m_status_map[maggie->name]->IsFinished(); - BLI_mutex_unlock(&m_threadinfo->m_mutex); - - if (!finished) { - printf("Library (%s) is currently being loaded asynchronously, and cannot be freed until this process is done\n", maggie->name); - return false; - } - } - - /* tag all false except the one we remove */ - for (vector
::iterator it = m_DynamicMaggie.begin(); !(it == m_DynamicMaggie.end()); it++) { - Main *main = *it; - if (main != maggie) { - BKE_main_id_tag_all(main, LIB_TAG_DOIT, false); - } - else { - maggie_index = i; - } - i++; - } - - /* should never happen but just to be safe */ - if (maggie_index == -1) - return false; - - m_DynamicMaggie.erase(m_DynamicMaggie.begin() + maggie_index); - BKE_main_id_tag_all(maggie, LIB_TAG_DOIT, true); - - /* free all tagged objects */ - KX_SceneList *scenes = m_ketsjiEngine->CurrentScenes(); - int numScenes = scenes->size(); - - for (int scene_idx = 0; scene_idx < numScenes; scene_idx++) { - KX_Scene *scene = scenes->at(scene_idx); - if (IS_TAGGED(scene->GetBlenderScene())) { - m_ketsjiEngine->RemoveScene(scene->GetName()); - m_mat_cache.erase(scene); - m_polymat_cache.erase(scene); - scene_idx--; - numScenes--; - } - else { - /* in case the mesh might be refered to later */ - { - CTR_Map &mapStringToMeshes = scene->GetLogicManager()->GetMeshMap(); - - for (int i = 0; i < mapStringToMeshes.size(); i++) { - RAS_MeshObject *meshobj = (RAS_MeshObject *) *mapStringToMeshes.at(i); - if (meshobj && IS_TAGGED(meshobj->GetMesh())) { - STR_HashedString mn = meshobj->GetName(); - mapStringToMeshes.remove(mn); - m_map_mesh_to_gamemesh.remove(CHashedPtr(meshobj->GetMesh())); - i--; - } - } - } - - /* Now unregister actions */ - { - CTR_Map &mapStringToActions = scene->GetLogicManager()->GetActionMap(); - - for (int i = 0; i < mapStringToActions.size(); i++) { - ID *action = (ID*) *mapStringToActions.at(i); - - if (IS_TAGGED(action)) { - STR_HashedString an = action->name + 2; - mapStringToActions.remove(an); - m_map_blender_to_gameAdtList.remove(CHashedPtr(action)); - i--; - } - } - } - - //scene->FreeTagged(); /* removed tagged objects and meshes*/ - CListValue *obj_lists[] = {scene->GetObjectList(), scene->GetInactiveList(), NULL}; - - for (int ob_ls_idx = 0; obj_lists[ob_ls_idx]; ob_ls_idx++) { - CListValue *obs = obj_lists[ob_ls_idx]; - RAS_MeshObject *mesh; - - for (int ob_idx = 0; ob_idx < obs->GetCount(); ob_idx++) { - KX_GameObject *gameobj = (KX_GameObject*)obs->GetValue(ob_idx); - if (IS_TAGGED(gameobj->GetBlenderObject())) { - int size_before = obs->GetCount(); - - /* Eventually calls RemoveNodeDestructObject - * frees m_map_gameobject_to_blender from UnregisterGameObject */ - scene->RemoveObject(gameobj); - - if (size_before != obs->GetCount()) - ob_idx--; - else { - printf("ERROR COULD NOT REMOVE \"%s\"\n", gameobj->GetName().ReadPtr()); - } - } - else { - gameobj->RemoveTaggedActions(); - /* free the mesh, we could be referecing a linked one! */ - int mesh_index = gameobj->GetMeshCount(); - while (mesh_index--) { - mesh = gameobj->GetMesh(mesh_index); - if (IS_TAGGED(mesh->GetMesh())) { - gameobj->RemoveMeshes(); /* XXX - slack, should only remove meshes that are library items but mostly objects only have 1 mesh */ - break; - } - else { - /* also free the mesh if it's using a tagged material */ - int mat_index = mesh->NumMaterials(); - while (mat_index--) { - if (IS_TAGGED(mesh->GetMeshMaterial(mat_index)->m_bucket->GetPolyMaterial()->GetBlenderMaterial())) { - gameobj->RemoveMeshes(); /* XXX - slack, same as above */ - break; - } - } - } - } - - /* make sure action actuators are not referencing tagged actions */ - for (unsigned int act_idx = 0; act_idx < gameobj->GetActuators().size(); act_idx++) { - if (gameobj->GetActuators()[act_idx]->IsType(SCA_IActuator::KX_ACT_ACTION)) { - BL_ActionActuator *act = (BL_ActionActuator *)gameobj->GetActuators()[act_idx]; - if (IS_TAGGED(act->GetAction())) - act->SetAction(NULL); - } - } - } - } - } - } - } - - int size; - - // delete the entities of this scene - /* TODO - */ -#if 0 - vector >::iterator worldit; - size = m_worldinfos.size(); - for (i=0, worldit=m_worldinfos.begin(); i KX_WorldInfoSet; - KX_WorldInfoSet worldset; - for (int scene_idx = 0; scene_idx < numScenes; scene_idx++) { - KX_Scene *scene = scenes->at(scene_idx); - if (scene->GetWorldInfo()) - worldset.insert(scene->GetWorldInfo()); - } - - vector >::iterator worldit; - size = m_worldinfos.size(); - for (i = 0, worldit = m_worldinfos.begin(); i < size;) { - if (worldit->second && (worldset.count(worldit->second)) == 0) { - delete worldit->second; - *worldit = m_worldinfos.back(); - m_worldinfos.pop_back(); - size--; - } - else { - i++; - worldit++; - } - } - worldset.clear(); - /* done freeing the worlds */ - - vector >::iterator polymit; - size = m_polymaterials.size(); - - for (i = 0, polymit = m_polymaterials.begin(); i < size; ) { - RAS_IPolyMaterial *mat = polymit->second; - Material *bmat = NULL; - - KX_BlenderMaterial *bl_mat = static_cast(mat); - bmat = bl_mat->GetBlenderMaterial(); - - if (IS_TAGGED(bmat)) { - /* only remove from bucket */ - polymit->first->GetBucketManager()->RemoveMaterial(mat); - } - - i++; - polymit++; - } - - for (i = 0, polymit = m_polymaterials.begin(); i < size; ) { - RAS_IPolyMaterial *mat = polymit->second; - Material *bmat = NULL; - - KX_BlenderMaterial *bl_mat = static_cast(mat); - bmat = bl_mat->GetBlenderMaterial(); - - if (IS_TAGGED(bmat)) { - // Remove the poly material coresponding to this Blender Material. - m_polymat_cache[polymit->first].erase(bmat); - delete polymit->second; - *polymit = m_polymaterials.back(); - m_polymaterials.pop_back(); - size--; - } else { - i++; - polymit++; - } - } - - vector >::iterator matit; - size = m_materials.size(); - for (i = 0, matit = m_materials.begin(); i < size; ) { - BL_Material *mat = matit->second; - if (IS_TAGGED(mat->material)) { - // Remove the bl material coresponding to this Blender Material. - m_mat_cache[matit->first].erase(mat->material); - delete matit->second; - *matit = m_materials.back(); - m_materials.pop_back(); - size--; - } - else { - i++; - matit++; - } - } - - vector >::iterator meshit; - RAS_BucketManager::BucketList::iterator bit; - list::iterator msit; - RAS_BucketManager::BucketList buckets; - - size = m_meshobjects.size(); - for (i = 0, meshit = m_meshobjects.begin(); i < size;) { - RAS_MeshObject *me = meshit->second; - if (IS_TAGGED(me->GetMesh())) { - // Before deleting the mesh object, make sure the rasterizer is - // no longer referencing it. - buckets = meshit->first->GetBucketManager()->GetSolidBuckets(); - for (bit = buckets.begin(); bit != buckets.end(); bit++) { - msit = (*bit)->msBegin(); - - while (msit != (*bit)->msEnd()) { - if (msit->m_mesh == meshit->second) - (*bit)->RemoveMesh(&(*msit++)); - else - msit++; - } - } - - // And now the alpha buckets - buckets = meshit->first->GetBucketManager()->GetAlphaBuckets(); - for (bit = buckets.begin(); bit != buckets.end(); bit++) { - msit = (*bit)->msBegin(); - - while (msit != (*bit)->msEnd()) { - if (msit->m_mesh == meshit->second) - (*bit)->RemoveMesh(&(*msit++)); - else - msit++; - } - } - - // Now it should be safe to delete - delete meshit->second; - *meshit = m_meshobjects.back(); - m_meshobjects.pop_back(); - size--; - } - else { - i++; - meshit++; - } - } - -#ifdef WITH_PYTHON - /* make sure this maggie is removed from the import list if it's there - * (this operation is safe if it isn't in the list) */ - removeImportMain(maggie); -#endif - - delete m_status_map[maggie->name]; - m_status_map.erase(maggie->name); - - BKE_main_free(maggie); - - return true; -} - -bool KX_BlenderSceneConverter::FreeBlendFile(const char *path) -{ - return FreeBlendFile(GetMainDynamicPath(path)); -} - -bool KX_BlenderSceneConverter::MergeScene(KX_Scene *to, KX_Scene *from) -{ - { - vector >::iterator itp = m_worldinfos.begin(); - while (itp != m_worldinfos.end()) { - if (itp->first == from) - itp->first = to; - itp++; - } - } - - { - vector >::iterator itp = m_polymaterials.begin(); - while (itp != m_polymaterials.end()) { - if (itp->first == from) { - itp->first = to; - - /* also switch internal data */ - RAS_IPolyMaterial *mat = itp->second; - mat->Replace_IScene(to); - } - itp++; - } - } - - { - vector >::iterator itp = m_meshobjects.begin(); - while (itp != m_meshobjects.end()) { - if (itp->first == from) - itp->first = to; - itp++; - } - } - - { - vector >::iterator itp = m_materials.begin(); - while (itp != m_materials.end()) { - if (itp->first == from) - itp->first = to; - itp++; - } - } - - MaterialCache::iterator matcacheit = m_mat_cache.find(from); - if (matcacheit != m_mat_cache.end()) { - // Merge cached BL_Material map. - m_mat_cache[to].insert(matcacheit->second.begin(), matcacheit->second.end()); - m_mat_cache.erase(matcacheit); - } - - PolyMaterialCache::iterator polymatcacheit = m_polymat_cache.find(from); - if (polymatcacheit != m_polymat_cache.end()) { - // Merge cached RAS_IPolyMaterial map. - m_polymat_cache[to].insert(polymatcacheit->second.begin(), polymatcacheit->second.end()); - m_polymat_cache.erase(polymatcacheit); - } - - return true; -} - -/* This function merges a mesh from the current scene into another main - * it does not convert */ -RAS_MeshObject *KX_BlenderSceneConverter::ConvertMeshSpecial(KX_Scene *kx_scene, Main *maggie, const char *name) -{ - /* Find a mesh in the current main */ - ID *me= static_cast(BLI_findstring(&m_maggie->mesh, name, offsetof(ID, name) + 2)); - Main *from_maggie = m_maggie; - - if (me == NULL) { - // The mesh wasn't in the current main, try any dynamic (i.e., LibLoaded) ones - vector
::iterator it; - - for (it = GetMainDynamic().begin(); it != GetMainDynamic().end(); it++) { - me = static_cast(BLI_findstring(&(*it)->mesh, name, offsetof(ID, name) + 2)); - from_maggie = *it; - - if (me) - break; - } - } - - if (me == NULL) { - printf("Could not be found \"%s\"\n", name); - return NULL; - } - - /* Watch this!, if its used in the original scene can cause big troubles */ - if (me->us > 0) { -#ifdef DEBUG - printf("Mesh has a user \"%s\"\n", name); -#endif - me = (ID*)BKE_mesh_copy(from_maggie, (Mesh*)me); - id_us_min(me); - } - BLI_remlink(&from_maggie->mesh, me); /* even if we made the copy it needs to be removed */ - BLI_addtail(&maggie->mesh, me); - - /* Must copy the materials this uses else we cant free them */ - { - Mesh *mesh = (Mesh *)me; - - /* ensure all materials are tagged */ - for (int i = 0; i < mesh->totcol; i++) { - if (mesh->mat[i]) - mesh->mat[i]->id.tag &= ~LIB_TAG_DOIT; - } - - for (int i = 0; i < mesh->totcol; i++) { - Material *mat_old = mesh->mat[i]; - - /* if its tagged its a replaced material */ - if (mat_old && (mat_old->id.tag & LIB_TAG_DOIT) == 0) { - Material *mat_old = mesh->mat[i]; - Material *mat_new = BKE_material_copy(from_maggie, mat_old); - - mat_new->id.tag |= LIB_TAG_DOIT; - id_us_min(&mat_old->id); - - BLI_remlink(&from_maggie->mat, mat_new); // BKE_material_copy uses G.main, and there is no BKE_material_copy_ex - BLI_addtail(&maggie->mat, mat_new); - - mesh->mat[i] = mat_new; - - /* the same material may be used twice */ - for (int j = i + 1; j < mesh->totcol; j++) { - if (mesh->mat[j] == mat_old) { - mesh->mat[j] = mat_new; - id_us_plus(&mat_new->id); - id_us_min(&mat_old->id); - } - } - } - } - } - - m_currentScene = kx_scene; // This needs to be set in case we LibLoaded earlier - RAS_MeshObject *meshobj = BL_ConvertMesh((Mesh *)me, NULL, kx_scene, this, false); - kx_scene->GetLogicManager()->RegisterMeshName(meshobj->GetName(),meshobj); - m_map_mesh_to_gamemesh.clear(); /* This is at runtime so no need to keep this, BL_ConvertMesh adds */ - return meshobj; -} diff --git a/source/gameengine/Converter/KX_BlenderSceneConverter.h b/source/gameengine/Converter/KX_BlenderSceneConverter.h deleted file mode 100644 index 40c71a4d74b..00000000000 --- a/source/gameengine/Converter/KX_BlenderSceneConverter.h +++ /dev/null @@ -1,232 +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_BlenderSceneConverter.h - * \ingroup bgeconv - */ - -#ifndef __KX_BLENDERSCENECONVERTER_H__ -#define __KX_BLENDERSCENECONVERTER_H__ - -#include "EXP_HashedPtr.h" -#include "CTR_Map.h" -#include - -#include "KX_ISceneConverter.h" -#include "KX_IpoConvert.h" - -#include - -using namespace std; - -class KX_WorldInfo; -class SCA_IActuator; -class SCA_IController; -class RAS_MeshObject; -class RAS_IPolyMaterial; -class BL_InterpolatorList; -class BL_Material; -struct Main; -struct Scene; -struct ThreadInfo; -struct Material; - -typedef map > MaterialCache; -typedef map > PolyMaterialCache; - -class KX_BlenderSceneConverter : public KX_ISceneConverter -{ - // Use vector of pairs to allow removal of entities between scene switch - vector > m_worldinfos; - vector > m_polymaterials; - vector > m_meshobjects; - vector > m_materials; - - vector m_mergequeue; - ThreadInfo *m_threadinfo; - - // Cached material conversions - MaterialCache m_mat_cache; - PolyMaterialCache m_polymat_cache; - - // Saved KX_LibLoadStatus objects - map m_status_map; - - // Should also have a list of collision shapes. - // For the time being this is held in KX_Scene::m_shapes - - CTR_Map m_map_blender_to_gameobject; /* cleared after conversion */ - CTR_Map m_map_mesh_to_gamemesh; /* cleared after conversion */ - CTR_Map m_map_blender_to_gameactuator; /* cleared after conversion */ - CTR_Mapm_map_blender_to_gamecontroller; /* cleared after conversion */ - - CTR_Map m_map_blender_to_gameAdtList; - - Main* m_maggie; - vector m_DynamicMaggie; - - STR_String m_newfilename; - class KX_KetsjiEngine* m_ketsjiEngine; - class KX_Scene* m_currentScene; // Scene being converted - bool m_alwaysUseExpandFraming; - bool m_usemat; - bool m_useglslmat; - bool m_use_mat_cache; - -public: - KX_BlenderSceneConverter( - Main* maggie, - class KX_KetsjiEngine* engine - ); - - virtual ~KX_BlenderSceneConverter(); - - /* Scenename: name of the scene to be converted. - * 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 - ); - virtual void RemoveScene(class KX_Scene *scene); - - void SetNewFileName(const STR_String& filename); - bool TryAndLoadNewFile(); - - void SetAlwaysUseExpandFraming(bool to_what); - - void RegisterGameObject(KX_GameObject *gameobject, struct Object *for_blenderobject); - void UnregisterGameObject(KX_GameObject *gameobject); - KX_GameObject *FindGameObject(struct Object *for_blenderobject); - - void RegisterGameMesh(RAS_MeshObject *gamemesh, struct Mesh *for_blendermesh); - RAS_MeshObject *FindGameMesh(struct Mesh *for_blendermesh/*, unsigned int onlayer*/); - - void RegisterPolyMaterial(RAS_IPolyMaterial *polymat); - void CachePolyMaterial(KX_Scene *scene, Material *mat, RAS_IPolyMaterial *polymat); - RAS_IPolyMaterial *FindCachedPolyMaterial(KX_Scene *scene, Material *mat); - - void RegisterBlenderMaterial(BL_Material *mat); - void CacheBlenderMaterial(KX_Scene *scene, Material *mat, BL_Material *blmat); - BL_Material *FindCachedBlenderMaterial(KX_Scene *scene, Material *mat); - - void RegisterInterpolatorList(BL_InterpolatorList *actList, struct bAction *for_act); - BL_InterpolatorList *FindInterpolatorList(struct bAction *for_act); - - void RegisterGameActuator(SCA_IActuator *act, struct bActuator *for_actuator); - SCA_IActuator *FindGameActuator(struct bActuator *for_actuator); - - void RegisterGameController(SCA_IController *cont, struct bController *for_controller); - SCA_IController *FindGameController(struct bController *for_controller); - - void RegisterWorldInfo(KX_WorldInfo *worldinfo); - - virtual void ResetPhysicsObjectsAnimationIpo(bool clearIpo); - - ///this is for reseting the position,rotation and scale of the gameobjet that is not dynamic - virtual void resetNoneDynamicObjectToIpo(); - - ///this generates ipo curves for position, rotation, allowing to use game physics in animation - virtual void WritePhysicsObjectToAnimationIpo(int frameNumber); - virtual void TestHandlesPhysicsObjectToAnimationIpo(); - - // use blender materials - virtual void SetMaterials(bool val); - virtual bool GetMaterials(); - - // use blender glsl materials - virtual void SetGLSLMaterials(bool val); - virtual bool GetGLSLMaterials(); - - // cache materials during conversion - virtual void SetCacheMaterials(bool val); - virtual bool GetCacheMaterials(); - - struct Scene* GetBlenderSceneForName(const STR_String& name); - -// struct Main* GetMain() { return m_maggie; } - struct Main* GetMainDynamicPath(const char *path); - vector &GetMainDynamic(); - - class KX_LibLoadStatus *LinkBlendFileMemory(void *data, int length, const char *path, char *group, KX_Scene *scene_merge, char **err_str, short options); - class KX_LibLoadStatus *LinkBlendFilePath(const char *path, char *group, KX_Scene *scene_merge, char **err_str, short options); - class KX_LibLoadStatus *LinkBlendFile(struct BlendHandle *bpy_openlib, const char *path, char *group, KX_Scene *scene_merge, char **err_str, short options); - bool MergeScene(KX_Scene *to, KX_Scene *from); - RAS_MeshObject *ConvertMeshSpecial(KX_Scene* kx_scene, Main *maggie, const char *name); - bool FreeBlendFile(struct Main *maggie); - bool FreeBlendFile(const char *path); - - virtual void MergeAsyncLoads(); - virtual void FinalizeAsyncLoads(); - void AddScenesToMergeQueue(class KX_LibLoadStatus *status); - - void PrintStats() { - printf("BGE STATS!\n"); - - printf("\nAssets...\n"); - printf("\t m_worldinfos: %d\n", (int)m_worldinfos.size()); - printf("\t m_polymaterials: %d\n", (int)m_polymaterials.size()); - printf("\t m_meshobjects: %d\n", (int)m_meshobjects.size()); - printf("\t m_materials: %d\n", (int)m_materials.size()); - - printf("\nMappings...\n"); - printf("\t m_map_blender_to_gameobject: %d\n", m_map_blender_to_gameobject.size()); - printf("\t m_map_mesh_to_gamemesh: %d\n", m_map_mesh_to_gamemesh.size()); - printf("\t m_map_blender_to_gameactuator: %d\n", m_map_blender_to_gameactuator.size()); - printf("\t m_map_blender_to_gamecontroller: %d\n", m_map_blender_to_gamecontroller.size()); - printf("\t m_map_blender_to_gameAdtList: %d\n", m_map_blender_to_gameAdtList.size()); - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_printmemlist_pydict(); -#endif -// /printf("\t m_ketsjiEngine->m_scenes: %d\n", m_ketsjiEngine->CurrentScenes()->size()); - } - - /* LibLoad Options */ - enum - { - LIB_LOAD_LOAD_ACTIONS = 1, - LIB_LOAD_VERBOSE = 2, - LIB_LOAD_LOAD_SCRIPTS = 4, - LIB_LOAD_ASYNC = 8, - }; - - - -#ifdef WITH_PYTHON - PyObject *GetPyNamespace(); -#endif - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:KX_BlenderSceneConverter") -#endif -}; - -#endif /* __KX_BLENDERSCENECONVERTER_H__ */ diff --git a/source/gameengine/Converter/KX_ConvertActuators.cpp b/source/gameengine/Converter/KX_ConvertActuators.cpp deleted file mode 100644 index d78ea4eed54..00000000000 --- a/source/gameengine/Converter/KX_ConvertActuators.cpp +++ /dev/null @@ -1,1146 +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 ***** - * Convert Blender actuators for use in the GameEngine - */ - -/** \file gameengine/Converter/KX_ConvertActuators.cpp - * \ingroup bgeconv - */ - -#ifdef _MSC_VER -# pragma warning (disable:4786) -#endif - -#include - -#include "MEM_guardedalloc.h" - -#include "KX_BlenderSceneConverter.h" -#include "KX_ConvertActuators.h" - -#ifdef WITH_AUDASPACE -# include -#endif - -// Actuators -//SCA logiclibrary native logicbricks -#include "SCA_PropertyActuator.h" -#include "SCA_LogicManager.h" -#include "SCA_RandomActuator.h" -#include "SCA_2DFilterActuator.h" - -// Ketsji specific logicbricks -#include "KX_SceneActuator.h" -#include "KX_SoundActuator.h" -#include "KX_ObjectActuator.h" -#include "KX_TrackToActuator.h" -#include "KX_ConstraintActuator.h" -#include "KX_CameraActuator.h" -#include "KX_GameActuator.h" -#include "KX_StateActuator.h" -#include "KX_VisibilityActuator.h" -#include "KX_SCA_AddObjectActuator.h" -#include "KX_SCA_EndObjectActuator.h" -#include "KX_SCA_ReplaceMeshActuator.h" -#include "KX_ParentActuator.h" -#include "KX_SCA_DynamicActuator.h" -#include "KX_SteeringActuator.h" -#include "KX_MouseActuator.h" - -#include "KX_Scene.h" -#include "KX_KetsjiEngine.h" - -#include "EXP_IntValue.h" -#include "KX_GameObject.h" - -/* This little block needed for linking to Blender... */ -#include "BKE_text.h" -#include "BLI_blenlib.h" -#include "BLI_math.h" -#include "BLI_path_util.h" - -#include "KX_NetworkMessageActuator.h" - -#ifdef WIN32 -#include "BLI_winstuff.h" -#endif - -#include "DNA_object_types.h" -#include "DNA_sound_types.h" -#include "DNA_scene_types.h" -#include "DNA_actuator_types.h" -#include "DNA_packedFile_types.h" -#include "BL_ActionActuator.h" -#include "BL_ShapeActionActuator.h" -#include "BL_ArmatureActuator.h" -#include "RNA_access.h" -#include "BL_Action.h" -/* end of blender include block */ - -#include "BL_BlenderDataConversion.h" - -/** - * KX_flt_trunc needed to round 'almost' zero values to zero, else velocities etc. are incorrectly set - */ - -BLI_INLINE float KX_flt_trunc(const float x) -{ - return ( x < 0.0001f && x > -0.0001f ) ? 0.0f : x; -} - -void BL_ConvertActuators(const char* maggiename, - struct Object* blenderobject, - KX_GameObject* gameobj, - SCA_LogicManager* logicmgr, - KX_Scene* scene, - KX_KetsjiEngine* ketsjiEngine, - int activeLayerBitInfo, - bool isInActiveLayer, - KX_BlenderSceneConverter* converter - ) -{ - - int uniqueint = 0; - int actcount = 0; - int executePriority = 0; - bActuator* bact = (bActuator*) blenderobject->actuators.first; - while (bact) - { - actcount++; - bact = bact->next; - } - gameobj->ReserveActuator(actcount); - bact = (bActuator*) blenderobject->actuators.first; - while (bact) - { - STR_String uniquename = bact->name; - STR_String& objectname = gameobj->GetName(); - - SCA_IActuator* baseact = NULL; - switch (bact->type) - { - case ACT_OBJECT: - { - bObjectActuator* obact = (bObjectActuator*) bact->data; - KX_GameObject* obref = NULL; - MT_Vector3 forcevec(KX_flt_trunc(obact->forceloc[0]), - KX_flt_trunc(obact->forceloc[1]), - KX_flt_trunc(obact->forceloc[2])); - MT_Vector3 torquevec(obact->forcerot[0], - obact->forcerot[1], - obact->forcerot[2]); - MT_Vector3 dlocvec(KX_flt_trunc(obact->dloc[0]), - KX_flt_trunc(obact->dloc[1]), - KX_flt_trunc(obact->dloc[2])); - MT_Vector3 drotvec(KX_flt_trunc(obact->drot[0]), - obact->drot[1],obact->drot[2]); - MT_Vector3 linvelvec(KX_flt_trunc(obact->linearvelocity[0]), - KX_flt_trunc(obact->linearvelocity[1]), - KX_flt_trunc(obact->linearvelocity[2])); - MT_Vector3 angvelvec(KX_flt_trunc(obact->angularvelocity[0]), - KX_flt_trunc(obact->angularvelocity[1]), - KX_flt_trunc(obact->angularvelocity[2])); - short damping = obact->damping; - - /* Blender uses a bit vector internally for the local-flags. In */ - /* KX, we have four bools. The compiler should be smart enough */ - /* to do the right thing. We need to explicitly convert here! */ - - KX_LocalFlags bitLocalFlag; - - bitLocalFlag.Force = bool((obact->flag & ACT_FORCE_LOCAL)!=0); - bitLocalFlag.Torque = bool((obact->flag & ACT_TORQUE_LOCAL) !=0);//rlocal; - bitLocalFlag.DLoc = bool((obact->flag & ACT_DLOC_LOCAL)!=0); - bitLocalFlag.DRot = bool((obact->flag & ACT_DROT_LOCAL)!=0); - bitLocalFlag.LinearVelocity = bool((obact->flag & ACT_LIN_VEL_LOCAL)!=0); - bitLocalFlag.AngularVelocity = bool((obact->flag & ACT_ANG_VEL_LOCAL)!=0); - bitLocalFlag.ServoControl = bool(obact->type == ACT_OBJECT_SERVO); - bitLocalFlag.CharacterMotion = bool(obact->type == ACT_OBJECT_CHARACTER); - bitLocalFlag.CharacterJump = bool((obact->flag & ACT_CHAR_JUMP)!=0); - bitLocalFlag.AddOrSetLinV = bool((obact->flag & ACT_ADD_LIN_VEL)!=0); - bitLocalFlag.AddOrSetCharLoc = bool((obact->flag & ACT_ADD_CHAR_LOC)!=0); - if (obact->reference && bitLocalFlag.ServoControl) - { - obref = converter->FindGameObject(obact->reference); - } - - KX_ObjectActuator* tmpbaseact = new KX_ObjectActuator( - gameobj, - obref, - forcevec.getValue(), - torquevec.getValue(), - dlocvec.getValue(), - drotvec.getValue(), - linvelvec.getValue(), - angvelvec.getValue(), - damping, - bitLocalFlag); - baseact = tmpbaseact; - break; - } - case ACT_ACTION: - { - bActionActuator* actact = (bActionActuator*) bact->data; - STR_String propname = actact->name; - STR_String propframe = actact->frameProp; - - short ipo_flags = 0; - - // Convert flags - if (actact->flag & ACT_IPOFORCE) ipo_flags |= BL_Action::ACT_IPOFLAG_FORCE; - if (actact->flag & ACT_IPOLOCAL) ipo_flags |= BL_Action::ACT_IPOFLAG_LOCAL; - if (actact->flag & ACT_IPOADD) ipo_flags |= BL_Action::ACT_IPOFLAG_ADD; - if (actact->flag & ACT_IPOCHILD) ipo_flags |= BL_Action::ACT_IPOFLAG_CHILD; - - BL_ActionActuator* tmpbaseact = new BL_ActionActuator( - gameobj, - propname, - propframe, - actact->sta, - actact->end, - actact->act, - actact->type, // + 1, because Blender starts to count at zero, - actact->blend_mode, - actact->blendin, - actact->priority, - actact->layer, - actact->layer_weight, - ipo_flags, - actact->end_reset, - actact->stridelength - // Ketsji at 1, because zero is reserved for "NoDef" - ); - baseact= tmpbaseact; - break; - } - case ACT_SHAPEACTION: - { - if (blenderobject->type==OB_MESH) { - bActionActuator* actact = (bActionActuator*) bact->data; - STR_String propname = actact->name; - STR_String propframe = actact->frameProp; - - BL_ShapeActionActuator* tmpbaseact = new BL_ShapeActionActuator( - gameobj, - propname, - propframe, - actact->sta, - actact->end, - actact->act, - actact->type, // + 1, because Blender starts to count at zero, - actact->blendin, - actact->priority, - actact->stridelength); - // Ketsji at 1, because zero is reserved for "NoDef" - baseact= tmpbaseact; - break; - } - else - printf ("Discarded shape action actuator from non-mesh object [%s]\n", blenderobject->id.name+2); - } - case ACT_LAMP: - { - break; - } - case ACT_CAMERA: - { - bCameraActuator *camact = (bCameraActuator *) bact->data; - if (camact->ob) { - KX_GameObject *tmpgob = converter->FindGameObject(camact->ob); - - /* visifac, fac and axis are not copied from the struct... */ - /* that's some internal state... */ - KX_CameraActuator *tmpcamact = new KX_CameraActuator( - gameobj, - tmpgob, - camact->height, - camact->min, - camact->max, - camact->axis, - camact->damping); - baseact = tmpcamact; - } - break; - } - case ACT_MESSAGE: - { - bMessageActuator *msgAct = (bMessageActuator *) bact->data; - - /* Get the name of the properties that objects must own that - * we're sending to, if present - */ - STR_String toPropName = msgAct->toPropName; - - /* Get the Message Subject to send. - */ - STR_String subject = msgAct->subject; - - /* Get the bodyType - */ - int bodyType = msgAct->bodyType; - - /* Get the body (text message or property name whose value - * we'll be sending, might be empty - */ - const STR_String body = msgAct->body; - - KX_NetworkMessageActuator *tmpmsgact = new KX_NetworkMessageActuator( - gameobj, // actuator controlling object - scene->GetNetworkScene(), // needed for replication - toPropName, - subject, - bodyType, - body); - baseact = tmpmsgact; - break; - } - case ACT_MATERIAL: - { - break; - } - case ACT_SOUND: - { - bSoundActuator* soundact = (bSoundActuator*) bact->data; - /* get type, and possibly a start and end frame */ - KX_SoundActuator::KX_SOUNDACT_TYPE - soundActuatorType = KX_SoundActuator::KX_SOUNDACT_NODEF; - - switch (soundact->type) { - case ACT_SND_PLAY_STOP_SOUND: - soundActuatorType = KX_SoundActuator::KX_SOUNDACT_PLAYSTOP; - break; - case ACT_SND_PLAY_END_SOUND: - soundActuatorType = KX_SoundActuator::KX_SOUNDACT_PLAYEND; - break; - case ACT_SND_LOOP_STOP_SOUND: - soundActuatorType = KX_SoundActuator::KX_SOUNDACT_LOOPSTOP; - break; - case ACT_SND_LOOP_END_SOUND: - soundActuatorType = KX_SoundActuator::KX_SOUNDACT_LOOPEND; - break; - case ACT_SND_LOOP_BIDIRECTIONAL_SOUND: - soundActuatorType = KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL; - break; - case ACT_SND_LOOP_BIDIRECTIONAL_STOP_SOUND: - soundActuatorType = KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP; - break; - - default: - /* This is an error!!! */ - soundActuatorType = KX_SoundActuator::KX_SOUNDACT_NODEF; - } - - if (soundActuatorType != KX_SoundActuator::KX_SOUNDACT_NODEF) - { - bSound* sound = soundact->sound; - bool is3d = soundact->flag & ACT_SND_3D_SOUND ? true : false; - AUD_Sound* snd_sound = NULL; - KX_3DSoundSettings settings; - settings.cone_inner_angle = RAD2DEGF(soundact->sound3D.cone_inner_angle); - settings.cone_outer_angle = RAD2DEGF(soundact->sound3D.cone_outer_angle); - settings.cone_outer_gain = soundact->sound3D.cone_outer_gain; - settings.max_distance = soundact->sound3D.max_distance; - settings.max_gain = soundact->sound3D.max_gain; - settings.min_gain = soundact->sound3D.min_gain; - settings.reference_distance = soundact->sound3D.reference_distance; - settings.rolloff_factor = soundact->sound3D.rolloff_factor; - - if (!sound) - { - std::cout << "WARNING: Sound actuator \"" << bact->name << - "\" from object \"" << blenderobject->id.name+2 << - "\" has no sound datablock." << std::endl; - } - else - { - snd_sound = sound->playback_handle; - - // if sound shall be 3D but isn't mono, we have to make it mono! - if (is3d) - { - snd_sound = AUD_Sound_rechannel(snd_sound, AUD_CHANNELS_MONO); - } - } - KX_SoundActuator* tmpsoundact = - new KX_SoundActuator(gameobj, - snd_sound, - soundact->volume, - (float)(expf((soundact->pitch / 12.0f) * (float)M_LN2)), - is3d, - settings, - soundActuatorType); - - // if we made it mono, we have to free it - if (sound && snd_sound && snd_sound != sound->playback_handle) { - AUD_Sound_free(snd_sound); - } - - tmpsoundact->SetName(bact->name); - baseact = tmpsoundact; - } - break; - } - case ACT_PROPERTY: - { - bPropertyActuator* propact = (bPropertyActuator*) bact->data; - SCA_IObject* destinationObj = NULL; - - /* - * here the destinationobject is searched. problem with multiple scenes: other scenes - * have not been converted yet, so the destobj will not be found, so the prop will - * not be copied. - * possible solutions: - * - convert everything when possible and not realtime only when needed. - * - let the object-with-property report itself to the act when converted - */ - if (propact->ob) - destinationObj = converter->FindGameObject(propact->ob); - - SCA_PropertyActuator* tmppropact = new SCA_PropertyActuator( - gameobj, - destinationObj, - propact->name, - propact->value, - propact->type + 1); // + 1 because Ketsji Logic starts - // with 0 for KX_ACT_PROP_NODEF - baseact = tmppropact; - break; - } - case ACT_EDIT_OBJECT: - { - bEditObjectActuator *editobact - = (bEditObjectActuator *) bact->data; - /* There are four different kinds of 'edit object' thingies */ - /* The alternative to this lengthy conversion is packing */ - /* several actuators in one, which is not very nice design.. */ - switch (editobact->type) { - case ACT_EDOB_ADD_OBJECT: - { - - // does the 'original' for replication exists, and - // is it in a non-active layer ? - SCA_IObject* originalval = NULL; - if (editobact->ob) - { - if (editobact->ob->lay & activeLayerBitInfo) - { - fprintf(stderr, "Warning, object \"%s\" from AddObject actuator \"%s\" is not in a hidden layer.\n", objectname.Ptr(), uniquename.Ptr()); - } - else { - originalval = converter->FindGameObject(editobact->ob); - } - } - - KX_SCA_AddObjectActuator* tmpaddact = new KX_SCA_AddObjectActuator( - gameobj, - originalval, - editobact->time, - scene, - editobact->linVelocity, - (editobact->localflag & ACT_EDOB_LOCAL_LINV) != 0, - editobact->angVelocity, - (editobact->localflag & ACT_EDOB_LOCAL_ANGV) != 0); - - //editobact->ob to gameobj - baseact = tmpaddact; - } - break; - case ACT_EDOB_END_OBJECT: - { - KX_SCA_EndObjectActuator* tmpendact - = new KX_SCA_EndObjectActuator(gameobj,scene); - baseact = tmpendact; - } - break; - case ACT_EDOB_REPLACE_MESH: - { - RAS_MeshObject *tmpmesh = converter->FindGameMesh(editobact->me); - - if (!tmpmesh) { - std::cout << "Warning: object \"" << objectname << - "\" from ReplaceMesh actuator \"" << uniquename << - "\" uses a mesh not owned by an object in scene \"" << - scene->GetName() << "\"." << std::endl; - } - - KX_SCA_ReplaceMeshActuator* tmpreplaceact = new KX_SCA_ReplaceMeshActuator( - gameobj, - tmpmesh, - scene, - (editobact->flag & ACT_EDOB_REPLACE_MESH_NOGFX) == 0, - (editobact->flag & ACT_EDOB_REPLACE_MESH_PHYS) != 0); - - baseact = tmpreplaceact; - } - break; - case ACT_EDOB_TRACK_TO: - { - SCA_IObject* originalval = NULL; - if (editobact->ob) - originalval = converter->FindGameObject(editobact->ob); - - KX_TrackToActuator* tmptrackact = new KX_TrackToActuator( - gameobj, - originalval, - editobact->time, - editobact->flag, - editobact->trackflag, - editobact->upflag); - baseact = tmptrackact; - break; - } - case ACT_EDOB_DYNAMICS: - { - KX_SCA_DynamicActuator* tmpdynact = new KX_SCA_DynamicActuator( - gameobj, - editobact->dyn_operation, - editobact->mass); - baseact = tmpdynact; - } - } - break; - } - case ACT_CONSTRAINT: - { - float min = 0.0, max = 0.0; - char *prop = NULL; - KX_ConstraintActuator::KX_CONSTRAINTTYPE locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_NODEF; - bConstraintActuator *conact - = (bConstraintActuator*) bact->data; - /* convert settings... degrees in the ui become radians */ - /* internally */ - if (conact->type == ACT_CONST_TYPE_ORI) { - min = conact->minloc[0]; - max = conact->maxloc[0]; - switch (conact->mode) { - case ACT_CONST_DIRPX: - locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIX; - break; - case ACT_CONST_DIRPY: - locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIY; - break; - case ACT_CONST_DIRPZ: - locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIZ; - break; - } - } else if (conact->type == ACT_CONST_TYPE_DIST) { - switch (conact->mode) { - case ACT_CONST_DIRPX: - locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPX; - min = conact->minloc[0]; - max = conact->maxloc[0]; - break; - case ACT_CONST_DIRPY: - locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPY; - min = conact->minloc[1]; - max = conact->maxloc[1]; - break; - case ACT_CONST_DIRPZ: - locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPZ; - min = conact->minloc[2]; - max = conact->maxloc[2]; - break; - case ACT_CONST_DIRNX: - locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNX; - min = conact->minloc[0]; - max = conact->maxloc[0]; - break; - case ACT_CONST_DIRNY: - locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNY; - min = conact->minloc[1]; - max = conact->maxloc[1]; - break; - case ACT_CONST_DIRNZ: - locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNZ; - min = conact->minloc[2]; - max = conact->maxloc[2]; - break; - } - prop = conact->matprop; - } else if (conact->type == ACT_CONST_TYPE_FH) { - switch (conact->mode) { - case ACT_CONST_DIRPX: - locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPX; - min = conact->minloc[0]; - max = conact->maxloc[0]; - break; - case ACT_CONST_DIRPY: - locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPY; - min = conact->minloc[1]; - max = conact->maxloc[1]; - break; - case ACT_CONST_DIRPZ: - locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPZ; - min = conact->minloc[2]; - max = conact->maxloc[2]; - break; - case ACT_CONST_DIRNX: - locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNX; - min = conact->minloc[0]; - max = conact->maxloc[0]; - break; - case ACT_CONST_DIRNY: - locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNY; - min = conact->minloc[1]; - max = conact->maxloc[1]; - break; - case ACT_CONST_DIRNZ: - locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNZ; - min = conact->minloc[2]; - max = conact->maxloc[2]; - break; - } - prop = conact->matprop; - } else { - switch (conact->flag) { - case ACT_CONST_LOCX: - locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCX; - min = conact->minloc[0]; - max = conact->maxloc[0]; - break; - case ACT_CONST_LOCY: - locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCY; - min = conact->minloc[1]; - max = conact->maxloc[1]; - break; - case ACT_CONST_LOCZ: - locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCZ; - min = conact->minloc[2]; - max = conact->maxloc[2]; - break; - case ACT_CONST_ROTX: - locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTX; - min = conact->minrot[0] * (float)MT_RADS_PER_DEG; - max = conact->maxrot[0] * (float)MT_RADS_PER_DEG; - break; - case ACT_CONST_ROTY: - locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTY; - min = conact->minrot[1] * (float)MT_RADS_PER_DEG; - max = conact->maxrot[1] * (float)MT_RADS_PER_DEG; - break; - case ACT_CONST_ROTZ: - locrot = KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTZ; - min = conact->minrot[2] * (float)MT_RADS_PER_DEG; - max = conact->maxrot[2] * (float)MT_RADS_PER_DEG; - break; - default: - ; /* error */ - } - } - KX_ConstraintActuator *tmpconact = new KX_ConstraintActuator( - gameobj, - conact->damp, - conact->rotdamp, - min, - max, - conact->maxrot, - locrot, - conact->time, - conact->flag, - prop); - baseact = tmpconact; - break; - } - case ACT_GROUP: - { - // deprecated - } - break; - case ACT_SCENE: - { - bSceneActuator *sceneact = (bSceneActuator *) bact->data; - STR_String nextSceneName(""); - - KX_SceneActuator* tmpsceneact; - int mode = KX_SceneActuator::KX_SCENE_NODEF; - KX_Camera *cam = NULL; - //KX_Scene* scene = NULL; - switch (sceneact->type) - { - case ACT_SCENE_RESUME: - case ACT_SCENE_SUSPEND: - case ACT_SCENE_ADD_FRONT: - case ACT_SCENE_ADD_BACK: - case ACT_SCENE_REMOVE: - case ACT_SCENE_SET: - { - switch (sceneact->type) - { - case ACT_SCENE_RESUME: - mode = KX_SceneActuator::KX_SCENE_RESUME; - break; - case ACT_SCENE_SUSPEND: - mode = KX_SceneActuator::KX_SCENE_SUSPEND; - break; - case ACT_SCENE_ADD_FRONT: - mode = KX_SceneActuator::KX_SCENE_ADD_FRONT_SCENE; - break; - case ACT_SCENE_ADD_BACK: - mode = KX_SceneActuator::KX_SCENE_ADD_BACK_SCENE; - break; - case ACT_SCENE_REMOVE: - mode = KX_SceneActuator::KX_SCENE_REMOVE_SCENE; - break; - case ACT_SCENE_SET: - default: - mode = KX_SceneActuator::KX_SCENE_SET_SCENE; - break; - }; - - if (sceneact->scene) { - nextSceneName = sceneact->scene->id.name + 2; - } - - break; - } - case ACT_SCENE_CAMERA: - mode = KX_SceneActuator::KX_SCENE_SET_CAMERA; - if (sceneact->camera) - { - KX_GameObject *tmp = converter->FindGameObject(sceneact->camera); - if (tmp && tmp->GetGameObjectType() == SCA_IObject::OBJ_CAMERA) - cam = (KX_Camera*)tmp; - } - break; - case ACT_SCENE_RESTART: - { - - mode = KX_SceneActuator::KX_SCENE_RESTART; - break; - } - default: - ; /* flag error */ - } - tmpsceneact = new KX_SceneActuator( - gameobj, - mode, - scene, - ketsjiEngine, - nextSceneName, - cam); - baseact = tmpsceneact; - break; - } - case ACT_GAME: - { - bGameActuator *gameact = (bGameActuator *) bact->data; - KX_GameActuator* tmpgameact; - STR_String filename = maggiename; - STR_String loadinganimationname = ""; - int mode = KX_GameActuator::KX_GAME_NODEF; - switch (gameact->type) - { - case ACT_GAME_LOAD: - { - mode = KX_GameActuator::KX_GAME_LOAD; - filename = gameact->filename; - loadinganimationname = gameact->loadaniname; - break; - } - case ACT_GAME_START: - { - mode = KX_GameActuator::KX_GAME_START; - filename = gameact->filename; - loadinganimationname = gameact->loadaniname; - break; - } - case ACT_GAME_RESTART: - { - mode = KX_GameActuator::KX_GAME_RESTART; - break; - } - case ACT_GAME_QUIT: - { - mode = KX_GameActuator::KX_GAME_QUIT; - break; - } - case ACT_GAME_SAVECFG: - { - mode = KX_GameActuator::KX_GAME_SAVECFG; - break; - } - case ACT_GAME_LOADCFG: - { - mode = KX_GameActuator::KX_GAME_LOADCFG; - break; - } - case ACT_GAME_SCREENSHOT: - { - mode = KX_GameActuator::KX_GAME_SCREENSHOT; - filename = gameact->filename; - break; - } - default: - ; /* flag error */ - } - tmpgameact = new KX_GameActuator( - gameobj, - mode, - filename, - loadinganimationname, - scene, - ketsjiEngine); - baseact = tmpgameact; - - break; - } - case ACT_RANDOM: - { - bRandomActuator *randAct - = (bRandomActuator *) bact->data; - - unsigned long seedArg = randAct->seed; - if (seedArg == 0) - { - seedArg = (int)(ketsjiEngine->GetRealTime()*100000.0); - seedArg ^= (intptr_t)randAct; - } - SCA_RandomActuator::KX_RANDOMACT_MODE modeArg - = SCA_RandomActuator::KX_RANDOMACT_NODEF; - SCA_RandomActuator *tmprandomact; - float paraArg1 = 0.0; - float paraArg2 = 0.0; - - switch (randAct->distribution) { - case ACT_RANDOM_BOOL_CONST: - modeArg = SCA_RandomActuator::KX_RANDOMACT_BOOL_CONST; - paraArg1 = (float) randAct->int_arg_1; - break; - case ACT_RANDOM_BOOL_UNIFORM: - modeArg = SCA_RandomActuator::KX_RANDOMACT_BOOL_UNIFORM; - break; - case ACT_RANDOM_BOOL_BERNOUILLI: - paraArg1 = randAct->float_arg_1; - modeArg = SCA_RandomActuator::KX_RANDOMACT_BOOL_BERNOUILLI; - break; - case ACT_RANDOM_INT_CONST: - modeArg = SCA_RandomActuator::KX_RANDOMACT_INT_CONST; - paraArg1 = (float) randAct->int_arg_1; - break; - case ACT_RANDOM_INT_UNIFORM: - paraArg1 = (float) randAct->int_arg_1; - paraArg2 = (float) randAct->int_arg_2; - modeArg = SCA_RandomActuator::KX_RANDOMACT_INT_UNIFORM; - break; - case ACT_RANDOM_INT_POISSON: - paraArg1 = randAct->float_arg_1; - modeArg = SCA_RandomActuator::KX_RANDOMACT_INT_POISSON; - break; - case ACT_RANDOM_FLOAT_CONST: - paraArg1 = randAct->float_arg_1; - modeArg = SCA_RandomActuator::KX_RANDOMACT_FLOAT_CONST; - break; - case ACT_RANDOM_FLOAT_UNIFORM: - paraArg1 = randAct->float_arg_1; - paraArg2 = randAct->float_arg_2; - modeArg = SCA_RandomActuator::KX_RANDOMACT_FLOAT_UNIFORM; - break; - case ACT_RANDOM_FLOAT_NORMAL: - paraArg1 = randAct->float_arg_1; - paraArg2 = randAct->float_arg_2; - modeArg = SCA_RandomActuator::KX_RANDOMACT_FLOAT_NORMAL; - break; - case ACT_RANDOM_FLOAT_NEGATIVE_EXPONENTIAL: - paraArg1 = randAct->float_arg_1; - modeArg = SCA_RandomActuator::KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL; - break; - default: - ; /* error */ - } - tmprandomact = new SCA_RandomActuator( - gameobj, - seedArg, - modeArg, - paraArg1, - paraArg2, - randAct->propname); - baseact = tmprandomact; - } - break; - - case ACT_VISIBILITY: - { - bVisibilityActuator *vis_act = (bVisibilityActuator *) bact->data; - KX_VisibilityActuator * tmp_vis_act = NULL; - bool v = ((vis_act->flag & ACT_VISIBILITY_INVISIBLE) != 0); - bool o = ((vis_act->flag & ACT_VISIBILITY_OCCLUSION) != 0); - bool recursive = ((vis_act->flag & ACT_VISIBILITY_RECURSIVE) != 0); - - tmp_vis_act = new KX_VisibilityActuator(gameobj, !v, o, recursive); - - baseact = tmp_vis_act; - } - break; - - case ACT_STATE: - { - bStateActuator *sta_act = (bStateActuator *) bact->data; - KX_StateActuator * tmp_sta_act = NULL; - - tmp_sta_act = - new KX_StateActuator(gameobj, sta_act->type, sta_act->mask); - - baseact = tmp_sta_act; - } - break; - - case ACT_2DFILTER: - { - bTwoDFilterActuator *_2dfilter = (bTwoDFilterActuator*) bact->data; - SCA_2DFilterActuator *tmp = NULL; - - RAS_2DFilterManager::RAS_2DFILTER_MODE filtermode; - switch (_2dfilter->type) { - case ACT_2DFILTER_MOTIONBLUR: - filtermode = RAS_2DFilterManager::RAS_2DFILTER_MOTIONBLUR; - break; - case ACT_2DFILTER_BLUR: - filtermode = RAS_2DFilterManager::RAS_2DFILTER_BLUR; - break; - case ACT_2DFILTER_SHARPEN: - filtermode = RAS_2DFilterManager::RAS_2DFILTER_SHARPEN; - break; - case ACT_2DFILTER_DILATION: - filtermode = RAS_2DFilterManager::RAS_2DFILTER_DILATION; - break; - case ACT_2DFILTER_EROSION: - filtermode = RAS_2DFilterManager::RAS_2DFILTER_EROSION; - break; - case ACT_2DFILTER_LAPLACIAN: - filtermode = RAS_2DFilterManager::RAS_2DFILTER_LAPLACIAN; - break; - case ACT_2DFILTER_SOBEL: - filtermode = RAS_2DFilterManager::RAS_2DFILTER_SOBEL; - break; - case ACT_2DFILTER_PREWITT: - filtermode = RAS_2DFilterManager::RAS_2DFILTER_PREWITT; - break; - case ACT_2DFILTER_GRAYSCALE: - filtermode = RAS_2DFilterManager::RAS_2DFILTER_GRAYSCALE; - break; - case ACT_2DFILTER_SEPIA: - filtermode = RAS_2DFilterManager::RAS_2DFILTER_SEPIA; - break; - case ACT_2DFILTER_INVERT: - filtermode = RAS_2DFilterManager::RAS_2DFILTER_INVERT; - break; - case ACT_2DFILTER_CUSTOMFILTER: - filtermode = RAS_2DFilterManager::RAS_2DFILTER_CUSTOMFILTER; - break; - case ACT_2DFILTER_NOFILTER: - filtermode = RAS_2DFilterManager::RAS_2DFILTER_NOFILTER; - break; - case ACT_2DFILTER_DISABLED: - filtermode = RAS_2DFilterManager::RAS_2DFILTER_DISABLED; - break; - case ACT_2DFILTER_ENABLED: - filtermode = RAS_2DFilterManager::RAS_2DFILTER_ENABLED; - break; - default: - filtermode = RAS_2DFilterManager::RAS_2DFILTER_NOFILTER; - break; - } - - tmp = new SCA_2DFilterActuator(gameobj, filtermode, _2dfilter->flag, - _2dfilter->float_arg, _2dfilter->int_arg, - ketsjiEngine->GetRasterizer(), scene); - - if (_2dfilter->text) - { - char *buf; - // this is some blender specific code - buf = txt_to_buf(_2dfilter->text); - if (buf) - { - tmp->SetShaderText(buf); - MEM_freeN(buf); - } - } - - baseact = tmp; - - } - break; - case ACT_PARENT: - { - bParentActuator *parAct = (bParentActuator *) bact->data; - int mode = KX_ParentActuator::KX_PARENT_NODEF; - bool addToCompound = true; - bool ghost = true; - KX_GameObject *tmpgob = NULL; - - switch (parAct->type) { - case ACT_PARENT_SET: - mode = KX_ParentActuator::KX_PARENT_SET; - tmpgob = converter->FindGameObject(parAct->ob); - addToCompound = !(parAct->flag & ACT_PARENT_COMPOUND); - ghost = !(parAct->flag & ACT_PARENT_GHOST); - break; - case ACT_PARENT_REMOVE: - mode = KX_ParentActuator::KX_PARENT_REMOVE; - tmpgob = NULL; - break; - } - - KX_ParentActuator *tmpparact - = new KX_ParentActuator(gameobj, - mode, - addToCompound, - ghost, - tmpgob); - baseact = tmpparact; - break; - } - - case ACT_ARMATURE: - { - bArmatureActuator* armAct = (bArmatureActuator*) bact->data; - KX_GameObject *tmpgob = converter->FindGameObject(armAct->target); - KX_GameObject *subgob = converter->FindGameObject(armAct->subtarget); - BL_ArmatureActuator* tmparmact = new BL_ArmatureActuator( - gameobj, - armAct->type, - armAct->posechannel, - armAct->constraint, - tmpgob, - subgob, - armAct->weight, - armAct->influence); - baseact = tmparmact; - break; - } - case ACT_STEERING: - { - bSteeringActuator *stAct = (bSteeringActuator *) bact->data; - KX_GameObject *navmeshob = NULL; - if (stAct->navmesh) - { - PointerRNA settings_ptr; - RNA_pointer_create((ID *)stAct->navmesh, &RNA_GameObjectSettings, stAct->navmesh, &settings_ptr); - if (RNA_enum_get(&settings_ptr, "physics_type") == OB_BODY_TYPE_NAVMESH) - navmeshob = converter->FindGameObject(stAct->navmesh); - } - KX_GameObject *targetob = converter->FindGameObject(stAct->target); - - int mode = KX_SteeringActuator::KX_STEERING_NODEF; - switch (stAct->type) { - case ACT_STEERING_SEEK: - mode = KX_SteeringActuator::KX_STEERING_SEEK; - break; - case ACT_STEERING_FLEE: - mode = KX_SteeringActuator::KX_STEERING_FLEE; - break; - case ACT_STEERING_PATHFOLLOWING: - mode = KX_SteeringActuator::KX_STEERING_PATHFOLLOWING; - break; - } - - bool selfTerminated = (stAct->flag & ACT_STEERING_SELFTERMINATED) !=0; - bool enableVisualization = (stAct->flag & ACT_STEERING_ENABLEVISUALIZATION) !=0; - short facingMode = (stAct->flag & ACT_STEERING_AUTOMATICFACING) ? stAct->facingaxis : 0; - bool normalup = (stAct->flag & ACT_STEERING_NORMALUP) !=0; - bool lockzvel = (stAct->flag & ACT_STEERING_LOCKZVEL) !=0; - KX_SteeringActuator *tmpstact - = new KX_SteeringActuator(gameobj, mode, targetob, navmeshob,stAct->dist, - stAct->velocity, stAct->acceleration, stAct->turnspeed, - selfTerminated, stAct->updateTime, - scene->GetObstacleSimulation(), facingMode, normalup, enableVisualization, lockzvel); - baseact = tmpstact; - break; - } - case ACT_MOUSE: - { - bMouseActuator* mouAct = (bMouseActuator*) bact->data; - int mode = KX_MouseActuator::KX_ACT_MOUSE_NODEF; - - switch (mouAct->type) { - case ACT_MOUSE_VISIBILITY: - { - mode = KX_MouseActuator::KX_ACT_MOUSE_VISIBILITY; - break; - } - case ACT_MOUSE_LOOK: - { - mode = KX_MouseActuator::KX_ACT_MOUSE_LOOK; - break; - } - } - - bool visible = (mouAct->flag & ACT_MOUSE_VISIBLE) != 0; - bool use_axis[2] = {(mouAct->flag & ACT_MOUSE_USE_AXIS_X) != 0, (mouAct->flag & ACT_MOUSE_USE_AXIS_Y) != 0}; - bool reset[2] = {(mouAct->flag & ACT_MOUSE_RESET_X) != 0, (mouAct->flag & ACT_MOUSE_RESET_Y) != 0}; - bool local[2] = {(mouAct->flag & ACT_MOUSE_LOCAL_X) != 0, (mouAct->flag & ACT_MOUSE_LOCAL_Y) != 0}; - - SCA_MouseManager* eventmgr = (SCA_MouseManager*) logicmgr->FindEventManager(SCA_EventManager::MOUSE_EVENTMGR); - if (eventmgr) { - KX_MouseActuator* tmpbaseact = new KX_MouseActuator(gameobj, - ketsjiEngine, - eventmgr, - mode, - visible, - use_axis, - mouAct->threshold, - reset, - mouAct->object_axis, - local, - mouAct->sensitivity, - mouAct->limit_x, - mouAct->limit_y); - baseact = tmpbaseact; - } else { - //cout << "\n Couldn't find mouse event manager..."; - should throw an error here... - } - break; - } - default: - ; /* generate some error */ - } - - if (baseact && !(bact->flag & ACT_DEACTIVATE)) - { - baseact->SetExecutePriority(executePriority++); - uniquename += "#ACT#"; - uniqueint++; - CIntValue* uniqueval = new CIntValue(uniqueint); - uniquename += uniqueval->GetText(); - uniqueval->Release(); - baseact->SetName(bact->name); - baseact->SetLogicManager(logicmgr); - //gameobj->SetProperty(uniquename,baseact); - gameobj->AddActuator(baseact); - - converter->RegisterGameActuator(baseact, bact); - // done with baseact, release it - baseact->Release(); - } - else if (baseact) - baseact->Release(); - - bact = bact->next; - } -} - - diff --git a/source/gameengine/Converter/KX_ConvertActuators.h b/source/gameengine/Converter/KX_ConvertActuators.h deleted file mode 100644 index 688b5db50ce..00000000000 --- a/source/gameengine/Converter/KX_ConvertActuators.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_ConvertActuators.h - * \ingroup bgeconv - */ - -#ifndef __KX_CONVERTACTUATORS_H__ -#define __KX_CONVERTACTUATORS_H__ - -void BL_ConvertActuators(const char* maggiename, - struct Object* blenderobject, - class KX_GameObject* gameobj, - class SCA_LogicManager* logicmgr, - class KX_Scene* scene, - class KX_KetsjiEngine* ketsjiEngine, - int activeLayerBitInfo, - bool isInActiveLayer, - class KX_BlenderSceneConverter* converter); - -#endif /* __KX_CONVERTACTUATORS_H__ */ diff --git a/source/gameengine/Converter/KX_ConvertControllers.cpp b/source/gameengine/Converter/KX_ConvertControllers.cpp deleted file mode 100644 index f55d81adb80..00000000000 --- a/source/gameengine/Converter/KX_ConvertControllers.cpp +++ /dev/null @@ -1,250 +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/Converter/KX_ConvertControllers.cpp - * \ingroup bgeconv - */ - - -#include "MEM_guardedalloc.h" - -#include "KX_BlenderSceneConverter.h" -#include "KX_ConvertControllers.h" -#include "EXP_Python.h" - -// Controller -#include "SCA_ANDController.h" -#include "SCA_ORController.h" -#include "SCA_NANDController.h" -#include "SCA_NORController.h" -#include "SCA_XORController.h" -#include "SCA_XNORController.h" -#include "SCA_PythonController.h" -#include "SCA_ExpressionController.h" - -#include "SCA_LogicManager.h" -#include "KX_GameObject.h" -#include "EXP_IntValue.h" - -/* This little block needed for linking to Blender... */ -#ifdef WIN32 -#include "BLI_winstuff.h" -#endif - -#include "DNA_object_types.h" -#include "DNA_controller_types.h" -#include "DNA_text_types.h" - -#include "BKE_text.h" - -#include "BLI_blenlib.h" - -/* end of blender include block */ - - - static void -LinkControllerToActuators( - SCA_IController *game_controller, - bController* bcontr, - SCA_LogicManager* logicmgr, - KX_BlenderSceneConverter* converter -) { - // Iterate through the actuators of the game blender - // controller and find the corresponding ketsji actuator. - - game_controller->ReserveActuator(bcontr->totlinks); - for (int i=0;itotlinks;i++) - { - bActuator* bact = (bActuator*) bcontr->links[i]; - SCA_IActuator *game_actuator = converter->FindGameActuator(bact); - if (game_actuator) { - logicmgr->RegisterToActuator(game_controller, game_actuator); - } - } -} - - -void BL_ConvertControllers( - struct Object* blenderobject, - class KX_GameObject* gameobj, - SCA_LogicManager* logicmgr, - int activeLayerBitInfo, - bool isInActiveLayer, - KX_BlenderSceneConverter* converter, - bool libloading -) { - int uniqueint=0; - int count = 0; - int executePriority=0; - bController* bcontr = (bController*)blenderobject->controllers.first; - while (bcontr) - { - bcontr = bcontr->next; - count++; - } - gameobj->ReserveController(count); - bcontr = (bController*)blenderobject->controllers.first; - while (bcontr) - { - SCA_IController* gamecontroller = NULL; - switch (bcontr->type) { - case CONT_LOGIC_AND: - { - gamecontroller = new SCA_ANDController(gameobj); - break; - } - case CONT_LOGIC_OR: - { - gamecontroller = new SCA_ORController(gameobj); - break; - } - case CONT_LOGIC_NAND: - { - gamecontroller = new SCA_NANDController(gameobj); - break; - } - case CONT_LOGIC_NOR: - { - gamecontroller = new SCA_NORController(gameobj); - break; - } - case CONT_LOGIC_XOR: - { - gamecontroller = new SCA_XORController(gameobj); - break; - } - case CONT_LOGIC_XNOR: - { - gamecontroller = new SCA_XNORController(gameobj); - break; - } - case CONT_EXPRESSION: - { - bExpressionCont* bexpcont = (bExpressionCont*) bcontr->data; - STR_String expressiontext = STR_String(bexpcont->str); - if (expressiontext.Length() > 0) - { - gamecontroller = new SCA_ExpressionController(gameobj,expressiontext); - } - break; - } - case CONT_PYTHON: - { - bPythonCont* pycont = (bPythonCont*) bcontr->data; - SCA_PythonController* pyctrl = new SCA_PythonController(gameobj, pycont->mode); - gamecontroller = pyctrl; -#ifdef WITH_PYTHON - // When libloading, this is delayed to KX_Scene::MergeScene_LogicBrick to avoid GIL issues - if (!libloading) - pyctrl->SetNamespace(converter->GetPyNamespace()); - - if (pycont->mode==SCA_PythonController::SCA_PYEXEC_SCRIPT) { - if (pycont->text) - { - char *buf; - // this is some blender specific code - buf= txt_to_buf(pycont->text); - if (buf) - { - pyctrl->SetScriptText(STR_String(buf)); - pyctrl->SetScriptName(pycont->text->id.name+2); - MEM_freeN(buf); - } - - } - } - else { - /* let the controller print any warnings here when importing */ - pyctrl->SetScriptText(STR_String(pycont->module)); - pyctrl->SetScriptName(pycont->module); /* will be something like module.func so using it as the name is OK */ - - if (pycont->flag & CONT_PY_DEBUG) { - printf("\nDebuging \"%s\", module for object %s\n\texpect worse performance.\n", pycont->module, blenderobject->id.name+2); - pyctrl->SetDebug(true); - } - } -#endif // WITH_PYTHON - - break; - } - default: - { - - } - } - - if (gamecontroller && !(bcontr->flag & CONT_DEACTIVATE)) - { - LinkControllerToActuators(gamecontroller,bcontr,logicmgr,converter); - gamecontroller->SetExecutePriority(executePriority++); - gamecontroller->SetBookmark((bcontr->flag & CONT_PRIO) != 0); - gamecontroller->SetState(bcontr->state_mask); - STR_String uniquename = bcontr->name; - uniquename += "#CONTR#"; - uniqueint++; - CIntValue* uniqueval = new CIntValue(uniqueint); - uniquename += uniqueval->GetText(); - uniqueval->Release(); - //unique name was never implemented for sensors and actuators, only for controllers - //and it's producing difference in the keys for the lists: obj.controllers/sensors/actuators - //at some point it should either be implemented globally (and saved as a separate var) or removed. - //gamecontroller->SetName(uniquename); - gamecontroller->SetName(bcontr->name); - gamecontroller->SetLogicManager(logicmgr); - gameobj->AddController(gamecontroller); - - converter->RegisterGameController(gamecontroller, bcontr); - -#ifdef WITH_PYTHON - // When libloading, this is delayed to KX_Scene::MergeScene_LogicBrick to avoid GIL issues - if (!libloading && bcontr->type==CONT_PYTHON) { - SCA_PythonController *pyctrl= static_cast(gamecontroller); - /* not strictly needed but gives syntax errors early on and - * gives more predictable performance for larger scripts */ - if (pyctrl->m_mode==SCA_PythonController::SCA_PYEXEC_SCRIPT) - pyctrl->Compile(); - else { - /* We cant do this because importing runs the script which could end up accessing - * internal BGE functions, this is unstable while we're converting the scene. - * This is a pity because its useful to see errors at startup but cant help it */ - - // pyctrl->Import(); - } - } - -#endif // WITH_PYTHON - - //done with gamecontroller - gamecontroller->Release(); - } - else if (gamecontroller) - gamecontroller->Release(); - - bcontr = bcontr->next; - } - -} diff --git a/source/gameengine/Converter/KX_ConvertControllers.h b/source/gameengine/Converter/KX_ConvertControllers.h deleted file mode 100644 index 2f93d70a6f9..00000000000 --- a/source/gameengine/Converter/KX_ConvertControllers.h +++ /dev/null @@ -1,47 +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_ConvertControllers.h - * \ingroup bgeconv - */ - -#ifndef __KX_CONVERTCONTROLLERS_H__ -#define __KX_CONVERTCONTROLLERS_H__ - -#include "EXP_Python.h" - -void BL_ConvertControllers( - struct Object* blenderobject, - class KX_GameObject* gameobj, - class SCA_LogicManager* logicmgr, - int activeLayerBitInfo, - bool isInActiveLayer, - class KX_BlenderSceneConverter* converter, - bool libloading -); - -#endif /* __KX_CONVERTCONTROLLERS_H__ */ diff --git a/source/gameengine/Converter/KX_ConvertProperties.cpp b/source/gameengine/Converter/KX_ConvertProperties.cpp deleted file mode 100644 index 2cb61207fb5..00000000000 --- a/source/gameengine/Converter/KX_ConvertProperties.cpp +++ /dev/null @@ -1,243 +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/Converter/KX_ConvertProperties.cpp - * \ingroup bgeconv - */ - - -#include "KX_ConvertProperties.h" - - -#include "DNA_object_types.h" -#include "DNA_property_types.h" -/* end of blender include block */ - - -#include "EXP_Value.h" -#include "EXP_VectorValue.h" -#include "EXP_BoolValue.h" -#include "EXP_StringValue.h" -#include "EXP_FloatValue.h" -#include "KX_GameObject.h" -#include "EXP_IntValue.h" -#include "SCA_TimeEventManager.h" -#include "SCA_IScene.h" - -#include "KX_FontObject.h" -#include "DNA_curve_types.h" - -/* This little block needed for linking to Blender... */ -#ifdef WIN32 -#include "BLI_winstuff.h" -#endif - -extern "C" { - #include "BKE_property.h" -} - -/* prototype */ -void BL_ConvertTextProperty(Object* object, KX_FontObject* fontobj,SCA_TimeEventManager* timemgr,SCA_IScene* scene, bool isInActiveLayer); - -void BL_ConvertProperties(Object* object,KX_GameObject* gameobj,SCA_TimeEventManager* timemgr,SCA_IScene* scene, bool isInActiveLayer) -{ - - bProperty* prop = (bProperty*)object->prop.first; - CValue* propval; - bool show_debug_info; - - while (prop) { - propval = NULL; - show_debug_info = bool (prop->flag & PROP_DEBUG); - - switch (prop->type) { - case GPROP_BOOL: - { - propval = new CBoolValue((bool)(prop->data != 0)); - gameobj->SetProperty(prop->name,propval); - //promp->poin= &prop->data; - break; - } - case GPROP_INT: - { - propval = new CIntValue((int)prop->data); - gameobj->SetProperty(prop->name,propval); - break; - } - case GPROP_FLOAT: - { - //prop->poin= &prop->data; - float floatprop = *((float*)&prop->data); - propval = new CFloatValue(floatprop); - gameobj->SetProperty(prop->name,propval); - } - break; - case GPROP_STRING: - { - //prop->poin= callocN(MAX_PROPSTRING, "property string"); - propval = new CStringValue((char*)prop->poin,""); - gameobj->SetProperty(prop->name,propval); - break; - } - case GPROP_TIME: - { - float floatprop = *((float*)&prop->data); - - CValue* timeval = new CFloatValue(floatprop); - // set a subproperty called 'timer' so that - // we can register the replica of this property - // at the time a game object is replicated (AddObjectActuator triggers this) - CValue *bval = new CBoolValue(true); - timeval->SetProperty("timer",bval); - bval->Release(); - if (isInActiveLayer) - { - timemgr->AddTimeProperty(timeval); - } - - propval = timeval; - gameobj->SetProperty(prop->name,timeval); - - } - default: - { - // todo make an assert etc. - } - } - - if (propval) - { - if (show_debug_info && isInActiveLayer) - { - scene->AddDebugProperty(gameobj,STR_String(prop->name)); - } - // done with propval, release it - propval->Release(); - } - -#ifdef WITH_PYTHON - /* Warn if we double up on attributes, this isn't quite right since it wont find inherited attributes however there arnt many */ - for (PyAttributeDef *attrdef = KX_GameObject::Attributes; attrdef->m_name; attrdef++) { - if (strcmp(prop->name, attrdef->m_name)==0) { - printf("Warning! user defined property name \"%s\" is also a python attribute for object \"%s\"\n\tUse ob[\"%s\"] syntax to avoid conflict\n", prop->name, object->id.name+2, prop->name); - break; - } - } - for (PyMethodDef *methdef = KX_GameObject::Methods; methdef->ml_name; methdef++) { - if (strcmp(prop->name, methdef->ml_name)==0) { - printf("Warning! user defined property name \"%s\" is also a python method for object \"%s\"\n\tUse ob[\"%s\"] syntax to avoid conflict\n", prop->name, object->id.name+2, prop->name); - break; - } - } - /* end warning check */ -#endif // WITH_PYTHON - - prop = prop->next; - } - // check if state needs to be debugged - if (object->scaflag & OB_DEBUGSTATE && isInActiveLayer) - { - // reserve name for object state - scene->AddDebugProperty(gameobj,STR_String("__state__")); - } - - /* Font Objects need to 'copy' the Font Object data body to ["Text"] */ - if (object->type == OB_FONT) - { - BL_ConvertTextProperty(object, (KX_FontObject *)gameobj, timemgr, scene, isInActiveLayer); - } -} - -void BL_ConvertTextProperty(Object* object, KX_FontObject* fontobj,SCA_TimeEventManager* timemgr,SCA_IScene* scene, bool isInActiveLayer) -{ - CValue* tprop = fontobj->GetProperty("Text"); - if (!tprop) return; - bProperty* prop = BKE_bproperty_object_get(object, "Text"); - if (!prop) return; - - Curve *curve = static_cast(object->data); - STR_String str = curve->str; - CValue* propval = NULL; - - switch (prop->type) { - case GPROP_BOOL: - { - int value = atoi(str); - propval = new CBoolValue((bool)(value != 0)); - tprop->SetValue(propval); - break; - } - case GPROP_INT: - { - int value = atoi(str); - propval = new CIntValue(value); - tprop->SetValue(propval); - break; - } - case GPROP_FLOAT: - { - float floatprop = (float)atof(str); - propval = new CFloatValue(floatprop); - tprop->SetValue(propval); - break; - } - case GPROP_STRING: - { - propval = new CStringValue(str, ""); - tprop->SetValue(propval); - break; - } - case GPROP_TIME: - { - float floatprop = (float)atof(str); - - CValue* timeval = new CFloatValue(floatprop); - // set a subproperty called 'timer' so that - // we can register the replica of this property - // at the time a game object is replicated (AddObjectActuator triggers this) - CValue *bval = new CBoolValue(true); - timeval->SetProperty("timer",bval); - bval->Release(); - if (isInActiveLayer) - { - timemgr->AddTimeProperty(timeval); - } - - propval = timeval; - tprop->SetValue(timeval); - } - default: - { - // todo make an assert etc. - } - } - - if (propval) { - propval->Release(); - } -} - diff --git a/source/gameengine/Converter/KX_ConvertProperties.h b/source/gameengine/Converter/KX_ConvertProperties.h deleted file mode 100644 index 8f96cc21af6..00000000000 --- a/source/gameengine/Converter/KX_ConvertProperties.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_ConvertProperties.h - * \ingroup bgeconv - */ - -#ifndef __KX_CONVERTPROPERTIES_H__ -#define __KX_CONVERTPROPERTIES_H__ - -void BL_ConvertProperties(struct Object* object, - class KX_GameObject* gameobj, - class SCA_TimeEventManager* timemgr, - class SCA_IScene* scene, - bool isInActiveLayer); - -#endif /* __KX_CONVERTPROPERTIES_H__ */ diff --git a/source/gameengine/Converter/KX_ConvertSensors.cpp b/source/gameengine/Converter/KX_ConvertSensors.cpp deleted file mode 100644 index 5e897bb4a62..00000000000 --- a/source/gameengine/Converter/KX_ConvertSensors.cpp +++ /dev/null @@ -1,663 +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/Converter/KX_ConvertSensors.cpp - * \ingroup bgeconv - * - * Conversion of Blender data blocks to KX sensor system - */ - -#include - -#ifdef _MSC_VER -# pragma warning (disable:4786) -#endif - -#include "wm_event_types.h" -#include "KX_BlenderSceneConverter.h" -#include "KX_ConvertSensors.h" - -/* This little block needed for linking to Blender... */ -#ifdef _MSC_VER -# include "BLI_winstuff.h" -#endif - -#include "DNA_object_types.h" -#include "DNA_material_types.h" -#include "DNA_sensor_types.h" -#include "DNA_controller_types.h" -#include "DNA_actuator_types.h" /* for SENS_ALL_KEYS ? this define is - * probably misplaced */ -/* end of blender include block */ - -#include "RAS_IPolygonMaterial.h" -// Sensors -#include "KX_GameObject.h" -#include "RAS_MeshObject.h" -#include "SCA_KeyboardSensor.h" -#include "SCA_MouseSensor.h" -#include "SCA_AlwaysSensor.h" -#include "KX_TouchSensor.h" -#include "KX_NearSensor.h" -#include "KX_RadarSensor.h" -#include "KX_MouseFocusSensor.h" -#include "KX_ArmatureSensor.h" -#include "SCA_JoystickSensor.h" -#include "KX_NetworkMessageSensor.h" -#include "SCA_ActuatorSensor.h" -#include "SCA_DelaySensor.h" - - -#include "SCA_PropertySensor.h" -#include "SCA_RandomSensor.h" -#include "KX_RaySensor.h" -#include "SCA_EventManager.h" -#include "SCA_LogicManager.h" -#include "KX_BlenderInputDevice.h" -#include "KX_Scene.h" -#include "EXP_IntValue.h" -#include "KX_BlenderKeyboardDevice.h" -#include "RAS_ICanvas.h" -#include "PHY_IPhysicsEnvironment.h" - -#include "KX_KetsjiEngine.h" -#include "BL_BlenderDataConversion.h" - -void BL_ConvertSensors(struct Object* blenderobject, - class KX_GameObject* gameobj, - SCA_LogicManager* logicmgr, - KX_Scene* kxscene, - KX_KetsjiEngine* kxengine, - int activeLayerBitInfo, - bool isInActiveLayer, - RAS_ICanvas* canvas, - KX_BlenderSceneConverter* converter - ) -{ - - int executePriority = 0; - int uniqueint = 0; - int count = 0; - bSensor* sens = (bSensor*)blenderobject->sensors.first; - bool pos_pulsemode = false; - bool neg_pulsemode = false; - int skipped_ticks = 0; - bool invert = false; - bool level = false; - bool tap = false; - - while (sens) - { - sens = sens->next; - count++; - } - gameobj->ReserveSensor(count); - sens = (bSensor*)blenderobject->sensors.first; - - while (sens) { - if (!(sens->flag & SENS_DEACTIVATE)) { - SCA_ISensor* gamesensor=NULL; - /* All sensors have a pulse toggle, skipped ticks parameter, and invert field. */ - /* These are extracted here, and set when the sensor is added to the */ - /* list. */ - pos_pulsemode = (sens->pulse & SENS_PULSE_REPEAT)!=0; - neg_pulsemode = (sens->pulse & SENS_NEG_PULSE_MODE)!=0; - - skipped_ticks = sens->freq; - invert = !(sens->invert == 0); - level = !(sens->level == 0); - tap = !(sens->tap == 0); - - switch (sens->type) - { - case SENS_ALWAYS: - { - - SCA_EventManager* eventmgr = logicmgr->FindEventManager(SCA_EventManager::BASIC_EVENTMGR); - if (eventmgr) - { - gamesensor = new SCA_AlwaysSensor(eventmgr, gameobj); - } - - break; - } - - case SENS_DELAY: - { - // we can reuse the Always event manager for the delay sensor - SCA_EventManager* eventmgr = logicmgr->FindEventManager(SCA_EventManager::BASIC_EVENTMGR); - if (eventmgr) - { - bDelaySensor* delaysensor = (bDelaySensor*)sens->data; - gamesensor = new SCA_DelaySensor(eventmgr, - gameobj, - delaysensor->delay, - delaysensor->duration, - (delaysensor->flag & SENS_DELAY_REPEAT) != 0); - } - break; - } - - case SENS_COLLISION: - { - SCA_EventManager* eventmgr = logicmgr->FindEventManager(SCA_EventManager::TOUCH_EVENTMGR); - if (eventmgr) - { - // collision sensor can sense both materials and properties. - - bool bFindMaterial = false, bTouchPulse = false; - - bCollisionSensor* blendertouchsensor = (bCollisionSensor*)sens->data; - - bFindMaterial = (blendertouchsensor->mode & SENS_COLLISION_MATERIAL); - bTouchPulse = (blendertouchsensor->mode & SENS_COLLISION_PULSE); - - - const STR_String touchPropOrMatName = bFindMaterial ? - blendertouchsensor->materialName : blendertouchsensor->name; - - - if (gameobj->GetPhysicsController()) - { - gamesensor = new KX_TouchSensor(eventmgr, - gameobj, - bFindMaterial, - bTouchPulse, - touchPropOrMatName); - } - - } - - break; - } - case SENS_MESSAGE: - { - KX_NetworkEventManager* eventmgr = (KX_NetworkEventManager*) - logicmgr->FindEventManager(SCA_EventManager::NETWORK_EVENTMGR); - if (eventmgr) { - bMessageSensor* msgSens = (bMessageSensor*) sens->data; - - /* Get our NetworkScene */ - NG_NetworkScene *NetworkScene = kxscene->GetNetworkScene(); - /* filter on the incoming subjects, might be empty */ - const STR_String subject = msgSens->subject; - - gamesensor = new KX_NetworkMessageSensor( - eventmgr, // our eventmanager - NetworkScene, // our NetworkScene - gameobj, // the sensor controlling object - subject); // subject to filter on - } - break; - } - case SENS_NEAR: - { - - SCA_EventManager* eventmgr = logicmgr->FindEventManager(SCA_EventManager::TOUCH_EVENTMGR); - if (eventmgr) - { - bNearSensor* blendernearsensor = (bNearSensor*)sens->data; - const STR_String nearpropertyname = (char *)blendernearsensor->name; - - //DT_ShapeHandle shape = DT_Sphere(0.0); - - // this sumoObject is not deleted by a gameobj, so delete it ourself - // later (memleaks)! - float radius = blendernearsensor->dist; - const MT_Vector3& wpos = gameobj->NodeGetWorldPosition(); - bool bFindMaterial = false; - PHY_IPhysicsController* physCtrl = kxscene->GetPhysicsEnvironment()->CreateSphereController(radius,wpos); - - //will be done in KX_TouchEventManager::RegisterSensor() - //if (isInActiveLayer) - // kxscene->GetPhysicsEnvironment()->addSensor(physCtrl); - - - - gamesensor = new KX_NearSensor(eventmgr,gameobj, - blendernearsensor->dist, - blendernearsensor->resetdist, - bFindMaterial, - nearpropertyname, - physCtrl); - - } - break; - } - - - case SENS_KEYBOARD: - { - /* temporary input device, for converting the code for the keyboard sensor */ - - bKeyboardSensor* blenderkeybdsensor = (bKeyboardSensor*)sens->data; - SCA_KeyboardManager* eventmgr = (SCA_KeyboardManager*) logicmgr->FindEventManager(SCA_EventManager::KEYBOARD_EVENTMGR); - if (eventmgr) - { - gamesensor = new SCA_KeyboardSensor(eventmgr, - ConvertKeyCode(blenderkeybdsensor->key), - ConvertKeyCode(blenderkeybdsensor->qual), - ConvertKeyCode(blenderkeybdsensor->qual2), - (blenderkeybdsensor->type == SENS_ALL_KEYS), - blenderkeybdsensor->targetName, - blenderkeybdsensor->toggleName, - gameobj, - KX_KetsjiEngine::GetExitKey()); // blenderkeybdsensor->pad); - - } - - break; - } - case SENS_MOUSE: - { - int keytype = SCA_MouseSensor::KX_MOUSESENSORMODE_NODEF; - int trackfocus = 0; - bMouseSensor *bmouse = (bMouseSensor *)sens->data; - - /* There are two main types of mouse sensors. If there is - * no focus-related behavior requested, we can make do - * with a basic sensor. This cuts down memory usage and - * gives a slight performance gain. */ - - SCA_MouseManager *eventmgr - = (SCA_MouseManager*) logicmgr->FindEventManager(SCA_EventManager::MOUSE_EVENTMGR); - if (eventmgr) { - - /* Determine key mode. There is at most one active mode. */ - switch (bmouse->type) { - case BL_SENS_MOUSE_LEFT_BUTTON: - keytype = SCA_MouseSensor::KX_MOUSESENSORMODE_LEFTBUTTON; - break; - case BL_SENS_MOUSE_MIDDLE_BUTTON: - keytype = SCA_MouseSensor::KX_MOUSESENSORMODE_MIDDLEBUTTON; - break; - case BL_SENS_MOUSE_RIGHT_BUTTON: - keytype = SCA_MouseSensor::KX_MOUSESENSORMODE_RIGHTBUTTON; - break; - case BL_SENS_MOUSE_WHEEL_UP: - keytype = SCA_MouseSensor::KX_MOUSESENSORMODE_WHEELUP; - break; - case BL_SENS_MOUSE_WHEEL_DOWN: - keytype = SCA_MouseSensor::KX_MOUSESENSORMODE_WHEELDOWN; - break; - case BL_SENS_MOUSE_MOVEMENT: - keytype = SCA_MouseSensor::KX_MOUSESENSORMODE_MOVEMENT; - break; - case BL_SENS_MOUSE_MOUSEOVER: - trackfocus = 1; - break; - case BL_SENS_MOUSE_MOUSEOVER_ANY: - trackfocus = 2; - break; - - default: - ; /* error */ - } - - /* initial mouse position */ - int startx = canvas->GetWidth()/2; - int starty = canvas->GetHeight()/2; - - if (!trackfocus) { - /* plain, simple mouse sensor */ - gamesensor = new SCA_MouseSensor(eventmgr, - startx,starty, - keytype, - gameobj); - } else { - /* give us a focus-aware sensor */ - bool bFindMaterial = (bmouse->mode & SENS_COLLISION_MATERIAL); - bool bXRay = (bmouse->flag & SENS_RAY_XRAY); - STR_String checkname = (bFindMaterial? bmouse->matname : bmouse->propname); - - gamesensor = new KX_MouseFocusSensor(eventmgr, - startx, - starty, - keytype, - trackfocus, - (bmouse->flag & SENS_MOUSE_FOCUS_PULSE) ? true:false, - checkname, - bFindMaterial, - bXRay, - kxscene, - kxengine, - gameobj); - } - } else { - // cout << "\n Could't find mouse event manager..."; - should throw an error here... - } - break; - } - case SENS_PROPERTY: - { - bPropertySensor* blenderpropsensor = (bPropertySensor*) sens->data; - SCA_EventManager* eventmgr - = logicmgr->FindEventManager(SCA_EventManager::BASIC_EVENTMGR); - if (eventmgr) - { - STR_String propname=blenderpropsensor->name; - STR_String propval=blenderpropsensor->value; - STR_String propmaxval=blenderpropsensor->maxvalue; - - SCA_PropertySensor::KX_PROPSENSOR_TYPE - propchecktype = SCA_PropertySensor::KX_PROPSENSOR_NODEF; - - /* Better do an explicit conversion here! (was implicit */ - /* before...) */ - switch (blenderpropsensor->type) { - case SENS_PROP_EQUAL: - propchecktype = SCA_PropertySensor::KX_PROPSENSOR_EQUAL; - break; - case SENS_PROP_NEQUAL: - propchecktype = SCA_PropertySensor::KX_PROPSENSOR_NOTEQUAL; - break; - case SENS_PROP_INTERVAL: - propchecktype = SCA_PropertySensor::KX_PROPSENSOR_INTERVAL; - break; - case SENS_PROP_CHANGED: - propchecktype = SCA_PropertySensor::KX_PROPSENSOR_CHANGED; - break; - case SENS_PROP_EXPRESSION: - propchecktype = SCA_PropertySensor::KX_PROPSENSOR_EXPRESSION; - /* error */ - break; - case SENS_PROP_LESSTHAN: - propchecktype = SCA_PropertySensor::KX_PROPSENSOR_LESSTHAN; - break; - case SENS_PROP_GREATERTHAN: - propchecktype = SCA_PropertySensor::KX_PROPSENSOR_GREATERTHAN; - break; - default: - ; /* error */ - } - gamesensor = new SCA_PropertySensor(eventmgr,gameobj,propname,propval,propmaxval,propchecktype); - } - - break; - } - case SENS_ACTUATOR: - { - bActuatorSensor* blenderactsensor = (bActuatorSensor*) sens->data; - // we will reuse the property event manager, there is nothing special with this sensor - SCA_EventManager* eventmgr - = logicmgr->FindEventManager(SCA_EventManager::ACTUATOR_EVENTMGR); - if (eventmgr) - { - STR_String propname=blenderactsensor->name; - gamesensor = new SCA_ActuatorSensor(eventmgr,gameobj,propname); - } - break; - } - - case SENS_ARMATURE: - { - bArmatureSensor* blenderarmsensor = (bArmatureSensor*) sens->data; - // we will reuse the property event manager, there is nothing special with this sensor - SCA_EventManager* eventmgr - = logicmgr->FindEventManager(SCA_EventManager::BASIC_EVENTMGR); - if (eventmgr) - { - STR_String bonename=blenderarmsensor->posechannel; - STR_String constraintname=blenderarmsensor->constraint; - gamesensor = new KX_ArmatureSensor(eventmgr,gameobj,bonename,constraintname, blenderarmsensor->type, blenderarmsensor->value); - } - break; - } - - case SENS_RADAR: - { - - SCA_EventManager* eventmgr = logicmgr->FindEventManager(SCA_EventManager::TOUCH_EVENTMGR); - if (eventmgr) - { - bRadarSensor* blenderradarsensor = (bRadarSensor*) sens->data; - const STR_String radarpropertyname = blenderradarsensor->name; - - int radaraxis = blenderradarsensor->axis; - - MT_Scalar coneheight = blenderradarsensor->range; - - // janco: the angle was doubled, so should I divide the factor in 2 - // or the blenderradarsensor->angle? - // nzc: the angle is the opening angle. We need to init with - // the axis-hull angle,so /2.0. - MT_Scalar factor = tan(blenderradarsensor->angle * 0.5f); - //MT_Scalar coneradius = coneheight * (factor / 2); - MT_Scalar coneradius = coneheight * factor; - - - // this sumoObject is not deleted by a gameobj, so delete it ourself - // later (memleaks)! - MT_Scalar smallmargin = 0.0; - MT_Scalar largemargin = 0.0; - - bool bFindMaterial = false; - PHY_IPhysicsController* ctrl = kxscene->GetPhysicsEnvironment()->CreateConeController((float)coneradius, (float)coneheight); - - gamesensor = new KX_RadarSensor( - eventmgr, - gameobj, - ctrl, - coneradius, - coneheight, - radaraxis, - smallmargin, - largemargin, - bFindMaterial, - radarpropertyname); - - } - - break; - } - case SENS_RAY: - { - bRaySensor* blenderraysensor = (bRaySensor*) sens->data; - - //blenderradarsensor->angle; - SCA_EventManager* eventmgr = logicmgr->FindEventManager(SCA_EventManager::BASIC_EVENTMGR); - if (eventmgr) - { - bool bFindMaterial = (blenderraysensor->mode & SENS_COLLISION_MATERIAL); - bool bXRay = (blenderraysensor->mode & SENS_RAY_XRAY); - - STR_String checkname = (bFindMaterial? blenderraysensor->matname : blenderraysensor->propname); - - // don't want to get rays of length 0.0 or so - double distance = (blenderraysensor->range < 0.01f ? 0.01f : blenderraysensor->range); - int axis = blenderraysensor->axisflag; - - - gamesensor = new KX_RaySensor(eventmgr, - gameobj, - checkname, - bFindMaterial, - bXRay, - distance, - axis, - kxscene); - - } - break; - } - - case SENS_RANDOM: - { - bRandomSensor* blenderrndsensor = (bRandomSensor*) sens->data; - // some files didn't write randomsensor, avoid crash now for NULL ptr's - if (blenderrndsensor) - { - SCA_EventManager* eventmgr = logicmgr->FindEventManager(SCA_EventManager::BASIC_EVENTMGR); - if (eventmgr) - { - int randomSeed = blenderrndsensor->seed; - if (randomSeed == 0) - { - randomSeed = (int)(kxengine->GetRealTime()*100000.0); - randomSeed ^= (intptr_t)blenderrndsensor; - } - gamesensor = new SCA_RandomSensor(eventmgr, gameobj, randomSeed); - } - } - break; - } - case SENS_JOYSTICK: - { - int joysticktype = SCA_JoystickSensor::KX_JOYSENSORMODE_NODEF; - - bJoystickSensor* bjoy = (bJoystickSensor*) sens->data; - - SCA_JoystickManager *eventmgr - = (SCA_JoystickManager*) logicmgr->FindEventManager(SCA_EventManager::JOY_EVENTMGR); - if (eventmgr) - { - int axis =0; - int axisf =0; - int button =0; - int hat =0; - int hatf =0; - int prec =0; - - switch (bjoy->type) { - case SENS_JOY_AXIS: - axis = bjoy->axis; - axisf = bjoy->axisf; - prec = bjoy->precision; - joysticktype = SCA_JoystickSensor::KX_JOYSENSORMODE_AXIS; - break; - case SENS_JOY_BUTTON: - button = bjoy->button; - joysticktype = SCA_JoystickSensor::KX_JOYSENSORMODE_BUTTON; - break; - case SENS_JOY_HAT: - hat = bjoy->hat; - hatf = bjoy->hatf; - joysticktype = SCA_JoystickSensor::KX_JOYSENSORMODE_HAT; - break; - case SENS_JOY_AXIS_SINGLE: - axis = bjoy->axis_single; - prec = bjoy->precision; - joysticktype = SCA_JoystickSensor::KX_JOYSENSORMODE_AXIS_SINGLE; - break; - default: - printf("Error: bad case statement\n"); - break; - } - gamesensor = new SCA_JoystickSensor( - eventmgr, - gameobj, - bjoy->joyindex, - joysticktype, - axis,axisf, - prec, - button, - hat,hatf, - (bjoy->flag & SENS_JOY_ANY_EVENT)); - } - else - { - printf("Error there was a problem finding the event manager\n"); - } - - break; - } - default: - { - } - } - - if (gamesensor) - { - gamesensor->SetExecutePriority(executePriority++); - STR_String uniquename = sens->name; - uniquename += "#SENS#"; - uniqueint++; - CIntValue* uniqueval = new CIntValue(uniqueint); - uniquename += uniqueval->GetText(); - uniqueval->Release(); - - /* Conversion succeeded, so we can set the generic props here. */ - gamesensor->SetPulseMode(pos_pulsemode, - neg_pulsemode, - skipped_ticks); - gamesensor->SetInvert(invert); - gamesensor->SetLevel(level); - gamesensor->SetTap(tap); - gamesensor->SetName(sens->name); - gamesensor->SetLogicManager(logicmgr); - - gameobj->AddSensor(gamesensor); - - // only register to manager if it's in an active layer - // Make registration dynamic: only when sensor is activated - //if (isInActiveLayer) - // gamesensor->RegisterToManager(); - - gamesensor->ReserveController(sens->totlinks); - for (int i=0;itotlinks;i++) - { - bController* linkedcont = (bController*) sens->links[i]; - if (linkedcont) { - // If the controller is deactived doesn't register it - if (!(linkedcont->flag & CONT_DEACTIVATE)) { - SCA_IController* gamecont = converter->FindGameController(linkedcont); - - if (gamecont) { - logicmgr->RegisterToSensor(gamecont,gamesensor); - } - else { - printf("Warning, sensor \"%s\" could not find its controller " - "(link %d of %d) from object \"%s\"\n" - "\tthere has been an error converting the blender controller for the game engine," - "logic may be incorrect\n", sens->name, i+1, sens->totlinks, blenderobject->id.name+2); - } - } - } - else { - printf("Warning, sensor \"%s\" has lost a link to a controller " - "(link %d of %d) from object \"%s\"\n" - "\tpossible causes are partially appended objects or an error reading the file," - "logic may be incorrect\n", sens->name, i+1, sens->totlinks, blenderobject->id.name+2); - } - } - // special case: Keyboard sensor with no link - // this combination is usually used for key logging. - if (sens->type == SENS_KEYBOARD && sens->totlinks == 0) { - // Force the registration so that the sensor runs - gamesensor->IncLink(); - } - - // done with gamesensor - gamesensor->Release(); - - } - } - - sens=sens->next; - } -} - diff --git a/source/gameengine/Converter/KX_ConvertSensors.h b/source/gameengine/Converter/KX_ConvertSensors.h deleted file mode 100644 index 56248721a37..00000000000 --- a/source/gameengine/Converter/KX_ConvertSensors.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_ConvertSensors.h - * \ingroup bgeconv - */ - -#ifndef __KX_CONVERTSENSORS_H__ -#define __KX_CONVERTSENSORS_H__ - -void BL_ConvertSensors(struct Object* blenderobject, - class KX_GameObject* gameobj, - class SCA_LogicManager* logicmgr, - class KX_Scene* kxscene, - class KX_KetsjiEngine* kxengine, - int activeLayerBitInfo, - bool isInActiveLayer, - class RAS_ICanvas* canvas, - class KX_BlenderSceneConverter* converter); - -#endif /* __KX_CONVERTSENSORS_H__ */ diff --git a/source/gameengine/Converter/KX_LibLoadStatus.cpp b/source/gameengine/Converter/KX_LibLoadStatus.cpp deleted file mode 100644 index 66fcd998269..00000000000 --- a/source/gameengine/Converter/KX_LibLoadStatus.cpp +++ /dev/null @@ -1,255 +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 KX_LibLoadStatus.cpp - * \ingroup bgeconv - */ - -#include "KX_LibLoadStatus.h" -#include "PIL_time.h" - -KX_LibLoadStatus::KX_LibLoadStatus(class KX_BlenderSceneConverter* kx_converter, - class KX_KetsjiEngine* kx_engine, - class KX_Scene* merge_scene, - const char *path) : - m_converter(kx_converter), - m_engine(kx_engine), - m_mergescene(merge_scene), - m_data(NULL), - m_libname(path), - m_progress(0.0f), - m_finished(false) -#ifdef WITH_PYTHON - , - m_finish_cb(NULL), - m_progress_cb(NULL) -#endif -{ - m_endtime = m_starttime = PIL_check_seconds_timer(); -} - -void KX_LibLoadStatus::Finish() -{ - m_finished = true; - m_progress = 1.f; - m_endtime = PIL_check_seconds_timer(); - - RunFinishCallback(); - RunProgressCallback(); -} - -void KX_LibLoadStatus::RunFinishCallback() -{ -#ifdef WITH_PYTHON - if (m_finish_cb) { - PyObject* args = Py_BuildValue("(O)", GetProxy()); - - if (!PyObject_Call(m_finish_cb, args, NULL)) { - PyErr_Print(); - PyErr_Clear(); - } - - Py_DECREF(args); - } -#endif -} - -void KX_LibLoadStatus::RunProgressCallback() -{ -// Progess callbacks are causing threading problems with Python, so they're disabled for now -#if 0 -#ifdef WITH_PYTHON - if (m_progress_cb) { - //PyGILState_STATE gstate = PyGILState_Ensure(); - PyObject* args = Py_BuildValue("(O)", GetProxy()); - - if (!PyObject_Call(m_progress_cb, args, NULL)) { - PyErr_Print(); - PyErr_Clear(); - } - - Py_DECREF(args); - //PyGILState_Release(gstate); - } -#endif -#endif -} - -class KX_BlenderSceneConverter *KX_LibLoadStatus::GetConverter() -{ - return m_converter; -} - -class KX_KetsjiEngine *KX_LibLoadStatus::GetEngine() -{ - return m_engine; -} - -class KX_Scene *KX_LibLoadStatus::GetMergeScene() -{ - return m_mergescene; -} - -void KX_LibLoadStatus::SetLibName(const char *name) -{ - m_libname = name; -} - -const char *KX_LibLoadStatus::GetLibName() -{ - return m_libname; -} - -void KX_LibLoadStatus::SetData(void *data) -{ - m_data = data; -} - -void *KX_LibLoadStatus::GetData() -{ - return m_data; -} - -void KX_LibLoadStatus::SetProgress(float progress) -{ - m_progress = progress; - RunProgressCallback(); -} - -float KX_LibLoadStatus::GetProgress() -{ - return m_progress; -} - -void KX_LibLoadStatus::AddProgress(float progress) -{ - m_progress += progress; - RunProgressCallback(); -} - -#ifdef WITH_PYTHON - -PyMethodDef KX_LibLoadStatus::Methods[] = -{ - {NULL} //Sentinel -}; - -PyAttributeDef KX_LibLoadStatus::Attributes[] = { - KX_PYATTRIBUTE_RW_FUNCTION("onFinish", KX_LibLoadStatus, pyattr_get_onfinish, pyattr_set_onfinish), - // KX_PYATTRIBUTE_RW_FUNCTION("onProgress", KX_LibLoadStatus, pyattr_get_onprogress, pyattr_set_onprogress), - KX_PYATTRIBUTE_FLOAT_RO("progress", KX_LibLoadStatus, m_progress), - KX_PYATTRIBUTE_STRING_RO("libraryName", KX_LibLoadStatus, m_libname), - KX_PYATTRIBUTE_RO_FUNCTION("timeTaken", KX_LibLoadStatus, pyattr_get_timetaken), - KX_PYATTRIBUTE_BOOL_RO("finished", KX_LibLoadStatus, m_finished), - { NULL } //Sentinel -}; - -PyTypeObject KX_LibLoadStatus::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "KX_LibLoadStatus", - 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_LibLoadStatus::pyattr_get_onfinish(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_LibLoadStatus* self = static_cast(self_v); - - if (self->m_finish_cb) { - Py_INCREF(self->m_finish_cb); - return self->m_finish_cb; - } - - Py_RETURN_NONE; -} - -int KX_LibLoadStatus::pyattr_set_onfinish(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_LibLoadStatus* self = static_cast(self_v); - - if (!PyCallable_Check(value)) { - PyErr_SetString(PyExc_TypeError, "KX_LibLoadStatus.onFinished requires a callable object"); - return PY_SET_ATTR_FAIL; - } - - if (self->m_finish_cb) - Py_DECREF(self->m_finish_cb); - - Py_INCREF(value); - self->m_finish_cb = value; - - return PY_SET_ATTR_SUCCESS; -} - -PyObject* KX_LibLoadStatus::pyattr_get_onprogress(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_LibLoadStatus* self = static_cast(self_v); - - if (self->m_progress_cb) { - Py_INCREF(self->m_progress_cb); - return self->m_progress_cb; - } - - Py_RETURN_NONE; -} - -int KX_LibLoadStatus::pyattr_set_onprogress(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - KX_LibLoadStatus* self = static_cast(self_v); - - if (!PyCallable_Check(value)) { - PyErr_SetString(PyExc_TypeError, "KX_LibLoadStatus.onProgress requires a callable object"); - return PY_SET_ATTR_FAIL; - } - - if (self->m_progress_cb) - Py_DECREF(self->m_progress_cb); - - Py_INCREF(value); - self->m_progress_cb = value; - - return PY_SET_ATTR_SUCCESS; -} - -PyObject* KX_LibLoadStatus::pyattr_get_timetaken(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - KX_LibLoadStatus* self = static_cast(self_v); - - return PyFloat_FromDouble(self->m_endtime - self->m_starttime); -} -#endif // WITH_PYTHON diff --git a/source/gameengine/Converter/KX_LibLoadStatus.h b/source/gameengine/Converter/KX_LibLoadStatus.h deleted file mode 100644 index fd51bfddd85..00000000000 --- a/source/gameengine/Converter/KX_LibLoadStatus.h +++ /dev/null @@ -1,93 +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 KX_LibLoadStatus.h - * \ingroup bgeconv - */ - -#ifndef __KX_LIBLOADSTATUS_H__ -#define __KX_LIBLOADSTATUS_H__ - -#include "EXP_PyObjectPlus.h" - -class KX_LibLoadStatus : public PyObjectPlus -{ - Py_Header -private: - class KX_BlenderSceneConverter* m_converter; - class KX_KetsjiEngine* m_engine; - class KX_Scene* m_mergescene; - void* m_data; - STR_String m_libname; - - float m_progress; - double m_starttime; - double m_endtime; - - // The current status of this libload, used by the scene converter. - bool m_finished; - -#ifdef WITH_PYTHON - PyObject* m_finish_cb; - PyObject* m_progress_cb; -#endif - -public: - KX_LibLoadStatus(class KX_BlenderSceneConverter* kx_converter, - class KX_KetsjiEngine* kx_engine, - class KX_Scene* merge_scene, - const char *path); - - void Finish(); // Called when the libload is done - void RunFinishCallback(); - void RunProgressCallback(); - - class KX_BlenderSceneConverter *GetConverter(); - class KX_KetsjiEngine *GetEngine(); - class KX_Scene *GetMergeScene(); - - void SetLibName(const char *name); - const char *GetLibName(); - - void SetData(void *data); - void *GetData(); - - inline bool IsFinished() const - { - return m_finished; - } - - void SetProgress(float progress); - float GetProgress(); - void AddProgress(float progress); - -#ifdef WITH_PYTHON - static PyObject* pyattr_get_onfinish(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_onfinish(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - static PyObject* pyattr_get_onprogress(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_onprogress(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - - static PyObject* pyattr_get_timetaken(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); -#endif -}; - -#endif // __KX_LIBLOADSTATUS_H__ diff --git a/source/gameengine/Converter/KX_SoftBodyDeformer.cpp b/source/gameengine/Converter/KX_SoftBodyDeformer.cpp deleted file mode 100644 index 877aebff556..00000000000 --- a/source/gameengine/Converter/KX_SoftBodyDeformer.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 ***** - */ - -/** \file gameengine/Converter/KX_SoftBodyDeformer.cpp - * \ingroup bgeconv - */ - - -#ifdef _MSC_VER -# pragma warning (disable:4786) -#endif //WIN32 - -#include "MT_assert.h" - -#include "KX_SoftBodyDeformer.h" -#include "RAS_MeshObject.h" -#include "CTR_Map.h" -#include "CTR_HashedPtr.h" - -#ifdef WITH_BULLET - -#include "CcdPhysicsEnvironment.h" -#include "CcdPhysicsController.h" -#include "BulletSoftBody/btSoftBody.h" - -#include "btBulletDynamicsCommon.h" - -void KX_SoftBodyDeformer::Relink(CTR_Map*map) -{ - void **h_obj = (*map)[m_gameobj]; - - if (h_obj) { - m_gameobj = (BL_DeformableGameObject*)(*h_obj); - m_pMeshObject = m_gameobj->GetMesh(0); - } else { - m_gameobj = NULL; - m_pMeshObject = NULL; - } -} - -bool KX_SoftBodyDeformer::Apply(class RAS_IPolyMaterial *polymat) -{ - CcdPhysicsController* ctrl = (CcdPhysicsController*) m_gameobj->GetPhysicsController(); - if (!ctrl) - return false; - - btSoftBody* softBody= ctrl->GetSoftBody(); - if (!softBody) - return false; - - //printf("apply\n"); - RAS_MeshSlot::iterator it; - RAS_MeshMaterial *mmat; - RAS_MeshSlot *slot; - size_t i; - - // update the vertex in m_transverts - Update(); - - // The vertex cache can only be updated for this deformer: - // Duplicated objects with more than one ploymaterial (=multiple mesh slot per object) - // share the same mesh (=the same cache). As the rendering is done per polymaterial - // cycling through the objects, the entire mesh cache cannot be updated in one shot. - mmat = m_pMeshObject->GetMeshMaterial(polymat); - if (!mmat->m_slots[(void*)m_gameobj]) - return true; - - slot = *mmat->m_slots[(void*)m_gameobj]; - - // for each array - for (slot->begin(it); !slot->end(it); slot->next(it)) - { - btSoftBody::tNodeArray& nodes(softBody->m_nodes); - - int index = 0; - for (i=it.startvertex; i= 0); - - MT_Point3 pt ( - nodes[v.getSoftBodyIndex()].m_x.getX(), - nodes[v.getSoftBodyIndex()].m_x.getY(), - nodes[v.getSoftBodyIndex()].m_x.getZ()); - v.SetXYZ(pt); - - MT_Vector3 normal ( - nodes[v.getSoftBodyIndex()].m_n.getX(), - nodes[v.getSoftBodyIndex()].m_n.getY(), - nodes[v.getSoftBodyIndex()].m_n.getZ()); - v.SetNormal(normal); - - } - } - return true; -} - -#endif diff --git a/source/gameengine/Converter/KX_SoftBodyDeformer.h b/source/gameengine/Converter/KX_SoftBodyDeformer.h deleted file mode 100644 index d7bc088e1c0..00000000000 --- a/source/gameengine/Converter/KX_SoftBodyDeformer.h +++ /dev/null @@ -1,102 +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_SoftBodyDeformer.h - * \ingroup bgeconv - */ - -#ifndef __KX_SOFTBODYDEFORMER_H__ -#define __KX_SOFTBODYDEFORMER_H__ - -#ifdef _MSC_VER -# pragma warning (disable:4786) /* get rid of stupid stl-visual compiler debug warning */ -#endif - -#include "RAS_Deformer.h" -#include "BL_DeformableGameObject.h" -#include - - -class KX_SoftBodyDeformer : public RAS_Deformer -{ - class RAS_MeshObject* m_pMeshObject; - class BL_DeformableGameObject* m_gameobj; - -public: - KX_SoftBodyDeformer(RAS_MeshObject* pMeshObject,BL_DeformableGameObject* gameobj) - :m_pMeshObject(pMeshObject), - m_gameobj(gameobj) - { - //printf("KX_SoftBodyDeformer\n"); - }; - - virtual ~KX_SoftBodyDeformer() - { - //printf("~KX_SoftBodyDeformer\n"); - }; - virtual void Relink(CTR_Map*map); - virtual bool Apply(class RAS_IPolyMaterial *polymat); - virtual bool Update(void) - { - //printf("update\n"); - m_bDynamic = true; - return true;//?? - } - virtual bool UpdateBuckets(void) - { - // this is to update the mesh slots outside the rasterizer, - // no need to do it for this deformer, it's done in any case in Apply() - return false; - } - - virtual RAS_Deformer *GetReplica() - { - KX_SoftBodyDeformer* deformer = new KX_SoftBodyDeformer(*this); - deformer->ProcessReplica(); - return deformer; - } - virtual void ProcessReplica() - { - // we have two pointers to deal with but we cannot do it now, will be done in Relink - m_bDynamic = false; - } - virtual bool SkipVertexTransform() - { - return true; - } - -protected: - //class RAS_MeshObject *m_pMesh; - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:BL_ShapeDeformer") -#endif -}; - - -#endif - diff --git a/source/gameengine/Expressions/CMakeLists.txt b/source/gameengine/Expressions/CMakeLists.txt deleted file mode 100644 index 9c563a46ea2..00000000000 --- a/source/gameengine/Expressions/CMakeLists.txt +++ /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) 2006, Blender Foundation -# All rights reserved. -# -# The Original Code is: all of this file. -# -# Contributor(s): Jacques Beaurain. -# -# ***** END GPL LICENSE BLOCK ***** - -set(INC - . - ../SceneGraph - ../../blender/blenlib - ../../../intern/guardedalloc - ../../../intern/string -) - -set(INC_SYS - ../../../intern/moto/include -) - -set(SRC - intern/BoolValue.cpp - intern/ConstExpr.cpp - intern/EmptyValue.cpp - intern/ErrorValue.cpp - intern/Expression.cpp - intern/FloatValue.cpp - intern/IdentifierExpr.cpp - intern/IfExpr.cpp - intern/InputParser.cpp - intern/IntValue.cpp - intern/HashedPtr.cpp - intern/ListValue.cpp - intern/Operator1Expr.cpp - intern/Operator2Expr.cpp - intern/PyObjectPlus.cpp - intern/StringValue.cpp - intern/Value.cpp - intern/VectorValue.cpp - intern/ListWrapper.cpp - - EXP_BoolValue.h - EXP_ConstExpr.h - EXP_EmptyValue.h - EXP_ErrorValue.h - EXP_Expression.h - EXP_FloatValue.h - EXP_HashedPtr.h - EXP_IdentifierExpr.h - EXP_IfExpr.h - EXP_InputParser.h - EXP_IntValue.h - EXP_ListValue.h - EXP_Operator1Expr.h - EXP_Operator2Expr.h - EXP_PyObjectPlus.h - EXP_Python.h - EXP_StringValue.h - EXP_Value.h - EXP_VectorValue.h - EXP_VoidValue.h - EXP_ListWrapper.h - -) - -if(WITH_PYTHON) - list(APPEND SRC - intern/PythonCallBack.cpp - - EXP_PythonCallBack.h - ) -endif() - -blender_add_lib(ge_logic_expressions "${SRC}" "${INC}" "${INC_SYS}") diff --git a/source/gameengine/Expressions/EXP_BoolValue.h b/source/gameengine/Expressions/EXP_BoolValue.h deleted file mode 100644 index 98ba1d75e52..00000000000 --- a/source/gameengine/Expressions/EXP_BoolValue.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * BoolValue.h: interface for the CBoolValue class. - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -/** \file EXP_BoolValue.h - * \ingroup expressions - */ - -#ifndef __EXP_BOOLVALUE_H__ -#define __EXP_BOOLVALUE_H__ - -#include "EXP_Value.h" - -/** - * Smart Boolean Value class. - * Is used by parser when an expression tree is build containing booleans. - */ - -class CBoolValue : public CPropValue -{ - - //PLUGIN_DECLARE_SERIAL(CBoolValue,CValue) - -public: - static const STR_String sTrueString; - static const STR_String sFalseString; - - CBoolValue(); - CBoolValue(bool inBool); - CBoolValue(bool innie, const char *name, AllocationTYPE alloctype = CValue::HEAPVALUE); - - virtual const STR_String& GetText(); - virtual double GetNumber(); - virtual int GetValueType(); - bool GetBool(); - virtual void SetValue(CValue* newval); - - virtual CValue* Calc(VALUE_OPERATOR op, CValue *val); - virtual CValue* CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val); - - void Configure(CValue* menuvalue); - virtual CValue* GetReplica(); -#ifdef WITH_PYTHON - virtual PyObject* ConvertValueToPython(); -#endif - -private: - bool m_bool; - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:CBoolValue") -#endif -}; - -#endif /* __EXP_BOOLVALUE_H__ */ diff --git a/source/gameengine/Expressions/EXP_ConstExpr.h b/source/gameengine/Expressions/EXP_ConstExpr.h deleted file mode 100644 index b4456dacdf3..00000000000 --- a/source/gameengine/Expressions/EXP_ConstExpr.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * ConstExpr.h: interface for the CConstExpr class. - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -/** \file EXP_ConstExpr.h - * \ingroup expressions - */ - -#ifndef __EXP_CONSTEXPR_H__ -#define __EXP_CONSTEXPR_H__ - -#include "EXP_Expression.h" -#include "EXP_Value.h" // Added by ClassView - -class CConstExpr : public CExpression -{ - //PLUGIN_DECLARE_SERIAL_EXPRESSION (CConstExpr,CExpression) -public: - virtual bool MergeExpression(CExpression* otherexpr); - - void BroadcastOperators(VALUE_OPERATOR op); - - virtual unsigned char GetExpressionID(); - CExpression* CheckLink(std::vector& brokenlinks); - //bool IsInside(float x,float y,float z,bool bBorderInclude=true); - bool NeedsRecalculated(); - void ClearModified(); - virtual double GetNumber(); - virtual CValue* Calculate(); - CConstExpr(CValue* constval); - CConstExpr(); - virtual ~CConstExpr(); - - -private: - CValue* m_value; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:CConstExpr") -#endif -}; - -#endif /* __EXP_CONSTEXPR_H__ */ diff --git a/source/gameengine/Expressions/EXP_EmptyValue.h b/source/gameengine/Expressions/EXP_EmptyValue.h deleted file mode 100644 index d23addb9f9f..00000000000 --- a/source/gameengine/Expressions/EXP_EmptyValue.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * EmptyValue.h: interface for the CEmptyValue class. - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -/** \file EXP_EmptyValue.h - * \ingroup expressions - */ - -#ifndef __EXP_EMPTYVALUE_H__ -#define __EXP_EMPTYVALUE_H__ - -#include "EXP_Value.h" - -class CListValue; - -class CEmptyValue : public CPropValue -{ - //PLUGIN_DECLARE_SERIAL (CEmptyValue,CValue) -public: - CEmptyValue(); - virtual ~CEmptyValue(); - - virtual const STR_String & GetText(); - virtual double GetNumber(); - virtual int GetValueType(); - CListValue* GetPolySoup(); - virtual double* GetVector3(bool bGetTransformedVec=false); - bool IsInside(CValue* testpoint,bool bBorderInclude=true); - CValue * Calc(VALUE_OPERATOR op, CValue *val); - CValue * CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val); - virtual CValue* GetReplica(); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:CEmptyValue") -#endif -}; - -#endif /* __EXP_EMPTYVALUE_H__ */ diff --git a/source/gameengine/Expressions/EXP_ErrorValue.h b/source/gameengine/Expressions/EXP_ErrorValue.h deleted file mode 100644 index a6f91ca200a..00000000000 --- a/source/gameengine/Expressions/EXP_ErrorValue.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - * ErrorValue.h: interface for the CErrorValue class. - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -/** \file EXP_ErrorValue.h - * \ingroup expressions - */ - -#ifndef __EXP_ERRORVALUE_H__ -#define __EXP_ERRORVALUE_H__ - -#include "EXP_Value.h" - -class CErrorValue : public CPropValue -{ - -public: - virtual const STR_String & GetText(); - virtual double GetNumber(); - virtual int GetValueType(); - CErrorValue(); - CErrorValue(const char *errmsg); - virtual ~CErrorValue(); - virtual CValue* Calc(VALUE_OPERATOR op, CValue* val); - virtual CValue* CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val); - virtual CValue* GetReplica(); - -private: - STR_String m_strErrorText; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:CErrorValue") -#endif -}; - -#endif /* __EXP_ERRORVALUE_H__ */ diff --git a/source/gameengine/Expressions/EXP_Expression.h b/source/gameengine/Expressions/EXP_Expression.h deleted file mode 100644 index 66a6e9476ff..00000000000 --- a/source/gameengine/Expressions/EXP_Expression.h +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Expression.h: interface for the CExpression class. - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -/** \file EXP_Expression.h - * \ingroup expressions - */ - -#ifndef __EXP_EXPRESSION_H__ -#define __EXP_EXPRESSION_H__ - -#include "EXP_Value.h" - -//extern int gRefCountExpr; // only for debugging purposes (detect mem.leaks) - - -#define PLUGIN_DECLARE_SERIAL_EXPRESSION(class_name, base_class_name) \ -public: \ - virtual base_class_name * Copy() { \ - return new class_name; \ - } \ - virtual bool EdSerialize(CompressorArchive& arch, \ - class CFactoryManager* facmgr, \ - bool bIsStoring); \ - virtual bool EdIdSerialize(CompressorArchive& arch, \ - class CFactoryManager* facmgr, \ - bool bIsStoring) \ - { \ - if (bIsStoring) \ - { \ - unsigned char exprID = GetExpressionID(); \ - arch << exprID; \ - } \ - return true; \ - } \ - - - -class CExpression; - - -// for undo/redo system the deletion in the expressiontree can be restored by replacing broken links 'inplace' -class CBrokenLinkInfo -{ - public: - CBrokenLinkInfo(CExpression** pmemexpr,CExpression* expr) - :m_pmemExpr(pmemexpr), - m_pExpr(expr) - { - assertd(pmemexpr); - m_bRestored=false; - }; - - virtual ~CBrokenLinkInfo(); - void RestoreLink(); - void BreakLink(); - - - // members vars - private: - CExpression** m_pmemExpr; - CExpression* m_pExpr; - bool m_bRestored; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:CBrokenLinkInfo") -#endif -}; - - - - - - - - -class CExpression -{ -public: - enum { - COPERATOR1EXPRESSIONID = 1, - COPERATOR2EXPRESSIONID = 2, - CCONSTEXPRESSIONID = 3, - CIFEXPRESSIONID = 4, - COPERATORVAREXPRESSIONID = 5, - CIDENTIFIEREXPRESSIONID = 6 - }; - - -protected: - virtual ~CExpression() = 0; //pure virtual -public: - virtual bool MergeExpression(CExpression* otherexpr) = 0; - CExpression(); - - - virtual CValue* Calculate() = 0; //pure virtual - virtual unsigned char GetExpressionID() = 0; - //virtual bool IsInside(float x,float y,float z,bool bBorderInclude=true) = 0; //pure virtual - virtual bool NeedsRecalculated() = 0; // another pure one - virtual CExpression * CheckLink(std::vector& brokenlinks) =0; // another pure one - virtual void ClearModified() = 0; // another pure one - //virtual CExpression * Copy() =0; - virtual void BroadcastOperators(VALUE_OPERATOR op) =0; - - virtual CExpression * AddRef() { // please leave multiline, for debugger !!! - -#ifdef DEBUG - //gRefCountExpr++; - assertd(m_refcount < 255); -#endif - m_refcount++; - return this; - }; - virtual CExpression* Release(CExpression* complicatedtrick=NULL) { -#ifdef DEBUG - //gRefCountExpr--; -#endif - if (--m_refcount < 1) - { - delete this; - } //else - // return this; - return complicatedtrick; - }; - - -protected: - - int m_refcount; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:CExpression") -#endif -}; - -#endif /* __EXP_EXPRESSION_H__ */ diff --git a/source/gameengine/Expressions/EXP_FloatValue.h b/source/gameengine/Expressions/EXP_FloatValue.h deleted file mode 100644 index 3c16c57d16d..00000000000 --- a/source/gameengine/Expressions/EXP_FloatValue.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - * FloatValue.h: interface for the CFloatValue class. - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -/** \file EXP_FloatValue.h - * \ingroup expressions - */ - -#ifndef __EXP_FLOATVALUE_H__ -#define __EXP_FLOATVALUE_H__ - -#include "EXP_Value.h" - -class CFloatValue : public CPropValue -{ - //PLUGIN_DECLARE_SERIAL (CFloatValue,CValue) -public: - CFloatValue(); - CFloatValue(float fl); - CFloatValue(float fl,const char *name,AllocationTYPE alloctype=CValue::HEAPVALUE); - - virtual const STR_String & GetText(); - - void Configure(CValue* menuvalue); - virtual double GetNumber(); - virtual int GetValueType(); - virtual void SetValue(CValue* newval); - float GetFloat(); - void SetFloat(float fl); - virtual ~CFloatValue(); - virtual CValue* GetReplica(); - virtual CValue* Calc(VALUE_OPERATOR op, CValue *val); - virtual CValue* CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val); -#ifdef WITH_PYTHON - virtual PyObject* ConvertValueToPython(); -#endif - -protected: - float m_float; - STR_String* m_pstrRep; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:CFloatValue") -#endif -}; - -#endif /* __EXP_FLOATVALUE_H__ */ diff --git a/source/gameengine/Expressions/EXP_HashedPtr.h b/source/gameengine/Expressions/EXP_HashedPtr.h deleted file mode 100644 index 7c7c5f6e5ec..00000000000 --- a/source/gameengine/Expressions/EXP_HashedPtr.h +++ /dev/null @@ -1,59 +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 EXP_HashedPtr.h - * \ingroup expressions - */ - -#ifndef __EXP_HASHEDPTR_H__ -#define __EXP_HASHEDPTR_H__ - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -class CHashedPtr -{ - void* m_valptr; - -public: - CHashedPtr(void* val); - - unsigned int hash() const; - - inline friend bool operator ==( const CHashedPtr & rhs,const CHashedPtr & lhs) - { - return rhs.m_valptr == lhs.m_valptr; - } - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:CHashedPtr") -#endif -}; - -#endif /* __EXP_HASHEDPTR_H__ */ diff --git a/source/gameengine/Expressions/EXP_IdentifierExpr.h b/source/gameengine/Expressions/EXP_IdentifierExpr.h deleted file mode 100644 index 96ef3677cf3..00000000000 --- a/source/gameengine/Expressions/EXP_IdentifierExpr.h +++ /dev/null @@ -1,59 +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 EXP_IdentifierExpr.h - * \ingroup expressions - */ - -#ifndef __EXP_IDENTIFIEREXPR_H__ -#define __EXP_IDENTIFIEREXPR_H__ - -#include "EXP_Expression.h" - -class CIdentifierExpr : public CExpression -{ - CValue* m_idContext; - STR_String m_identifier; -public: - CIdentifierExpr(const STR_String& identifier,CValue* id_context); - virtual ~CIdentifierExpr(); - - virtual CValue* Calculate(); - virtual bool MergeExpression(CExpression* otherexpr); - virtual unsigned char GetExpressionID(); - virtual bool NeedsRecalculated(); - virtual CExpression* CheckLink(std::vector& brokenlinks); - virtual void ClearModified(); - virtual void BroadcastOperators(VALUE_OPERATOR op); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:CIdentifierExpr") -#endif -}; - -#endif /* __EXP_IDENTIFIEREXPR_H__ */ diff --git a/source/gameengine/Expressions/EXP_IfExpr.h b/source/gameengine/Expressions/EXP_IfExpr.h deleted file mode 100644 index 43b4b8faf53..00000000000 --- a/source/gameengine/Expressions/EXP_IfExpr.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * IfExpr.h: interface for the CIfExpr class. - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -/** \file EXP_IfExpr.h - * \ingroup expressions - */ - -#ifndef __EXP_IFEXPR_H__ -#define __EXP_IFEXPR_H__ - -#include "EXP_Expression.h" - -class CIfExpr : public CExpression -{ - //PLUGIN_DECLARE_SERIAL_EXPRESSION (CIfExpr,CExpression) - -private: - CExpression *m_guard, *m_e1, *m_e2; - -public: - virtual bool MergeExpression(CExpression* otherexpr); - CIfExpr(CExpression *guard, CExpression *e1, CExpression *e2); - CIfExpr(); - - virtual unsigned char GetExpressionID(); - virtual ~CIfExpr(); - virtual CValue* Calculate(); - - virtual bool IsInside(float x,float y,float z,bool bBorderInclude=true); - virtual bool NeedsRecalculated(); - - - virtual CExpression* CheckLink(std::vector& brokenlinks); - virtual void ClearModified(); - virtual void BroadcastOperators(VALUE_OPERATOR op); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:CIfExpr") -#endif -}; - -#endif /* __EXP_IFEXPR_H__ */ diff --git a/source/gameengine/Expressions/EXP_InputParser.h b/source/gameengine/Expressions/EXP_InputParser.h deleted file mode 100644 index 80471009a16..00000000000 --- a/source/gameengine/Expressions/EXP_InputParser.h +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Parser.h: interface for the CParser class. - * Eindhoven University of Technology 1997 - * OOPS team (Serge vd Boom, Erwin Coumans, Tom Geelen, Wynke Stuylemeier) - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -/** \file EXP_InputParser.h - * \ingroup expressions - */ - -#ifndef __EXP_INPUTPARSER_H__ -#define __EXP_INPUTPARSER_H__ - -class CParser; -#include "EXP_Expression.h" - - -class CParser -{ -public: - CParser(); - virtual ~CParser(); - - float GetFloat(STR_String& txt); - CValue* GetValue(STR_String& txt, bool bFallbackToText=false); - CExpression* ProcessText(const char *intext); - void SetContext(CValue* context); - -private: - enum symbols { - errorsym, - lbracksym, - rbracksym, - cellsym, - commasym, - opsym, - constsym, - sumsym, - ifsym, - whocodedsym, - eolsym, - idsym - }; // all kinds of symbols - - enum optype { - OPmodulus, - OPplus, - OPminus, - OPtimes, - OPdivide, - OPand, - OPor, - OPequal, - OPunequal, - OPgreater, - OPless, - OPgreaterequal, - OPlessequal, - OPnot - }; // all kinds of operators - - enum consttype { - booltype, - inttype, - floattype, - stringtype - }; // all kinds of constants - - int sym, // current symbol - opkind, // kind of operator, if symbol is an operator - constkind; // kind of operator, if symbol is a constant - - char ch; // current character - int chcount; // index to character in input string - CExpression *errmsg; // contains a errormessage, if scanner error - - STR_String text, // contains a copy of the original text - const_as_string; // string representation of the symbol, if symbol is a constant - bool boolvalue; // value of the boolean, if symbol is a constant of type boolean - CValue* m_identifierContext;// context in which identifiers are looked up - - - void ScanError(const char *str); - CExpression* Error(const char *str); - void NextCh(); - void TermChar(char c); - void DigRep(); - void CharRep(); - void GrabString(int start); - void GrabRealString(int start); - void NextSym(); -#if 0 /* not used yet */ - int MakeInt(); -#endif - const char *Symbol2Str(int s); - void Term(int s); - int Priority(int optor); - CExpression *Ex(int i); - CExpression *Expr(); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:CParser") -#endif -}; - -#endif /* __EXP_INPUTPARSER_H__ */ - diff --git a/source/gameengine/Expressions/EXP_IntValue.h b/source/gameengine/Expressions/EXP_IntValue.h deleted file mode 100644 index a1cd96a888e..00000000000 --- a/source/gameengine/Expressions/EXP_IntValue.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * IntValue.h: interface for the CIntValue class. - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -/** \file EXP_IntValue.h - * \ingroup expressions - */ - -#ifndef __EXP_INTVALUE_H__ -#define __EXP_INTVALUE_H__ - - -#include "EXP_Value.h" - -typedef long long cInt; - -class CIntValue : public CPropValue -{ - //PLUGIN_DECLARE_SERIAL (CIntValue,CValue) - -public: - virtual const STR_String& GetText(); - virtual double GetNumber(); - virtual int GetValueType(); - - cInt GetInt(); - CIntValue(); - CIntValue(cInt innie); - CIntValue(cInt innie, - const char *name, - AllocationTYPE alloctype=CValue::HEAPVALUE); - - virtual CValue* Calc(VALUE_OPERATOR op, - CValue *val); - - virtual CValue* CalcFinal(VALUE_DATA_TYPE dtype, - VALUE_OPERATOR op, - CValue *val); - - virtual void SetValue(CValue* newval); - - void Configure(CValue* menuvalue); - void AddConfigurationData(CValue* menuvalue); - virtual CValue* GetReplica(); - -#ifdef WITH_PYTHON - virtual PyObject* ConvertValueToPython(); -#endif - -protected: - virtual ~CIntValue(); - -private: - cInt m_int; - STR_String* m_pstrRep; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:CIntValue") -#endif -}; - -#endif /* __EXP_INTVALUE_H__ */ diff --git a/source/gameengine/Expressions/EXP_ListValue.h b/source/gameengine/Expressions/EXP_ListValue.h deleted file mode 100644 index f5421066f62..00000000000 --- a/source/gameengine/Expressions/EXP_ListValue.h +++ /dev/null @@ -1,92 +0,0 @@ -/* - * ListValue.h: interface for the CListValue class. - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -/** \file EXP_ListValue.h - * \ingroup expressions - */ - -#ifndef __EXP_LISTVALUE_H__ -#define __EXP_LISTVALUE_H__ - -#include "EXP_Value.h" - -class CListValue : public CPropValue -{ - Py_Header - //PLUGIN_DECLARE_SERIAL (CListValue,CValue) - -public: - CListValue(); - virtual ~CListValue(); - - void AddConfigurationData(CValue* menuvalue); - void Configure(CValue* menuvalue); - void Add(CValue* value); - - /** \attention not implemented yet :( */ - virtual CValue* Calc(VALUE_OPERATOR op,CValue *val); - virtual CValue* CalcFinal(VALUE_DATA_TYPE dtype, - VALUE_OPERATOR op, - CValue* val); - virtual double GetNumber(); - virtual int GetValueType(); - virtual CValue* GetReplica(); - -public: - void MergeList(CListValue* otherlist); - bool RemoveValue(CValue* val); - void SetReleaseOnDestruct(bool bReleaseContents); - bool SearchValue(CValue* val); - - CValue* FindValue(const STR_String & name); - CValue* FindValue(const char *name); - - void ReleaseAndRemoveAll(); - virtual void SetModified(bool bModified); - virtual inline bool IsModified(); - void Remove(int i); - void Resize(int num); - void SetValue(int i,CValue* val); - CValue* GetValue(int i) { assertd(i < m_pValueArray.size()); return m_pValueArray[i]; } - int GetCount() { return m_pValueArray.size(); } - virtual const STR_String & GetText(); - - bool CheckEqual(CValue* first,CValue* second); - -#ifdef WITH_PYTHON - virtual PyObject *py_repr(void) { - PyObject *py_proxy= this->GetProxy(); - PyObject *py_list= PySequence_List(py_proxy); - PyObject *py_string= PyObject_Repr(py_list); - Py_DECREF(py_list); - Py_DECREF(py_proxy); - return py_string; - } - - KX_PYMETHOD_O(CListValue,append); - KX_PYMETHOD_NOARGS(CListValue,reverse); - KX_PYMETHOD_O(CListValue,index); - KX_PYMETHOD_O(CListValue,count); - KX_PYMETHOD_VARARGS(CListValue,get); - KX_PYMETHOD_O(CListValue,from_id); -#endif - -private: - - std::vector m_pValueArray; - bool m_bReleaseContents; -}; - -#endif /* __EXP_LISTVALUE_H__ */ - diff --git a/source/gameengine/Expressions/EXP_ListWrapper.h b/source/gameengine/Expressions/EXP_ListWrapper.h deleted file mode 100644 index e4c97691acb..00000000000 --- a/source/gameengine/Expressions/EXP_ListWrapper.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. - * - * Contributor(s): Porteries Tristan. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file EXP_ListWrapper.h - * \ingroup expressions - */ - -#ifdef WITH_PYTHON - -#ifndef __EXP_LISTWRAPPER_H__ -#define __EXP_LISTWRAPPER_H__ - -#include "EXP_Value.h" - -class CListWrapper : public CValue -{ - Py_Header -private: - /** The client instance passed as first argument of each callback. - * We use a void * instead of a template to avoid to declare this class - * for each use in KX_PythonInitTypes. - */ - void *m_client; - - // The python object which owned this list. - PyObject *m_base; - - /// Returns true if the list is still valid, else each call will raise an error. - bool (*m_checkValid)(void *); - - /// Returns the list size. - int (*m_getSize)(void *); - - /// Returns the list item for the giving index. - PyObject *(*m_getItem)(void *, int); - - /// Returns name item for the giving index, used for python operator list["name"]. - const char *(*m_getItemName)(void *, int); - - /// Sets the nex item to the index place, return false when failed item conversion. - bool (*m_setItem)(void *, int, PyObject *); - -public: - CListWrapper(void *client, - PyObject *base, - bool (*checkValid)(void *), - int (*getSize)(void *), - PyObject *(*getItem)(void *, int), - const char *(*getItemName)(void *, int), - bool (*setItem)(void *, int, PyObject *)); - ~CListWrapper(); - - /// \section Python Interface - bool CheckValid(); - int GetSize(); - PyObject *GetItem(int index); - const char *GetItemName(int index); - bool SetItem(int index, PyObject *item); - bool AllowSetItem(); - bool AllowGetItemByName(); - - /// \section CValue Inherited Functions. - virtual const STR_String &GetText(); - virtual void SetName(const char *name); - virtual STR_String &GetName(); - virtual CValue *GetReplica(); - virtual CValue *Calc(VALUE_OPERATOR op, CValue *val); - virtual CValue *CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val); - virtual double GetNumber(); - virtual int GetValueType(); - virtual PyObject *py_repr(); - - // Python list operators. - static PySequenceMethods py_as_sequence; - // Python dictionnary operators. - static PyMappingMethods py_as_mapping; - - static Py_ssize_t py_len(PyObject *self); - static PyObject *py_get_item(PyObject *self, Py_ssize_t index); - static int py_set_item(PyObject *self, Py_ssize_t index, PyObject *value); - static PyObject *py_mapping_subscript(PyObject *self, PyObject *key); - static int py_mapping_ass_subscript(PyObject *self, PyObject *key, PyObject *value); - static int py_contains(PyObject *self, PyObject *key); - - KX_PYMETHOD_VARARGS(CListWrapper, Get); -}; - -#endif // __EXP_LISTWRAPPER_H__ - -#endif // WITH_PYTHON diff --git a/source/gameengine/Expressions/EXP_Operator1Expr.h b/source/gameengine/Expressions/EXP_Operator1Expr.h deleted file mode 100644 index 9a05ce9c0c4..00000000000 --- a/source/gameengine/Expressions/EXP_Operator1Expr.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Operator1Expr.h: interface for the COperator1Expr class. - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -/** \file EXP_Operator1Expr.h - * \ingroup expressions - */ - -#ifndef __EXP_OPERATOR1EXPR_H__ -#define __EXP_OPERATOR1EXPR_H__ - -#include "EXP_Expression.h" - -class COperator1Expr : public CExpression -{ - //PLUGIN_DECLARE_SERIAL_EXPRESSION (COperator1Expr,CExpression) - - - -public: - virtual bool MergeExpression(CExpression* otherexpr); - virtual void BroadcastOperators(VALUE_OPERATOR op); - - virtual unsigned char GetExpressionID() { return COPERATOR1EXPRESSIONID; } - CExpression* CheckLink(std::vector& brokenlinks); - //virtual bool IsInside(float x,float y,float z,bool bBorderInclude = true); - virtual bool NeedsRecalculated(); - void ClearModified() { - if (m_lhs) - m_lhs->ClearModified(); - } - virtual CValue* Calculate(); - COperator1Expr(VALUE_OPERATOR op, CExpression *lhs); - COperator1Expr(); - virtual ~COperator1Expr(); - - - -private: - VALUE_OPERATOR m_op; - CExpression * m_lhs; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:") -#endif -}; - -#endif /* __EXP_OPERATOR1EXPR_H__ */ diff --git a/source/gameengine/Expressions/EXP_Operator2Expr.h b/source/gameengine/Expressions/EXP_Operator2Expr.h deleted file mode 100644 index cd7a492fde0..00000000000 --- a/source/gameengine/Expressions/EXP_Operator2Expr.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Operator2Expr.h: interface for the COperator2Expr class. - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -/** \file EXP_Operator2Expr.h - * \ingroup expressions - */ - -#ifndef __EXP_OPERATOR2EXPR_H__ -#define __EXP_OPERATOR2EXPR_H__ - - -#include "EXP_Expression.h" -#include "EXP_Value.h" // Added by ClassView - -class COperator2Expr : public CExpression -{ - //PLUGIN_DECLARE_SERIAL_EXPRESSION (COperator2Expr,CExpression) - -public: - virtual bool MergeExpression(CExpression* otherexpr); - virtual unsigned char GetExpressionID() { return COPERATOR2EXPRESSIONID; } - virtual void BroadcastOperators(VALUE_OPERATOR op); - CExpression* CheckLink(std::vector& brokenlinks); - //virtual bool IsInside(float x,float y,float z,bool bBorderInclude=true); - //virtual bool IsLeftInside(float x,float y,float z,bool bBorderInclude); - //virtual bool IsRightInside(float x,float y,float z,bool bBorderInclude); - bool NeedsRecalculated(); - void ClearModified() { - if (m_lhs) - m_lhs->ClearModified(); - if (m_rhs) - m_rhs->ClearModified(); - } - virtual CValue* Calculate(); - COperator2Expr(VALUE_OPERATOR op, CExpression *lhs, CExpression *rhs); - COperator2Expr(); - virtual ~COperator2Expr(); - - -protected: - CExpression * m_rhs; - CExpression * m_lhs; - CValue* m_cached_calculate; // cached result - -private: - VALUE_OPERATOR m_op; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:COperator2Expr") -#endif -}; - -#endif /* __EXP_OPERATOR2EXPR_H__ */ - diff --git a/source/gameengine/Expressions/EXP_PyObjectPlus.h b/source/gameengine/Expressions/EXP_PyObjectPlus.h deleted file mode 100644 index 32dc79cf6eb..00000000000 --- a/source/gameengine/Expressions/EXP_PyObjectPlus.h +++ /dev/null @@ -1,648 +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 EXP_PyObjectPlus.h - * \ingroup expressions - */ - -#ifndef __EXP_PYOBJECTPLUS_H__ -#define __EXP_PYOBJECTPLUS_H__ - -/* for now keep weakrefs optional */ -#define USE_WEAKREFS - - -#ifndef __cplusplus // c++ only -#error Must be compiled with C++ -#endif - -#include "EXP_Python.h" -#include "STR_String.h" -#include "MT_Vector3.h" -#include "SG_QList.h" -#include - -#ifdef WITH_PYTHON -#ifdef USE_MATHUTILS -extern "C" { -#include "../../blender/python/mathutils/mathutils.h" /* so we can have mathutils callbacks */ -#include "../../blender/python/generic/py_capi_utils.h" /* for PyC_LineSpit only */ -} -#endif - -#define MAX_PROP_NAME 64 - -/* Use with ShowDeprecationWarning macro */ -typedef struct { - bool warn_done; - void *link; -} WarnLink; - -#define ShowDeprecationWarning(old_way, new_way) \ -{ \ - static WarnLink wlink = {false, NULL}; \ - if ((PyObjectPlus::m_ignore_deprecation_warnings || wlink.warn_done)==0) \ - { \ - PyObjectPlus::ShowDeprecationWarning_func(old_way, new_way); \ - \ - WarnLink *wlink_last= PyObjectPlus::GetDeprecationWarningLinkLast(); \ - wlink.warn_done = true; \ - wlink.link = NULL; \ - \ - if (wlink_last) { \ - wlink_last->link= (void *)&(wlink); \ - PyObjectPlus::SetDeprecationWarningLinkLast(&(wlink)); \ - } \ - else { \ - PyObjectPlus::SetDeprecationWarningFirst(&(wlink)); \ - PyObjectPlus::SetDeprecationWarningLinkLast(&(wlink)); \ - } \ - } \ -} \ - - - -typedef struct PyObjectPlus_Proxy { - PyObject_HEAD /* required python macro */ - class PyObjectPlus *ref; // pointer to GE object, it holds a reference to this proxy - void *ptr; // optional pointer to generic structure, the structure holds no reference to this proxy - bool py_owns; // true if the object pointed by ref should be deleted when the proxy is deleted - bool py_ref; // true if proxy is connected to a GE object (ref is used) -#ifdef USE_WEAKREFS - PyObject *in_weakreflist; // weak reference enabler -#endif -} PyObjectPlus_Proxy; - -#define BGE_PROXY_ERROR_MSG "Blender Game Engine data has been freed, cannot use this python variable" -#define BGE_PROXY_REF(_self) (((PyObjectPlus_Proxy *)_self)->ref) -#define BGE_PROXY_PTR(_self) (((PyObjectPlus_Proxy *)_self)->ptr) -#define BGE_PROXY_PYOWNS(_self) (((PyObjectPlus_Proxy *)_self)->py_owns) -#define BGE_PROXY_PYREF(_self) (((PyObjectPlus_Proxy *)_self)->py_ref) -#ifdef USE_WEAKREFS -# define BGE_PROXY_WKREF(_self) (((PyObjectPlus_Proxy *)_self)->in_weakreflist) -#endif - -/* Note, sometimes we don't care what BGE type this is as long as its a proxy */ -#define BGE_PROXY_CHECK_TYPE(_type) ((_type)->tp_dealloc == PyObjectPlus::py_base_dealloc) - -/* Opposite of BGE_PROXY_REF */ -#define BGE_PROXY_FROM_REF(_self) (((PyObjectPlus *)_self)->GetProxy()) -/* Same as 'BGE_PROXY_REF' but doesn't incref. */ -#define BGE_PROXY_FROM_REF_BORROW(_self) _bge_proxy_from_ref_borrow((void *)_self) - - -// This must be the first line of each -// PyC++ class -// AttributesPtr correspond to attributes of proxy generic pointer -// each PyC++ class must be registered in KX_PythonInitTypes.cpp -#define __Py_Header \ -public: \ - static PyTypeObject Type; \ - static PyMethodDef Methods[]; \ - static PyAttributeDef Attributes[]; \ - virtual PyTypeObject *GetType(void) { \ - return &Type; \ - } \ - virtual PyObject *GetProxy() { \ - return GetProxyPlus_Ext(this, &Type, NULL); \ - } \ - virtual PyObject *NewProxy(bool py_owns) { \ - return NewProxyPlus_Ext(this, &Type, NULL, py_owns); \ - } \ - -// leave above line empty (macro)! -// use this macro for class that use generic pointer in proxy -// GetProxy() and NewProxy() must be defined to set the correct pointer in the proxy -#define __Py_HeaderPtr \ -public: \ - static PyTypeObject Type; \ - static PyMethodDef Methods[]; \ - static PyAttributeDef Attributes[]; \ - static PyAttributeDef AttributesPtr[]; \ - virtual PyTypeObject *GetType(void) { \ - return &Type; \ - } \ - virtual PyObject *GetProxy(); \ - virtual PyObject *NewProxy(bool py_owns); \ - -// leave above line empty (macro)! -#ifdef WITH_CXX_GUARDEDALLOC -#define Py_Header __Py_Header \ - void *operator new(size_t num_bytes) { \ - return MEM_mallocN(num_bytes, Type.tp_name); \ - } \ - void operator delete(void *mem) { \ - MEM_freeN(mem); \ - } \ - -#else -# define Py_Header __Py_Header -#endif - -#ifdef WITH_CXX_GUARDEDALLOC -#define Py_HeaderPtr __Py_HeaderPtr \ - void *operator new(size_t num_bytes) { \ - return MEM_mallocN(num_bytes, Type.tp_name); \ - } \ - void operator delete(void *mem) { \ - MEM_freeN(mem); \ - } \ - -#else -# define Py_HeaderPtr __Py_HeaderPtr -#endif - -/* - * nonzero values are an error for setattr - * however because of the nested lookups we need to know if the errors - * was because the attribute didnt exits of if there was some problem setting the value - */ - -#define PY_SET_ATTR_COERCE_FAIL 2 -#define PY_SET_ATTR_FAIL 1 -#define PY_SET_ATTR_MISSING -1 -#define PY_SET_ATTR_SUCCESS 0 - -/** - * These macros are helpful when embedding Python routines. The second - * macro is one that also requires a documentation string - */ -#define KX_PYMETHOD(class_name, method_name) \ - PyObject *Py##method_name(PyObject *args, PyObject *kwds); \ - static PyObject * \ - sPy##method_name(PyObject *self, PyObject *args, PyObject *kwds) { \ - if (BGE_PROXY_REF(self)==NULL) { \ - PyErr_SetString(PyExc_RuntimeError, \ - #class_name "." #method_name "() - " \ - BGE_PROXY_ERROR_MSG); \ - return NULL; \ - } \ - return((class_name*)BGE_PROXY_REF(self))->Py##method_name(args, kwds); \ - } \ - -#define KX_PYMETHOD_VARARGS(class_name, method_name) \ - PyObject *Py##method_name(PyObject *args); \ - static PyObject* \ - sPy##method_name(PyObject *self, PyObject *args) { \ - if (BGE_PROXY_REF(self)==NULL) { \ - PyErr_SetString(PyExc_RuntimeError, \ - #class_name "." #method_name "() - " \ - BGE_PROXY_ERROR_MSG); return NULL; \ - } \ - return((class_name*)BGE_PROXY_REF(self))->Py##method_name(args); \ - } \ - -#define KX_PYMETHOD_NOARGS(class_name, method_name) \ - PyObject *Py##method_name(); \ - static PyObject* \ - sPy##method_name(PyObject *self) { \ - if (BGE_PROXY_REF(self)==NULL) { \ - PyErr_SetString(PyExc_RuntimeError, \ - #class_name "." #method_name "() - " \ - BGE_PROXY_ERROR_MSG); return NULL; \ - } \ - return((class_name*)BGE_PROXY_REF(self))->Py##method_name(); \ - } \ - -#define KX_PYMETHOD_O(class_name, method_name) \ - PyObject *Py##method_name(PyObject *value); \ - static PyObject* \ - sPy##method_name(PyObject *self, PyObject *value) { \ - if (BGE_PROXY_REF(self)==NULL) { \ - PyErr_SetString(PyExc_RuntimeError, \ - #class_name "." #method_name "(value) - " \ - BGE_PROXY_ERROR_MSG); return NULL; \ - } \ - return((class_name*)BGE_PROXY_REF(self))->Py##method_name(value); \ - } \ - -#define KX_PYMETHOD_DOC(class_name, method_name) \ - PyObject *Py##method_name(PyObject *args, PyObject *kwds); \ - static PyObject* \ - sPy##method_name(PyObject *self, PyObject *args, PyObject *kwds) { \ - if (BGE_PROXY_REF(self)==NULL) { \ - PyErr_SetString(PyExc_RuntimeError, \ - #class_name "." #method_name "(...) - " \ - BGE_PROXY_ERROR_MSG); return NULL; \ - } \ - return((class_name*)BGE_PROXY_REF(self))->Py##method_name(args, kwds); \ - } \ - static const char method_name##_doc[]; \ - -#define KX_PYMETHOD_DOC_VARARGS(class_name, method_name) \ - PyObject *Py##method_name(PyObject *args); \ - static PyObject* \ - sPy##method_name(PyObject *self, PyObject *args) { \ - if (BGE_PROXY_REF(self)==NULL) { \ - PyErr_SetString(PyExc_RuntimeError, \ - #class_name "." #method_name "(...) - " \ - BGE_PROXY_ERROR_MSG); \ - return NULL; \ - } \ - return((class_name*)BGE_PROXY_REF(self))->Py##method_name(args); \ - } \ - static const char method_name##_doc[]; \ - -#define KX_PYMETHOD_DOC_O(class_name, method_name) \ - PyObject *Py##method_name(PyObject *value); \ - static PyObject * \ - sPy##method_name(PyObject *self, PyObject *value) { \ - if (BGE_PROXY_REF(self)==NULL) { \ - PyErr_SetString(PyExc_RuntimeError, \ - #class_name "." #method_name "(value) - " \ - BGE_PROXY_ERROR_MSG); \ - return NULL; \ - } \ - return ((class_name*)BGE_PROXY_REF(self))->Py##method_name(value); \ - } \ - static const char method_name##_doc[]; \ - -#define KX_PYMETHOD_DOC_NOARGS(class_name, method_name) \ - PyObject *Py##method_name(); \ - static PyObject * \ - sPy##method_name(PyObject *self) { \ - if (BGE_PROXY_REF(self)==NULL) { \ - PyErr_SetString(PyExc_RuntimeError, \ - #class_name "." #method_name "() - " \ - BGE_PROXY_ERROR_MSG); \ - return NULL; \ - } \ - return ((class_name*)BGE_PROXY_REF(self))->Py##method_name(); \ - } \ - static const char method_name##_doc[]; \ - - -/* The line above should remain empty */ -/** - * Method table macro (with doc) - */ -#define KX_PYMETHODTABLE(class_name, method_name) \ - {#method_name, (PyCFunction) class_name::sPy##method_name, METH_VARARGS, (const char *)class_name::method_name##_doc} - -#define KX_PYMETHODTABLE_O(class_name, method_name) \ - {#method_name, (PyCFunction) class_name::sPy##method_name, METH_O, (const char *)class_name::method_name##_doc} - -#define KX_PYMETHODTABLE_NOARGS(class_name, method_name) \ - {#method_name, (PyCFunction) class_name::sPy##method_name, METH_NOARGS, (const char *)class_name::method_name##_doc} - -#define KX_PYMETHODTABLE_KEYWORDS(class_name, method_name) \ - {#method_name, (PyCFunction) class_name::sPy##method_name, METH_VARARGS|METH_KEYWORDS, (const char *)class_name::method_name##_doc} - -/** - * Function implementation macro - */ -#define KX_PYMETHODDEF_DOC(class_name, method_name, doc_string) \ -const char class_name::method_name##_doc[] = doc_string; \ -PyObject *class_name::Py##method_name(PyObject *args, PyObject *kwds) - -#define KX_PYMETHODDEF_DOC_VARARGS(class_name, method_name, doc_string) \ -const char class_name::method_name##_doc[] = doc_string; \ -PyObject *class_name::Py##method_name(PyObject *args) - -#define KX_PYMETHODDEF_DOC_O(class_name, method_name, doc_string) \ -const char class_name::method_name##_doc[] = doc_string; \ -PyObject *class_name::Py##method_name(PyObject *value) - -#define KX_PYMETHODDEF_DOC_NOARGS(class_name, method_name, doc_string) \ -const char class_name::method_name##_doc[] = doc_string; \ -PyObject *class_name::Py##method_name() - -/** - * Attribute management - */ -enum KX_PYATTRIBUTE_TYPE { - KX_PYATTRIBUTE_TYPE_BOOL, - KX_PYATTRIBUTE_TYPE_ENUM, - KX_PYATTRIBUTE_TYPE_SHORT, - KX_PYATTRIBUTE_TYPE_INT, - KX_PYATTRIBUTE_TYPE_FLOAT, - KX_PYATTRIBUTE_TYPE_STRING, - KX_PYATTRIBUTE_TYPE_DUMMY, - KX_PYATTRIBUTE_TYPE_FUNCTION, - KX_PYATTRIBUTE_TYPE_VECTOR, - KX_PYATTRIBUTE_TYPE_FLAG, - KX_PYATTRIBUTE_TYPE_CHAR -}; - -enum KX_PYATTRIBUTE_ACCESS { - KX_PYATTRIBUTE_RW, - KX_PYATTRIBUTE_RO -}; - -struct KX_PYATTRIBUTE_DEF; -typedef int (*KX_PYATTRIBUTE_CHECK_FUNCTION)(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); -typedef int (*KX_PYATTRIBUTE_SET_FUNCTION)(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); -typedef PyObject *(*KX_PYATTRIBUTE_GET_FUNCTION)(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - -typedef struct KX_PYATTRIBUTE_DEF { - const char *m_name; // name of the python attribute - KX_PYATTRIBUTE_TYPE m_type; // type of value - KX_PYATTRIBUTE_ACCESS m_access; // read/write access or read-only - int m_imin; // minimum value in case of integer attributes - // (for string: minimum string length, for flag: mask value, for float: matrix row size) - int m_imax; // maximum value in case of integer attributes - // (for string: maximum string length, for flag: 1 if flag is negative, float: vector/matrix col size) - float m_fmin; // minimum value in case of float attributes - float m_fmax; // maximum value in case of float attributes - bool m_clamp; // enforce min/max value by clamping - bool m_usePtr; // the attribute uses the proxy generic pointer, set at runtime - size_t m_offset; // position of field in structure - size_t m_size; // size of field for runtime verification (enum only) - size_t m_length; // length of array, 1=simple attribute - KX_PYATTRIBUTE_CHECK_FUNCTION m_checkFunction; // static function to check the assignment, returns 0 if no error - KX_PYATTRIBUTE_SET_FUNCTION m_setFunction; // static function to check the assignment, returns 0 if no error - KX_PYATTRIBUTE_GET_FUNCTION m_getFunction; // static function to check the assignment, returns 0 if no error - - // The following pointers are just used to have compile time check for attribute type. - // It would have been good to use a union but that would require C99 compatibility - // to initialize specific union fields through designated initializers. - struct { - bool *m_boolPtr; - short int *m_shortPtr; - int *m_intPtr; - float *m_floatPtr; - STR_String *m_stringPtr; - MT_Vector3 *m_vectorPtr; - char *m_charPtr; - } m_typeCheck; -} PyAttributeDef; - -#define KX_PYATTRIBUTE_BOOL_RW(name, object, field) \ - { name, KX_PYATTRIBUTE_TYPE_BOOL, KX_PYATTRIBUTE_RW, 0, 1, 0.f, 0.f, false, false, offsetof(object, field), 0, 1, NULL, NULL, NULL, {&((object *)0)->field, NULL, NULL, NULL, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_BOOL_RW_CHECK(name, object, field, function) \ - { name, KX_PYATTRIBUTE_TYPE_BOOL, KX_PYATTRIBUTE_RW, 0, 1, 0.f, 0.f, false, false, offsetof(object, field), 0, 1, &object::function, NULL, NULL, {&((object *)0)->field, NULL, NULL, NULL, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_BOOL_RO(name, object, field) \ - { name, KX_PYATTRIBUTE_TYPE_BOOL, KX_PYATTRIBUTE_RO, 0, 1, 0.f, 0.f, false, false, offsetof(object, field), 0, 1, NULL, NULL, NULL, {&((object *)0)->field, NULL, NULL, NULL, NULL, NULL, NULL} } - -/* attribute points to a single bit of an integer field, attribute=true if bit is set */ -#define KX_PYATTRIBUTE_FLAG_RW(name, object, field, bit) \ - { name, KX_PYATTRIBUTE_TYPE_FLAG, KX_PYATTRIBUTE_RW, bit, 0, 0.f, 0.f, false, false, offsetof(object, field), sizeof(((object *)0)->field), 1, NULL, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_FLAG_RW_CHECK(name, object, field, bit, function) \ - { name, KX_PYATTRIBUTE_TYPE_FLAG, KX_PYATTRIBUTE_RW, bit, 0, 0.f, 0.f, false, false, offsetof(object, field), sizeof(((object *)0)->field), 1, &object::function, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_FLAG_RO(name, object, field, bit) \ - { name, KX_PYATTRIBUTE_TYPE_FLAG, KX_PYATTRIBUTE_RO, bit, 0, 0.f, 0.f, false, false, offsetof(object, field), sizeof(((object *)0)->field), 1, NULL, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, NULL} } - -/* attribute points to a single bit of an integer field, attribute=true if bit is set*/ -#define KX_PYATTRIBUTE_FLAG_NEGATIVE_RW(name, object, field, bit) \ - { name, KX_PYATTRIBUTE_TYPE_FLAG, KX_PYATTRIBUTE_RW, bit, 1, 0.f, 0.f, false, false, offsetof(object, field), sizeof(((object *)0)->field), 1, NULL, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_FLAG_NEGATIVE_RW_CHECK(name, object, field, bit, function) \ - { name, KX_PYATTRIBUTE_TYPE_FLAG, KX_PYATTRIBUTE_RW, bit, 1, 0.f, 0.f, false, false, offsetof(object, field), sizeof(((object *)0)->field), 1, &object::function, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_FLAG_NEGATIVE_RO(name, object, field, bit) \ - { name, KX_PYATTRIBUTE_TYPE_FLAG, KX_PYATTRIBUTE_RO, bit, 1, 0.f, 0.f, false, false, offsetof(object, field), sizeof(((object *)0)->field), 1, NULL, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, NULL} } - -// enum field cannot be mapped to pointer (because we would need a pointer for each enum) -// use field size to verify mapping at runtime only, assuming enum size is equal to int size. -#define KX_PYATTRIBUTE_ENUM_RW(name, min, max, clamp, object, field) \ - { name, KX_PYATTRIBUTE_TYPE_ENUM, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), sizeof(((object *)0)->field), 1, NULL, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_ENUM_RW_CHECK(name, min, max, clamp, object, field, function) \ - { name, KX_PYATTRIBUTE_TYPE_ENUM, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), sizeof(((object *)0)->field), 1, &object::function, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_ENUM_RO(name, object, field) \ - { name, KX_PYATTRIBUTE_TYPE_ENUM, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, false, false, offsetof(object, field), sizeof(((object *)0)->field), 1, NULL, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, NULL} } - -#define KX_PYATTRIBUTE_SHORT_RW(name, min, max, clamp, object, field) \ - { name, KX_PYATTRIBUTE_TYPE_SHORT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, 1, NULL, NULL, NULL, {NULL, &((object *)0)->field, NULL, NULL, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_SHORT_RW_CHECK(name, min, max, clamp, object, field, function) \ - { name, KX_PYATTRIBUTE_TYPE_SHORT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, 1, &object::function, NULL, NULL, {NULL, &((object *)0)->field, NULL, NULL, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_SHORT_RO(name, object, field) \ - { name, KX_PYATTRIBUTE_TYPE_SHORT, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, false, false, offsetof(object, field), 0, 1, NULL, NULL, NULL, {NULL, &((object *)0)->field, NULL, NULL, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_SHORT_ARRAY_RW(name, min, max, clamp, object, field, length) \ - { name, KX_PYATTRIBUTE_TYPE_SHORT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, length, NULL, NULL, NULL, {NULL, ((object *)0)->field, NULL, NULL, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_SHORT_ARRAY_RW_CHECK(name, min, max, clamp, object, field, length, function) \ - { name, KX_PYATTRIBUTE_TYPE_SHORT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, length, &object::function, NULL, NULL, {NULL, ((object *)0)->field, NULL, NULL, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_SHORT_ARRAY_RO(name, object, field, length) \ - { name, KX_PYATTRIBUTE_TYPE_SHORT, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, false, false, offsetof(object, field), 0, length, NULL, NULL, NULL, {NULL, ((object *)0)->field, NULL, NULL, NULL, NULL, NULL} } -// SHORT_LIST -#define KX_PYATTRIBUTE_SHORT_LIST_RW(name, min, max, clamp, object, field, length) \ - { name, KX_PYATTRIBUTE_TYPE_SHORT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, length, NULL, NULL, NULL, {NULL, &((object *)0)->field, NULL, NULL, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_SHORT_LIST_RW_CHECK(name, min, max, clamp, object, field, length, function) \ - { name, KX_PYATTRIBUTE_TYPE_SHORT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, length, &object::function, NULL, NULL, {NULL, &((object *)0)->field, NULL, NULL, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_SHORT_LIST_RO(name, object, field, length) \ - { name, KX_PYATTRIBUTE_TYPE_SHORT, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, false, false, offsetof(object, field), 0, length, NULL, NULL, NULL, {NULL, &((object *)0)->field, NULL, NULL, NULL, NULL, NULL} } - -#define KX_PYATTRIBUTE_INT_RW(name, min, max, clamp, object, field) \ - { name, KX_PYATTRIBUTE_TYPE_INT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, 1, NULL, NULL, NULL, {NULL, NULL, &((object *)0)->field, NULL, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_INT_RW_CHECK(name, min, max, clamp, object, field, function) \ - { name, KX_PYATTRIBUTE_TYPE_INT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, 1, &object::function, NULL, NULL, {NULL, NULL, &((object *)0)->field, NULL, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_INT_RO(name, object, field) \ - { name, KX_PYATTRIBUTE_TYPE_INT, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, false, false, offsetof(object, field), 0, 1, NULL, NULL, NULL, {NULL, NULL, &((object *)0)->field, NULL, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_INT_ARRAY_RW(name, min, max, clamp, object, field, length) \ - { name, KX_PYATTRIBUTE_TYPE_INT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, length, NULL, NULL, NULL, {NULL, NULL, ((object *)0)->field, NULL, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_INT_ARRAY_RW_CHECK(name, min, max, clamp, object, field, length, function) \ - { name, KX_PYATTRIBUTE_TYPE_INT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, length, &object::function, NULL, NULL, {NULL, NULL, ((object *)0)->field, NULL, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_INT_ARRAY_RO(name, object, field, length) \ - { name, KX_PYATTRIBUTE_TYPE_INT, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, false, false, offsetof(object, field), 0, length, NULL, NULL, NULL, {NULL, NULL, ((object *)0)->field, NULL, NULL, NULL, NULL} } -// INT_LIST -#define KX_PYATTRIBUTE_INT_LIST_RW(name, min, max, clamp, object, field, length) \ - { name, KX_PYATTRIBUTE_TYPE_INT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, length, NULL, NULL, NULL, {NULL, NULL, &((object *)0)->field, NULL, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_INT_LIST_RW_CHECK(name, min, max, clamp, object, field, length, function) \ - { name, KX_PYATTRIBUTE_TYPE_INT, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, length, &object::function, NULL, NULL, {NULL, NULL, &((object *)0)->field, NULL, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_INT_LIST_RO(name, object, field, length) \ - { name, KX_PYATTRIBUTE_TYPE_INT, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, false, false, offsetof(object, field), 0, length, NULL, NULL, NULL, {NULL, NULL, &((object *)0)->field, NULL, NULL, NULL, NULL} } - -// always clamp for float -#define KX_PYATTRIBUTE_FLOAT_RW(name, min, max, object, field) \ - { name, KX_PYATTRIBUTE_TYPE_FLOAT, KX_PYATTRIBUTE_RW, 0, 0, min, max, true, false, offsetof(object, field), 0, 1, NULL, NULL, NULL, {NULL, NULL, NULL, &((object *)0)->field, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_FLOAT_RW_CHECK(name, min, max, object, field, function) \ - { name, KX_PYATTRIBUTE_TYPE_FLOAT, KX_PYATTRIBUTE_RW, 0, 0, min, max, true, false, offsetof(object, field), 0, 1, &object::function, NULL, NULL, {NULL, NULL, NULL, &((object *)0)->field, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_FLOAT_RO(name, object, field) \ - { name, KX_PYATTRIBUTE_TYPE_FLOAT, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, false, false, offsetof(object, field), 0, 1, NULL, NULL, NULL, {NULL, NULL, NULL, &((object *)0)->field, NULL, NULL, NULL} } -// field must be float[n], returns a sequence -#define KX_PYATTRIBUTE_FLOAT_ARRAY_RW(name, min, max, object, field, length) \ - { name, KX_PYATTRIBUTE_TYPE_FLOAT, KX_PYATTRIBUTE_RW, 0, 0, min, max, true, false, offsetof(object, field), 0, length, NULL, NULL, NULL, {NULL, NULL, NULL, ((object *)0)->field, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_FLOAT_ARRAY_RW_CHECK(name, min, max, object, field, length, function) \ - { name, KX_PYATTRIBUTE_TYPE_FLOAT, KX_PYATTRIBUTE_RW, 0, 0, min, max, true, false, offsetof(object, field), 0, length, &object::function, NULL, NULL, {NULL, NULL, NULL, ((object *)0)->field, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_FLOAT_ARRAY_RO(name, object, field, length) \ - { name, KX_PYATTRIBUTE_TYPE_FLOAT, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, false, false, offsetof(object, field), 0, length, NULL, NULL, NULL, {NULL, NULL, NULL, ((object *)0)->field, NULL, NULL, NULL} } -// field must be float[n], returns a vector -#define KX_PYATTRIBUTE_FLOAT_VECTOR_RW(name, min, max, object, field, length) \ - { name, KX_PYATTRIBUTE_TYPE_FLOAT, KX_PYATTRIBUTE_RW, 0, length, min, max, true, false, offsetof(object, field), sizeof(((object *)0)->field), 1, NULL, NULL, NULL, {NULL, NULL, NULL, ((object *)0)->field, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_FLOAT_VECTOR_RW_CHECK(name, min, max, object, field, length, function) \ - { name, KX_PYATTRIBUTE_TYPE_FLOAT, KX_PYATTRIBUTE_RW, 0, length, min, max, true, false, offsetof(object, field), sizeof(((object *)0)->field), 1, &object::function, NULL, NULL, {NULL, NULL, NULL, ((object *)0)->field, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_FLOAT_VECTOR_RO(name, object, field, length) \ - { name, KX_PYATTRIBUTE_TYPE_FLOAT, KX_PYATTRIBUTE_RO, 0, length, 0.f, 0.f, false, false, offsetof(object, field), sizeof(((object *)0)->field), 1, NULL, NULL, NULL, {NULL, NULL, NULL, ((object *)0)->field, NULL, NULL, NULL} } -// field must be float[n][n], returns a matrix -#define KX_PYATTRIBUTE_FLOAT_MATRIX_RW(name, min, max, object, field, length) \ - { name, KX_PYATTRIBUTE_TYPE_FLOAT, KX_PYATTRIBUTE_RW, length, length, min, max, true, false, offsetof(object, field), sizeof(((object *)0)->field), 1, NULL, NULL, NULL, {NULL, NULL, NULL, ((object *)0)->field[0], NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_FLOAT_MATRIX_RW_CHECK(name, min, max, object, field, length, function) \ - { name, KX_PYATTRIBUTE_TYPE_FLOAT, KX_PYATTRIBUTE_RW, length, length, min, max, true, false, offsetof(object, field), sizeof(((object *)0)->field), 1, &object::function, NULL, NULL, {NULL, NULL, NULL, ((object *)0)->field[0], NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_FLOAT_MATRIX_RO(name, object, field, length) \ - { name, KX_PYATTRIBUTE_TYPE_FLOAT, KX_PYATTRIBUTE_RO, length, length, 0.f, 0.f, false, false, offsetof(object, field), sizeof(((object *)0)->field), 1, NULL, NULL, NULL, {NULL, NULL, NULL, ((object *)0)->field[0], NULL, NULL, NULL} } - -// only for STR_String member -#define KX_PYATTRIBUTE_STRING_RW(name, min, max, clamp, object, field) \ - { name, KX_PYATTRIBUTE_TYPE_STRING, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, 1, NULL, NULL, NULL, {NULL, NULL, NULL, NULL, &((object *)0)->field, NULL, NULL} } -#define KX_PYATTRIBUTE_STRING_RW_CHECK(name, min, max, clamp, object, field, function) \ - { name, KX_PYATTRIBUTE_TYPE_STRING, KX_PYATTRIBUTE_RW, min, max, 0.f, 0.f, clamp, false, offsetof(object, field), 0, 1, &object::function, NULL, NULL, {NULL, NULL, NULL, NULL, &((object *)0)->field, NULL, NULL} } -#define KX_PYATTRIBUTE_STRING_RO(name, object, field) \ - { name, KX_PYATTRIBUTE_TYPE_STRING, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, false, false, offsetof(object, field), 0, 1 , NULL, NULL, NULL, {NULL, NULL, NULL, NULL, &((object *)0)->field, NULL, NULL} } - -// only for char [] array -#define KX_PYATTRIBUTE_CHAR_RW(name, object, field) \ - { name, KX_PYATTRIBUTE_TYPE_CHAR, KX_PYATTRIBUTE_RW, 0, 0, 0.f, 0.f, true, false, offsetof(object, field), sizeof(((object *)0)->field), 1, NULL, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, ((object *)0)->field} } -#define KX_PYATTRIBUTE_CHAR_RW_CHECK(name, object, field, function) \ - { name, KX_PYATTRIBUTE_TYPE_CHAR, KX_PYATTRIBUTE_RW, 0, 0, 0.f, 0.f, true, false, offsetof(object, field), sizeof(((object *)0)->field), 1, &object::function, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, ((object *)0)->field} } -#define KX_PYATTRIBUTE_CHAR_RO(name, object, field) \ - { name, KX_PYATTRIBUTE_TYPE_CHAR, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, false, false, offsetof(object, field), sizeof(((object *)0)->field), 1 , NULL, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, NULL, ((object *)0)->field} } - -// for MT_Vector3 member -#define KX_PYATTRIBUTE_VECTOR_RW(name, min, max, object, field) \ - { name, KX_PYATTRIBUTE_TYPE_VECTOR, KX_PYATTRIBUTE_RW, 0, 0, min, max, true, false, offsetof(object, field), 0, 1, NULL, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, &((object *)0)->field, NULL} } -#define KX_PYATTRIBUTE_VECTOR_RW_CHECK(name, min, max, clamp, object, field, function) \ - { name, KX_PYATTRIBUTE_TYPE_VECTOR, KX_PYATTRIBUTE_RW, 0, 0, min, max, true, false, offsetof(object, field), 0, 1, &object::function, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, &((object *)0)->field, NULL} } -#define KX_PYATTRIBUTE_VECTOR_RO(name, object, field) \ - { name, KX_PYATTRIBUTE_TYPE_VECTOR, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, false, false, offsetof(object, field), 0, 1 , NULL, NULL, NULL, {NULL, NULL, NULL, NULL, NULL, &((object *)0)->field, NULL} } - -#define KX_PYATTRIBUTE_RW_FUNCTION(name, object, getfunction, setfunction) \ - { name, KX_PYATTRIBUTE_TYPE_FUNCTION, KX_PYATTRIBUTE_RW, 0, 0, 0.f, 0.f, false, false, 0, 0, 1, NULL, &object::setfunction, &object::getfunction, {NULL, NULL, NULL, NULL, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_RO_FUNCTION(name, object, getfunction) \ - { name, KX_PYATTRIBUTE_TYPE_FUNCTION, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0.f, false, false, 0, 0, 1, NULL, NULL, &object::getfunction, {NULL, NULL, NULL, NULL, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_ARRAY_RW_FUNCTION(name, object, length, getfunction, setfunction) \ - { name, KX_PYATTRIBUTE_TYPE_FUNCTION, KX_PYATTRIBUTE_RW, 0, 0, 0.f, 0, f, false, false, 0, 0, length, NULL, &object::setfunction, &object::getfunction, {NULL, NULL, NULL, NULL, NULL, NULL, NULL} } -#define KX_PYATTRIBUTE_ARRAY_RO_FUNCTION(name, object, length, getfunction) \ - { name, KX_PYATTRIBUTE_TYPE_FUNCTION, KX_PYATTRIBUTE_RO, 0, 0, 0.f, 0, f, false, false, 0, 0, length, NULL, NULL, &object::getfunction, {NULL, NULL, NULL, NULL, NULL, NULL, NULL} } - - -/*------------------------------ - * PyObjectPlus - *------------------------------ */ -typedef PyTypeObject *PyParentObject; /* Define the PyParent Object */ - -#else // WITH_PYTHON - -#ifdef WITH_CXX_GUARDEDALLOC -#define Py_Header \ -public: \ - MEM_CXX_CLASS_ALLOC_FUNCS("GE:PyObjectPlus") \ - - -#define Py_HeaderPtr \ - MEM_CXX_CLASS_ALLOC_FUNCS("GE:PyObjectPlusPtr") \ - -#else // WITH_CXX_GUARDEDALLOC - -#define Py_Header \ -public: \ - -#define Py_HeaderPtr \ -public: \ - -#endif /* WITH_CXX_GUARDEDALLOC */ - -#endif - - -// By making SG_QList the ultimate parent for PyObjectPlus objects, it -// allows to put them in 2 different dynamic lists at the same time -// The use of these links is interesting because they free of memory allocation -// but it's very important not to mess up with them. If you decide that -// the SG_QList or SG_DList component is used for something for a certain class, -// they cannot can be used for anything else at a parent level! -// What these lists are and what they are used for must be carefully documented -// at the level where they are used. -// DON'T MAKE ANY USE OF THESE LIST AT THIS LEVEL, they are already used -// at SCA_IActuator, SCA_ISensor, SCA_IController level which rules out the -// possibility to use them at SCA_ILogicBrick, CValue and PyObjectPlus level. -class PyObjectPlus : public SG_QList -{ // The PyObjectPlus abstract class - Py_Header // Always start with Py_Header - -public: - PyObjectPlus(); - - virtual ~PyObjectPlus(); // destructor - -#ifdef WITH_PYTHON - PyObject *m_proxy; /* actually a PyObjectPlus_Proxy */ - - /* These static functions are referenced by ALL PyObjectPlus_Proxy types - * they take the C++ reference from the PyObjectPlus_Proxy and call - * its own virtual py_repr, py_base_dealloc, etc. functions. - */ - - static PyObject* py_base_new(PyTypeObject *type, PyObject *args, PyObject *kwds); /* allows subclassing */ - static void py_base_dealloc(PyObject *self); - static PyObject* py_base_repr(PyObject *self); - - /* These are all virtual python methods that are defined in each class - * Our own fake subclassing calls these on each class, then calls the parent */ - virtual PyObject* py_repr(void); - /* subclass may overwrite this function to implement more sophisticated method of validating a proxy */ - virtual bool py_is_valid(void) { return true; } - - static PyObject* py_get_attrdef(PyObject *self_py, const PyAttributeDef *attrdef); - static int py_set_attrdef(PyObject *self_py, PyObject *value, const PyAttributeDef *attrdef); - - /* Kindof dumb, always returns True, the false case is checked for, before this function gets accessed */ - static PyObject* pyattr_get_invalid(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - - static PyObject *GetProxyPlus_Ext(PyObjectPlus *self, PyTypeObject *tp, void *ptr); - /* self=NULL => proxy to generic pointer detached from GE object - * if py_owns is true, the memory pointed by ptr will be deleted automatically with MEM_freeN - * self!=NULL=> proxy attached to GE object, ptr is optional and point to a struct from which attributes can be defined - * if py_owns is true, the object will be deleted automatically, ptr will NOT be deleted - * (assume object destructor takes care of it) */ - static PyObject *NewProxyPlus_Ext(PyObjectPlus *self, PyTypeObject *tp, void *ptr, bool py_owns); - - static WarnLink* GetDeprecationWarningLinkFirst(void); - static WarnLink* GetDeprecationWarningLinkLast(void); - static void SetDeprecationWarningFirst(WarnLink* wlink); - static void SetDeprecationWarningLinkLast(WarnLink* wlink); - static void NullDeprecationWarning(); - - /** enable/disable display of deprecation warnings */ - static void SetDeprecationWarnings(bool ignoreDeprecationWarnings); - /** Shows a deprecation warning */ - static void ShowDeprecationWarning_func(const char *method, const char *prop); - static void ClearDeprecationWarning(); - -#endif - - void InvalidateProxy(); - - /** - * Makes sure any internal data owned by this class is deep copied. - */ - virtual void ProcessReplica(); - - static bool m_ignore_deprecation_warnings; -}; - -#ifdef WITH_PYTHON -PyObject *PyUnicode_From_STR_String(const STR_String& str); - -inline PyObject *_bge_proxy_from_ref_borrow(void *self_v) -{ - PyObject *self_proxy = BGE_PROXY_FROM_REF(self_v); - /* this is typically _very_ bad practice, - * however we know the proxy is owned by 'self_v' */ - self_proxy->ob_refcnt--; - return self_proxy; -} - -#endif - -#endif /* __EXP_PYOBJECTPLUS_H__ */ diff --git a/source/gameengine/Expressions/EXP_Python.h b/source/gameengine/Expressions/EXP_Python.h deleted file mode 100644 index f904151085e..00000000000 --- a/source/gameengine/Expressions/EXP_Python.h +++ /dev/null @@ -1,82 +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 EXP_Python.h - * \ingroup expressions - */ - -#ifndef __EXP_PYTHON_H__ -#define __EXP_PYTHON_H__ - -//#define USE_DL_EXPORT - -/* python redefines, quiet the compiler */ -#ifdef _XOPEN_SOURCE -#undef _XOPEN_SOURCE -#endif - -#ifdef _POSIX_C_SOURCE -#undef _POSIX_C_SOURCE -#endif - -#ifdef WITH_PYTHON -#include "Python.h" - -#define USE_MATHUTILS // Blender 2.5x api will use mathutils, for a while we might want to test without it - -#endif - -#ifdef __FreeBSD__ -#include -#if __FreeBSD_version > 500039 -#undef isalnum -#undef isalpha -#undef iscntrl -#undef isdigit -#undef isgraph -#undef islower -#undef isprint -#undef ispunct -#undef isspace -#undef isupper -#undef isxdigit -#undef tolower -#undef toupper -#endif -#endif - -#ifdef __APPLE__ -#undef isalnum -#undef isalpha -#undef islower -#undef isspace -#undef isupper -#undef tolower -#undef toupper -#endif - -#endif /* __EXP_PYTHON_H__ */ diff --git a/source/gameengine/Expressions/EXP_PythonCallBack.h b/source/gameengine/Expressions/EXP_PythonCallBack.h deleted file mode 100644 index f0cbcac0c6f..00000000000 --- a/source/gameengine/Expressions/EXP_PythonCallBack.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. - * - * Contributor(s): Porteries Tristan. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file EXP_PythonCallBack.h - * \ingroup expressions - */ - -#ifndef __EXP_PYTHON_CALLBACK_H__ -#define __EXP_PYTHON_CALLBACK_H__ - -#include "EXP_Python.h" - -/** Execute each functions with at least one argument - * \param functionlist The python list which contains callbacks. - * \param arglist The first item in the tuple to execute callbacks (can be NULL for no arguments). - * \param minargcount The minimum of quantity of arguments possible. - * \param maxargcount The maximum of quantity of arguments possible. - */ -void RunPythonCallBackList(PyObject *functionlist, PyObject **arglist, unsigned int minargcount, unsigned int maxargcount); - -#endif // __EXP_PYTHON_CALLBACK_H__ diff --git a/source/gameengine/Expressions/EXP_StringValue.h b/source/gameengine/Expressions/EXP_StringValue.h deleted file mode 100644 index ca59ebf1f82..00000000000 --- a/source/gameengine/Expressions/EXP_StringValue.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * StringValue.h: interface for the CStringValue class. - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -/** \file EXP_StringValue.h - * \ingroup expressions - */ - -#ifndef __EXP_STRINGVALUE_H__ -#define __EXP_STRINGVALUE_H__ - -#include "EXP_Value.h" - -class CStringValue : public CPropValue -{ - - - //PLUGIN_DECLARE_SERIAL(CStringValue,CValue) -public: - /// Construction / destruction - CStringValue(); - CStringValue(const char *txt, const char *name, AllocationTYPE alloctype = CValue::HEAPVALUE); - - virtual ~CStringValue() {} - /// CValue implementation - virtual bool IsEqual(const STR_String & other); - virtual const STR_String & GetText(); - virtual double GetNumber(); - virtual int GetValueType(); - - virtual CValue* Calc(VALUE_OPERATOR op, CValue *val); - virtual CValue* CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val); - virtual void SetValue(CValue* newval) { m_strString = newval->GetText(); SetModified(true); } - virtual CValue* GetReplica(); -#ifdef WITH_PYTHON - virtual PyObject* ConvertValueToPython() { - return PyUnicode_From_STR_String(m_strString); - } -#endif /* WITH_PYTHON */ - -private: - // data member - STR_String m_strString; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:CStringValue") -#endif -}; - -#endif /* __EXP_STRINGVALUE_H__ */ diff --git a/source/gameengine/Expressions/EXP_Value.h b/source/gameengine/Expressions/EXP_Value.h deleted file mode 100644 index 014fc59405f..00000000000 --- a/source/gameengine/Expressions/EXP_Value.h +++ /dev/null @@ -1,432 +0,0 @@ -/* - * Value.h: interface for the CValue class. - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -/** \file EXP_Value.h - * \ingroup expressions - */ - -#ifndef __EXP_VALUE_H__ -#define __EXP_VALUE_H__ - -#ifdef _MSC_VER -# pragma warning (disable:4786) -#endif - -#include // array functionality for the propertylist -#include "STR_String.h" // STR_String class - -using namespace std; - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -#ifndef GEN_NO_ASSERT -#undef assert -#define assert(exp) ((void)NULL) -#endif - - -#ifndef GEN_NO_TRACE -#undef trace -#define trace(exp) ((void)NULL) -#endif - -#ifndef GEN_NO_DEBUG -#undef debug -#define debug(exp) ((void)NULL) -#endif - -#ifndef GEN_NO_ASSERTD -#undef assertd -#define assertd(exp) ((void)NULL) -#endif - -enum VALUE_OPERATOR { - - VALUE_MOD_OPERATOR, // % - VALUE_ADD_OPERATOR, // + - VALUE_SUB_OPERATOR, // - - VALUE_MUL_OPERATOR, // * - VALUE_DIV_OPERATOR, // / - VALUE_NEG_OPERATOR, // - - VALUE_POS_OPERATOR, // + - VALUE_AND_OPERATOR, // && - VALUE_OR_OPERATOR, // || - VALUE_EQL_OPERATOR, // == - VALUE_NEQ_OPERATOR, // != - VALUE_GRE_OPERATOR, // > - VALUE_LES_OPERATOR, // < - VALUE_GEQ_OPERATOR, // >= - VALUE_LEQ_OPERATOR, // <= - VALUE_NOT_OPERATOR, // ! - VALUE_NO_OPERATOR // no operation at all -}; - -enum VALUE_DATA_TYPE { - VALUE_NO_TYPE, // abstract baseclass - VALUE_INT_TYPE, - VALUE_FLOAT_TYPE, - VALUE_STRING_TYPE, - VALUE_BOOL_TYPE, - VALUE_ERROR_TYPE, - VALUE_EMPTY_TYPE, - VALUE_LIST_TYPE, - VALUE_VOID_TYPE, - VALUE_VECTOR_TYPE, - VALUE_MAX_TYPE //only here to provide number of types -}; - - - -#ifdef DEBUG -//extern int gRefCountValue; // debugonly variable to check if all CValue Refences are Dereferenced at programexit -#endif - -struct HashableInt -{ - HashableInt(int id) : mData(id) { } - - unsigned long Hash() const { return 0;} ////}gHash(&mData, sizeof(int));} - - bool operator==(HashableInt rhs) { return mData == rhs.mData; } - - int mData; -}; - - -// -// Bitfield that stores the flags for each CValue derived class -// -struct ValueFlags { - ValueFlags() : - Modified(true), - Selected(false), - Affected(false), - ReleaseRequested(false), - Error(false), - RefCountDisabled(false), - HasProperties(false), - HasName(false), - Visible(true), - CustomFlag1(false), - CustomFlag2(false) - { - } - - unsigned short Modified : 1; - unsigned short Selected : 1; - unsigned short Affected : 1; - unsigned short ReleaseRequested : 1; - unsigned short Error : 1; - unsigned short RefCountDisabled : 1; - unsigned short HasProperties : 1; - unsigned short HasName : 1; - unsigned short Visible : 1; - unsigned short CustomFlag1 : 1; - unsigned short CustomFlag2 : 1; - - -}; - -/** - * Base Class for all Actions performed on CValue's. Can be extended for undo/redo system in future. - */ -class CAction -{ -public: - CAction() { - }; - virtual ~CAction() { - }; - virtual void Execute() const =0; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:CAction") -#endif -}; - - -#include "EXP_PyObjectPlus.h" -#ifdef WITH_PYTHON -#include "object.h" -#endif - -/** - * Baseclass CValue - * - * Together with CExpression, CValue and it's derived classes can be used to - * parse expressions into a parsetree with error detecting/correcting capabilities - * also expandable by a CFactory pluginsystem - * - * Base class for all editor functionality, flexible object type that allows - * calculations and uses reference counting for memory management. - * - * Features: - * - Reference Counting (AddRef() / Release()) - * - Calculations (Calc() / CalcFinal()) - * - Configuration (Configure()) - * - Serialization (EdSerialize() / EdIdSerialize() / EdPtrSerialize() and macro PLUGIN_DECLARE_SERIAL - * - Property system (SetProperty() / GetProperty() / FindIdentifier()) - * - Replication (GetReplica()) - * - Flags (IsSelected() / IsModified() / SetSelected()...) - * - * - Some small editor-specific things added - * - A helperclass CompressorArchive handles the serialization - * - */ -class CValue : public PyObjectPlus - -{ -Py_Header -public: - enum AllocationTYPE { - STACKVALUE = 0, - HEAPVALUE = 1 - }; - - enum DrawTYPE { - STARTFRAME = 0, - ENDFRAME = 1, - INTERFRAME = 2 - }; - - - // Construction / Destruction - CValue(); - -#ifdef WITH_PYTHON - //static PyObject *PyMake(PyObject *, PyObject *); - virtual PyObject *py_repr(void) - { - return PyUnicode_From_STR_String(GetText()); - } - - virtual PyObject *ConvertValueToPython() { - return NULL; - } - - virtual CValue *ConvertPythonToValue(PyObject *pyobj, const bool do_type_exception, const char *error_prefix); - - static PyObject *pyattr_get_name(void *self, const KX_PYATTRIBUTE_DEF *attrdef); - - virtual PyObject *ConvertKeysToPython( void ); -#endif /* WITH_PYTHON */ - - - - // Expression Calculation - virtual CValue* Calc(VALUE_OPERATOR op, CValue *val) = 0; - virtual CValue* CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val) = 0; - virtual void SetOwnerExpression(class CExpression* expr); - - - - void Execute(const CAction& a) - { - a.Execute(); - }; - - /// Reference Counting - int GetRefCount() - { - return m_refcount; - } - - // Add a reference to this value - CValue *AddRef() - { - // Increase global reference count, used to see at the end of the program - // if all CValue-derived classes have been dereferenced to 0 - //debug(gRefCountValue++); -#ifdef DEBUG - //gRefCountValue++; -#endif - m_refcount++; - return this; - } - - // Release a reference to this value (when reference count reaches 0, the value is removed from the heap) - int Release() - { - // Decrease global reference count, used to see at the end of the program - // if all CValue-derived classes have been dereferenced to 0 - //debug(gRefCountValue--); -#ifdef DEBUG - //gRefCountValue--; -#endif - // Decrease local reference count, if it reaches 0 the object should be freed - if (--m_refcount > 0) - { - // Reference count normal, return new reference count - return m_refcount; - } - else - { - // Reference count reached 0, delete ourselves and return 0 - // MT_assert(m_refcount==0, "Reference count reached sub-zero, object released too much"); - - delete this; - return 0; - } - } - - - /// Property Management - virtual void SetProperty(const STR_String& name,CValue* ioProperty); // Set property , overwrites and releases a previous property with the same name if needed - virtual void SetProperty(const char* name,CValue* ioProperty); - virtual CValue* GetProperty(const char* inName); // Get pointer to a property with name , returns NULL if there is no property named - virtual CValue* GetProperty(const STR_String & inName); - const STR_String& GetPropertyText(const STR_String & inName); // Get text description of property with name , returns an empty string if there is no property named - float GetPropertyNumber(const STR_String& inName,float defnumber); - virtual bool RemoveProperty(const char *inName); // Remove the property named , returns true if the property was succesfully removed, false if property was not found or could not be removed - virtual vector GetPropertyNames(); - virtual void ClearProperties(); // Clear all properties - - virtual void SetPropertiesModified(bool inModified); // Set all properties' modified flag to - virtual bool IsAnyPropertyModified(); // Check if any of the properties in this value have been modified - - virtual CValue* GetProperty(int inIndex); // Get property number - virtual int GetPropertyCount(); // Get the amount of properties assiocated with this value - - virtual CValue* FindIdentifier(const STR_String& identifiername); - /** Set the wireframe color of this value depending on the CSG - * operator type - * \attention: not implemented */ - virtual void SetColorOperator(VALUE_OPERATOR op); - - virtual const STR_String & GetText() = 0; - virtual double GetNumber() = 0; - virtual int GetValueType(); // Get Prop value type - double* ZeroVector() { return m_sZeroVec; } - virtual double* GetVector3(bool bGetTransformedVec = false); - - virtual STR_String& GetName() = 0; // Retrieve the name of the value - virtual void SetName(const char *name) = 0; // Set the name of the value - /** Sets the value to this cvalue. - * \attention this particular function should never be called. Why not abstract? */ - virtual void SetValue(CValue* newval); - virtual CValue* GetReplica() =0; - virtual void ProcessReplica(); - //virtual CValue* Copy() = 0; - - STR_String op2str(VALUE_OPERATOR op); - - // setting / getting flags - inline void SetSelected(bool bSelected) { m_ValFlags.Selected = bSelected; } - virtual void SetModified(bool bModified) { m_ValFlags.Modified = bModified; } - virtual void SetAffected(bool bAffected=true) { m_ValFlags.Affected = bAffected; } - inline void SetReleaseRequested(bool bReleaseRequested) { m_ValFlags.ReleaseRequested=bReleaseRequested; } - inline void SetError(bool err) { m_ValFlags.Error=err; } - inline void SetVisible (bool vis) { m_ValFlags.Visible=vis; } - - virtual bool IsModified() { return m_ValFlags.Modified; } - inline bool IsError() { return m_ValFlags.Error; } - virtual bool IsAffected() { return m_ValFlags.Affected || m_ValFlags.Modified; } - virtual bool IsSelected() { return m_ValFlags.Selected; } - inline bool IsReleaseRequested() { return m_ValFlags.ReleaseRequested; } - virtual bool IsVisible() { return m_ValFlags.Visible;} - virtual void SetCustomFlag1(bool bCustomFlag) { m_ValFlags.CustomFlag1 = bCustomFlag;} - virtual bool IsCustomFlag1() { return m_ValFlags.CustomFlag1;} - - virtual void SetCustomFlag2(bool bCustomFlag) { m_ValFlags.CustomFlag2 = bCustomFlag;} - virtual bool IsCustomFlag2() { return m_ValFlags.CustomFlag2;} - -protected: - virtual void DisableRefCount(); // Disable reference counting for this value - //virtual void AddDataToReplica(CValue* replica); - virtual ~CValue(); -private: - // Member variables - std::map* m_pNamedPropertyArray; // Properties for user/game etc - ValueFlags m_ValFlags; // Frequently used flags in a bitfield (low memoryusage) - int m_refcount; // Reference Counter - static double m_sZeroVec[3]; - -}; - - - -// -// Declare a CValue or CExpression or CWhatever to be serialized by the editor. -// -// This macro introduces the EdSerialize() function (which must be implemented by -// the client) and the EdIdSerialize() function (which is implemented by this macro). -// -// The generated Copy() function returns a pointer to type -// of object. So, for *any* CValue-derived object this should be set to CValue, -// for *any* CExpression-derived object this should be set to CExpression. -// -#define PLUGIN_DECLARE_SERIAL(class_name, root_base_class_name) \ -public: \ - virtual root_base_class_name *Copy() { \ - return new class_name; \ - } \ - virtual bool EdSerialize(CompressorArchive& arch, \ - class CFactoryManager* facmgr, \ - bool bIsStoring); \ - virtual bool EdIdSerialize(CompressorArchive& arch, \ - class CFactoryManager* facmgr, \ - bool bIsStoring) \ - { \ - if (bIsStoring) \ - arch.StoreString(#class_name); \ - return false; \ - } \ - - -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -// CPropValue is a CValue derived class, that implements the identification (String name) -// SetName() / GetName(), -// normal classes should derive from CPropValue, real lightweight classes straight from CValue - - -class CPropValue : public CValue -{ -public: - CPropValue() : - CValue(), - m_strNewName() - - { - } - - virtual ~CPropValue() - { - } - - virtual void SetName(const char *name) { - m_strNewName = name; - } - - virtual STR_String& GetName() { - //STR_String namefromprop = GetPropertyText("Name"); - //if (namefromprop.Length() > 0) - // return namefromprop; - return m_strNewName; - } // name of Value - -protected: - STR_String m_strNewName; // Identification - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:CPropValue") -#endif -}; - -#endif /* __EXP_VALUE_H__ */ diff --git a/source/gameengine/Expressions/EXP_VectorValue.h b/source/gameengine/Expressions/EXP_VectorValue.h deleted file mode 100644 index d87d5097156..00000000000 --- a/source/gameengine/Expressions/EXP_VectorValue.h +++ /dev/null @@ -1,94 +0,0 @@ -/* - * VectorValue.h: interface for the CVectorValue class. - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -/** \file EXP_VectorValue.h - * \ingroup expressions - */ - -#ifndef __EXP_VECTORVALUE_H__ -#define __EXP_VECTORVALUE_H__ - -#include "EXP_Value.h" - -#define KX_X 0 -#define KX_Y 1 -#define KX_Z 2 - - -class CVectorValue : public CPropValue -{ - //PLUGIN_DECLARE_SERIAL(CVectorValue,CValue) - -public: - //void Transform(rcMatrix4x4 mat); - virtual void SetValue(CValue* newval); - void SetVector(double newvec[]); - void Configure(CValue* menuvalue); - virtual double* GetVector3(bool bGetTransformedVec=false); - virtual double GetNumber(); - virtual int GetValueType(); - - CValue* Calc(VALUE_OPERATOR op, CValue *val) { - return val->CalcFinal(VALUE_VECTOR_TYPE, op, this); - } - - CValue* CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val); - - - CVectorValue(double vec[3], const char *name,AllocationTYPE alloctype=CValue::HEAPVALUE); - CVectorValue() {}; - - CVectorValue(double vec[3], AllocationTYPE alloctype=CValue::HEAPVALUE); - CVectorValue(float x,float y,float z, AllocationTYPE alloctype = CValue::HEAPVALUE); - virtual ~CVectorValue(); - //virtual bool ExportT3D(File *txtfile,bool bNoName=false); - void AddConfigurationData(CValue* menuvalue); - - - - virtual CValue* GetReplica(); - virtual const STR_String & GetText(); - -#if 0 - void SnapPoint(float num,int snap) - { - if (num > 0) num += ((float)snap / 2); - else num -= ((float)snap / 2); - num = (long)(((long)(num / snap)) * snap); - }; - - void SnapPosition(const double snapvec[]) - { - - if (snapvec[KX_X] >= 1) - SnapPoint(m_vec[KX_X],snapvec[KX_X]); - if (snapvec[KX_Y] >= 1) - SnapPoint(m_vec[KX_Y],snapvec[KX_Y]); - if (snapvec[KX_Z] >= 1) - SnapPoint(m_vec[KX_Z],snapvec[KX_Z]); - - } -#endif - -protected: - double m_vec[3]; - double m_transformedvec[3]; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:CVectorValue") -#endif -}; - -#endif /* __EXP_VECTORVALUE_H__ */ diff --git a/source/gameengine/Expressions/EXP_VoidValue.h b/source/gameengine/Expressions/EXP_VoidValue.h deleted file mode 100644 index 8b2c29488d7..00000000000 --- a/source/gameengine/Expressions/EXP_VoidValue.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * VoidValue.h: interface for the CVoidValue class. - * - * ***** 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 EXP_VoidValue.h - * \ingroup expressions - */ - -#ifndef __EXP_VOIDVALUE_H__ -#define __EXP_VOIDVALUE_H__ - -#include "EXP_Value.h" - -// -// Void value, used to transport *any* type of data -// -class CVoidValue : public CPropValue -{ - //PLUGIN_DECLARE_SERIAL (CVoidValue,CValue) - -public: - /// Construction/destruction - CVoidValue() : m_bDeleteOnDestruct(false), m_pAnything(NULL) { } - CVoidValue(void *voidptr, bool bDeleteOnDestruct, AllocationTYPE alloctype) : - m_bDeleteOnDestruct(bDeleteOnDestruct), - m_pAnything(voidptr) - { - if (alloctype == STACKVALUE) { - CValue::DisableRefCount(); - } - } - virtual ~CVoidValue(); /* Destruct void value, delete memory if we're owning it */ - - /// Value -> String or number - virtual const STR_String & GetText(); /* Get string description of void value (unimplemented) */ - virtual double GetNumber() { return -1; } - virtual int GetValueType() { return VALUE_VOID_TYPE; } - - /// Value calculation - virtual CValue* Calc(VALUE_OPERATOR op, CValue *val); - virtual CValue* CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue* val); - - /// Value replication - virtual CValue* GetReplica(); - - /// Data members - bool m_bDeleteOnDestruct; - void* m_pAnything; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:CVoidValue") -#endif -}; - -#endif /* __EXP_VOIDVALUE_H__ */ diff --git a/source/gameengine/Expressions/intern/BoolValue.cpp b/source/gameengine/Expressions/intern/BoolValue.cpp deleted file mode 100644 index 1523a9212ba..00000000000 --- a/source/gameengine/Expressions/intern/BoolValue.cpp +++ /dev/null @@ -1,216 +0,0 @@ -/** \file gameengine/Expressions/BoolValue.cpp - * \ingroup expressions - */ - -// BoolValue.cpp: implementation of the CBoolValue class. -/* - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -#include "EXP_BoolValue.h" -#include "EXP_StringValue.h" -#include "EXP_ErrorValue.h" -#include "EXP_VoidValue.h" - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -const STR_String CBoolValue::sTrueString = "TRUE"; -const STR_String CBoolValue::sFalseString = "FALSE"; - -CBoolValue::CBoolValue() -/* - * pre: false - * effect: constructs a new CBoolValue - */ -{ - trace("Bool constructor error"); -} - - - -CBoolValue::CBoolValue(bool inBool) -: m_bool(inBool) -{ -} // Constructs a new CBoolValue containing - - - -CBoolValue::CBoolValue(bool innie,const char *name,AllocationTYPE alloctype) -{ - m_bool = innie; - SetName(name); - - if (alloctype == CValue::STACKVALUE) - CValue::DisableRefCount(); -} - - - -void CBoolValue::SetValue(CValue* newval) -{ - m_bool = (newval->GetNumber() != 0); - SetModified(true); -} - - - -CValue* CBoolValue::Calc(VALUE_OPERATOR op, CValue *val) -/* -pre: -ret: a new object containing the result of applying operator op to this -object and val -*/ -{ - switch (op) - { - case VALUE_POS_OPERATOR: - case VALUE_NEG_OPERATOR: - { - return new CErrorValue (op2str(op) + GetText()); - break; - } - case VALUE_NOT_OPERATOR: - { - return new CBoolValue (!m_bool); - break; - } - default: - { - return val->CalcFinal(VALUE_BOOL_TYPE, op, this); - break; - } - } -} - - - -CValue* CBoolValue::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val) -/* -pre: the type of val is dtype -ret: a new object containing the result of applying operator op to val and -this object -*/ -{ - CValue *ret; - - switch (dtype) { - case VALUE_EMPTY_TYPE: - case VALUE_BOOL_TYPE: - { - switch (op) { - case VALUE_AND_OPERATOR: - { - ret = new CBoolValue (((CBoolValue *) val)->GetBool() && m_bool); - break; - } - case VALUE_OR_OPERATOR: - { - ret = new CBoolValue (((CBoolValue *) val)->GetBool() || m_bool); - break; - } - case VALUE_EQL_OPERATOR: - { - ret = new CBoolValue (((CBoolValue *) val)->GetBool() == m_bool); - break; - } - case VALUE_NEQ_OPERATOR: - { - ret = new CBoolValue (((CBoolValue *) val)->GetBool() != m_bool); - break; - } - case VALUE_NOT_OPERATOR: - { - return new CBoolValue (!m_bool); - break; - } - default: - { - ret = new CErrorValue(val->GetText() + op2str(op) + - "[operator not allowed on booleans]"); - break; - } - } - break; - } - case VALUE_STRING_TYPE: - { - switch (op) { - case VALUE_ADD_OPERATOR: - { - ret = new CStringValue(val->GetText() + GetText(),""); - break; - } - default: - { - ret = new CErrorValue(val->GetText() + op2str(op) + "[Only + allowed on boolean and string]"); - break; - } - } - break; - } - default: - ret = new CErrorValue("[type mismatch]" + op2str(op) + GetText()); - } - - return ret; -} - - - -bool CBoolValue::GetBool() -/* -pre: -ret: the bool stored in the object -*/ -{ - return m_bool; -} - - - -double CBoolValue::GetNumber() -{ - return (double)m_bool; -} - - - -int CBoolValue::GetValueType() -{ - return VALUE_BOOL_TYPE; -} - - - -const STR_String& CBoolValue::GetText() -{ - return m_bool ? sTrueString : sFalseString; -} - - - -CValue* CBoolValue::GetReplica() -{ - CBoolValue* replica = new CBoolValue(*this); - replica->ProcessReplica(); - - return replica; -} - -#ifdef WITH_PYTHON -PyObject *CBoolValue::ConvertValueToPython() -{ - return PyBool_FromLong(m_bool != 0); -} -#endif // WITH_PYTHON diff --git a/source/gameengine/Expressions/intern/ConstExpr.cpp b/source/gameengine/Expressions/intern/ConstExpr.cpp deleted file mode 100644 index 597427ecfe5..00000000000 --- a/source/gameengine/Expressions/intern/ConstExpr.cpp +++ /dev/null @@ -1,131 +0,0 @@ -/** \file gameengine/Expressions/ConstExpr.cpp - * \ingroup expressions - */ -// ConstExpr.cpp: implementation of the CConstExpr class. - -/* - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -#include "EXP_Value.h" // for precompiled header -#include "EXP_ConstExpr.h" -#include "EXP_VectorValue.h" - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -CConstExpr::CConstExpr() -{ -} - - - -CConstExpr::CConstExpr(CValue* constval) -/* -pre: -effect: constructs a CConstExpr cointing the value constval -*/ -{ - m_value = constval; -// m_bModified=true; -} - - - -CConstExpr::~CConstExpr() -/* -pre: -effect: deletes the object -*/ -{ - if (m_value) - m_value->Release(); -} - - - -unsigned char CConstExpr::GetExpressionID() -{ - return CCONSTEXPRESSIONID; -} - - - -CValue* CConstExpr::Calculate() -/* -pre: -ret: a new object containing the value of the stored CValue -*/ -{ - return m_value->AddRef(); -} - - - -void CConstExpr::ClearModified() -{ - if (m_value) - { - m_value->SetModified(false); - m_value->SetAffected(false); - } -} - - - -double CConstExpr::GetNumber() -{ - return -1; -} - - - -bool CConstExpr::NeedsRecalculated() -{ - return m_value->IsAffected(); // IsAffected is m_bModified OR m_bAffected !!! -} - - - -CExpression* CConstExpr::CheckLink(std::vector& brokenlinks) -{ -// parent checks if child is still useful. -// When for example it's value it's deleted flag set -// then release Value, and return NULL in case of constexpression -// else return this... - - assertd(m_value); - if (m_value->IsReleaseRequested()) - { - AddRef(); //numchanges++; - return Release(); - } - else - return this; -} - - - -void CConstExpr::BroadcastOperators(VALUE_OPERATOR op) -{ - assertd(m_value); - m_value->SetColorOperator(op); -} - - - -bool CConstExpr::MergeExpression(CExpression *otherexpr) -{ - assertd(false); - return false; -} diff --git a/source/gameengine/Expressions/intern/EmptyValue.cpp b/source/gameengine/Expressions/intern/EmptyValue.cpp deleted file mode 100644 index 9227626777d..00000000000 --- a/source/gameengine/Expressions/intern/EmptyValue.cpp +++ /dev/null @@ -1,133 +0,0 @@ -/** \file gameengine/Expressions/EmptyValue.cpp - * \ingroup expressions - */ - -// EmptyValue.cpp: implementation of the CEmptyValue class. -/* - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -#include "EXP_EmptyValue.h" -#include "EXP_IntValue.h" -#include "EXP_FloatValue.h" -#include "EXP_StringValue.h" -#include "EXP_ErrorValue.h" -#include "EXP_ListValue.h" -#include "EXP_VoidValue.h" - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -CEmptyValue::CEmptyValue() -/* - * pre: - * effect: constructs a new CEmptyValue - */ -{ - SetModified(false); -} - - - -CEmptyValue::~CEmptyValue() -/* - * pre: - * effect: deletes the object - */ -{ - -} - - - -CValue *CEmptyValue::Calc(VALUE_OPERATOR op, CValue *val) -/* - * pre: - * ret: a new object containing the result of applying operator op to this - * object and val - */ -{ - return val->CalcFinal(VALUE_EMPTY_TYPE, op, this); - -} - - - -CValue * CEmptyValue::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val) -/* - * pre: the type of val is dtype - * ret: a new object containing the result of applying operator op to val and - * this object - */ -{ - return val->AddRef(); -} - - - -double CEmptyValue::GetNumber() -{ - return 0; -} - - - -int CEmptyValue::GetValueType() -{ - return VALUE_EMPTY_TYPE; -} - - - -CListValue* CEmptyValue::GetPolySoup() -{ - CListValue* soup = new CListValue(); - //don't add any poly, while it's an empty value - return soup; -} - - - -bool CEmptyValue::IsInside(CValue* testpoint,bool bBorderInclude) -{ - // empty space is solid, so always inside - return true; -} - - - -double* CEmptyValue::GetVector3(bool bGetTransformedVec) -{ - assertd(false); // don't get vector from me - return ZeroVector(); -} - - - -static STR_String emptyString = STR_String(""); - - -const STR_String & CEmptyValue::GetText() -{ - return emptyString; -} - - - -CValue* CEmptyValue::GetReplica() -{ - CEmptyValue* replica = new CEmptyValue(*this); - replica->ProcessReplica(); - return replica; -} - diff --git a/source/gameengine/Expressions/intern/ErrorValue.cpp b/source/gameengine/Expressions/intern/ErrorValue.cpp deleted file mode 100644 index c03ceb88073..00000000000 --- a/source/gameengine/Expressions/intern/ErrorValue.cpp +++ /dev/null @@ -1,131 +0,0 @@ -/** \file gameengine/Expressions/ErrorValue.cpp - * \ingroup expressions - */ -// ErrorValue.cpp: implementation of the CErrorValue class. -/* - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -#include "EXP_ErrorValue.h" - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -CErrorValue::CErrorValue() -/* -pre: -effect: constructs a new CErrorValue containing errormessage "Error" -*/ -{ - m_strErrorText = "Error"; - SetError(true); -} - - - -CErrorValue::CErrorValue(const char *errmsg) -/* -pre: -effect: constructs a new CErrorValue containing errormessage errmsg -*/ -{ - m_strErrorText = "["; - m_strErrorText += errmsg; - m_strErrorText += "]"; - SetError(true); -} - - - -CErrorValue::~CErrorValue() -/* -pre: -effect: deletes the object -*/ -{ - -} - - - -CValue* CErrorValue::Calc(VALUE_OPERATOR op, CValue *val) -/* -pre: -ret: a new object containing the result of applying operator op to this - object and val -*/ -{ - CValue* errorval; - - switch (op) - { - case VALUE_POS_OPERATOR: - case VALUE_NEG_OPERATOR: - case VALUE_NOT_OPERATOR: - { - errorval = new CErrorValue (op2str(op) + GetText()); - break; - } - default: - { - errorval = val->CalcFinal(VALUE_ERROR_TYPE, op, this); - break; - } - } - - return errorval; -} - - - -CValue* CErrorValue::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val) -/* -pre: the type of val is dtype -ret: a new object containing the result of applying operator op to val and - this object -*/ -{ - return new CErrorValue (val->GetText() + op2str(op) + GetText()); -} - - - -double CErrorValue::GetNumber() -{ - return -1; -} - - - -int CErrorValue::GetValueType() -{ - return VALUE_ERROR_TYPE; -} - - - -const STR_String & CErrorValue::GetText() -{ - return m_strErrorText; -} - - - -CValue* CErrorValue::GetReplica() -{ - // who would want a copy of an error ? - trace ("Error: ErrorValue::GetReplica() not implemented yet"); - assertd(false); - - return NULL; -} diff --git a/source/gameengine/Expressions/intern/Expression.cpp b/source/gameengine/Expressions/intern/Expression.cpp deleted file mode 100644 index 6a98a15aa12..00000000000 --- a/source/gameengine/Expressions/intern/Expression.cpp +++ /dev/null @@ -1,77 +0,0 @@ -/** \file gameengine/Expressions/Expression.cpp - * \ingroup expressions - */ -// Expression.cpp: implementation of the CExpression class. -/* - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -#include "EXP_Expression.h" -#include "EXP_ErrorValue.h" - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// -#ifdef DEBUG -//int gRefCountExpr; -#endif -CExpression::CExpression()// : m_cached_calculate(NULL) -{ - m_refcount = 1; -#ifdef DEBUG - //gRefCountExpr++; -#endif -} - -CExpression::~CExpression() -{ - assert (m_refcount == 0); -} - - - -// destuctor for CBrokenLinkInfo -CBrokenLinkInfo::~CBrokenLinkInfo() -{ - if (m_pExpr && !m_bRestored) - m_pExpr->Release(); -} - - -void CBrokenLinkInfo::RestoreLink() -{ - - - assertd(m_pExpr); - - if (m_pExpr) - { - if (!m_bRestored) { - m_bRestored=true; - - } - if (*m_pmemExpr) - { - (*m_pmemExpr)->Release(); - } - *m_pmemExpr = m_pExpr; - -// m_pExpr=NULL; - } -} - -void CBrokenLinkInfo::BreakLink() -{ - m_bRestored=false; - m_pExpr->AddRef(); -} - diff --git a/source/gameengine/Expressions/intern/FloatValue.cpp b/source/gameengine/Expressions/intern/FloatValue.cpp deleted file mode 100644 index 0f86a429d81..00000000000 --- a/source/gameengine/Expressions/intern/FloatValue.cpp +++ /dev/null @@ -1,329 +0,0 @@ -/** \file gameengine/Expressions/FloatValue.cpp - * \ingroup expressions - */ -// FloatValue.cpp: implementation of the CFloatValue class. -/* - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -#include "EXP_FloatValue.h" -#include "EXP_IntValue.h" -#include "EXP_StringValue.h" -#include "EXP_BoolValue.h" -#include "EXP_ErrorValue.h" -#include "EXP_VoidValue.h" - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -CFloatValue::CFloatValue() -/* -pre: false -effect: constructs a new CFloatValue -*/ -{ - m_pstrRep=NULL; -} - - - -CFloatValue::CFloatValue(float fl) -/* -pre: -effect: constructs a new CFloatValue containing value fl -*/ -{ - m_float = fl; - m_pstrRep=NULL; -} - - - -CFloatValue::CFloatValue(float fl,const char *name,AllocationTYPE alloctype) -/* -pre: -effect: constructs a new CFloatValue containing value fl -*/ -{ - - m_float = fl; - SetName(name); - if (alloctype==CValue::STACKVALUE) - { - CValue::DisableRefCount(); - - } - m_pstrRep=NULL; -} - - - -CFloatValue::~CFloatValue() -/* -pre: -effect: deletes the object -*/ -{ - if (m_pstrRep) - delete m_pstrRep; -} - - - -CValue* CFloatValue::Calc(VALUE_OPERATOR op, CValue *val) -/* -pre: -ret: a new object containing the result of applying operator op to this - object and val -*/ -{ - //return val->CalcFloat(op, this); - switch (op) - { - case VALUE_POS_OPERATOR: - return new CFloatValue (m_float); - break; - case VALUE_NEG_OPERATOR: - return new CFloatValue (-m_float); - break; - case VALUE_NOT_OPERATOR: - return new CBoolValue (m_float == 0.f); - break; - case VALUE_AND_OPERATOR: - case VALUE_OR_OPERATOR: - return new CErrorValue(val->GetText() + op2str(op) + "only allowed on booleans"); - break; - default: - return val->CalcFinal(VALUE_FLOAT_TYPE, op, this); - break; - } -} - - - -CValue* CFloatValue::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val) -/* -pre: the type of val is dtype -ret: a new object containing the result of applying operator op to val and - this object -*/ -{ - CValue *ret; - - switch (dtype) { - case VALUE_INT_TYPE: - { - switch (op) { - case VALUE_MOD_OPERATOR: - ret = new CFloatValue(fmod(((CIntValue *) val)->GetInt(), m_float)); - break; - case VALUE_ADD_OPERATOR: - ret = new CFloatValue(((CIntValue *) val)->GetInt() + m_float); - break; - case VALUE_SUB_OPERATOR: - ret = new CFloatValue(((CIntValue *) val)->GetInt() - m_float); - break; - case VALUE_MUL_OPERATOR: - ret = new CFloatValue(((CIntValue *) val)->GetInt() * m_float); - break; - case VALUE_DIV_OPERATOR: - if (m_float == 0) - ret = new CErrorValue("Division by zero"); - else - ret = new CFloatValue (((CIntValue *) val)->GetInt() / m_float); - break; - case VALUE_EQL_OPERATOR: - ret = new CBoolValue(((CIntValue *) val)->GetInt() == m_float); - break; - case VALUE_NEQ_OPERATOR: - ret = new CBoolValue(((CIntValue *) val)->GetInt() != m_float); - break; - case VALUE_GRE_OPERATOR: - ret = new CBoolValue(((CIntValue *) val)->GetInt() > m_float); - break; - case VALUE_LES_OPERATOR: - ret = new CBoolValue(((CIntValue *) val)->GetInt() < m_float); - break; - case VALUE_GEQ_OPERATOR: - ret = new CBoolValue(((CIntValue *) val)->GetInt() >= m_float); - break; - case VALUE_LEQ_OPERATOR: - ret = new CBoolValue(((CIntValue *) val)->GetInt() <= m_float); - break; - case VALUE_NOT_OPERATOR: - ret = new CBoolValue(m_float == 0); - break; - default: - ret = new CErrorValue("illegal operator. please send a bug report."); - break; - } - break; - } - case VALUE_EMPTY_TYPE: - case VALUE_FLOAT_TYPE: - { - switch (op) { - case VALUE_MOD_OPERATOR: - ret = new CFloatValue(fmod(((CFloatValue *) val)->GetFloat(), m_float)); - break; - case VALUE_ADD_OPERATOR: - ret = new CFloatValue(((CFloatValue *) val)->GetFloat() + m_float); - break; - case VALUE_SUB_OPERATOR: - ret = new CFloatValue(((CFloatValue *) val)->GetFloat() - m_float); - break; - case VALUE_MUL_OPERATOR: - ret = new CFloatValue(((CFloatValue *) val)->GetFloat() * m_float); - break; - case VALUE_DIV_OPERATOR: - if (m_float == 0) - ret = new CErrorValue("Division by zero"); - else - ret = new CFloatValue (((CFloatValue *) val)->GetFloat() / m_float); - break; - case VALUE_EQL_OPERATOR: - ret = new CBoolValue(((CFloatValue *) val)->GetFloat() == m_float); - break; - case VALUE_NEQ_OPERATOR: - ret = new CBoolValue(((CFloatValue *) val)->GetFloat() != m_float); - break; - case VALUE_GRE_OPERATOR: - ret = new CBoolValue(((CFloatValue *) val)->GetFloat() > m_float); - break; - case VALUE_LES_OPERATOR: - ret = new CBoolValue(((CFloatValue *) val)->GetFloat() < m_float); - break; - case VALUE_GEQ_OPERATOR: - ret = new CBoolValue(((CFloatValue *) val)->GetFloat() >= m_float); - break; - case VALUE_LEQ_OPERATOR: - ret = new CBoolValue(((CFloatValue *) val)->GetFloat() <= m_float); - break; - case VALUE_NEG_OPERATOR: - ret = new CFloatValue (-m_float); - break; - case VALUE_POS_OPERATOR: - ret = new CFloatValue (m_float); - break; - case VALUE_NOT_OPERATOR: - ret = new CBoolValue(m_float == 0); - break; - default: - ret = new CErrorValue("illegal operator. please send a bug report."); - break; - } - break; - } - case VALUE_STRING_TYPE: - { - switch (op) { - case VALUE_ADD_OPERATOR: - ret = new CStringValue(val->GetText() + GetText(),""); - break; - case VALUE_EQL_OPERATOR: - case VALUE_NEQ_OPERATOR: - case VALUE_GRE_OPERATOR: - case VALUE_LES_OPERATOR: - case VALUE_GEQ_OPERATOR: - case VALUE_LEQ_OPERATOR: - ret = new CErrorValue("[Cannot compare string with float]" + op2str(op) + GetText()); - break; - default: - ret = new CErrorValue("[operator not allowed on strings]" + op2str(op) + GetText()); - break; - } - break; - } - case VALUE_BOOL_TYPE: - ret = new CErrorValue("[operator not valid on boolean and float]" + op2str(op) + GetText()); - break; - case VALUE_ERROR_TYPE: - ret = new CErrorValue(val->GetText() + op2str(op) + GetText()); - break; - default: - ret = new CErrorValue("illegal type. contact your dealer (if any)"); - break; - } - return ret; -} - - - -void CFloatValue::SetFloat(float fl) -{ - m_float = fl; - SetModified(true); -} - - - -float CFloatValue::GetFloat() -/* -pre: -ret: the float stored in the object -*/ -{ - return m_float; -} - - - -double CFloatValue::GetNumber() -{ - return m_float; -} - - - -int CFloatValue::GetValueType() -{ - return VALUE_FLOAT_TYPE; -} - - - -void CFloatValue::SetValue(CValue* newval) -{ - m_float = (float)newval->GetNumber(); - SetModified(true); -} - - - -const STR_String & CFloatValue::GetText() -{ - if (!m_pstrRep) - m_pstrRep = new STR_String(); - - m_pstrRep->Format("%f",m_float); - return *m_pstrRep; -} - - - -CValue* CFloatValue::GetReplica() -{ - CFloatValue* replica = new CFloatValue(*this); - replica->m_pstrRep = NULL; /* should be in CFloatValue::ProcessReplica() but its not defined, no matter */ - replica->ProcessReplica(); - - return replica; -} - - -#ifdef WITH_PYTHON -PyObject *CFloatValue::ConvertValueToPython() -{ - return PyFloat_FromDouble(m_float); -} -#endif // WITH_PYTHON diff --git a/source/gameengine/Expressions/intern/HashedPtr.cpp b/source/gameengine/Expressions/intern/HashedPtr.cpp deleted file mode 100644 index 11d9482f993..00000000000 --- a/source/gameengine/Expressions/intern/HashedPtr.cpp +++ /dev/null @@ -1,57 +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/Expressions/KX_HashedPtr.cpp - * \ingroup expressions - */ - - -#include "EXP_HashedPtr.h" - - -CHashedPtr::CHashedPtr(void* val) : m_valptr(val) -{ -} - - -unsigned int CHashedPtr::hash() const -{ -#if defined(_WIN64) - unsigned __int64 key = (unsigned __int64)m_valptr; -#else - unsigned long key = (unsigned long)m_valptr; -#endif - - key += ~(key << 16); - key ^= (key >> 5); - key += (key << 3); - key ^= (key >> 13); - key += ~(key << 9); - key ^= (key >> 17); - - return (unsigned int)(key & 0xffffffff); -} diff --git a/source/gameengine/Expressions/intern/IdentifierExpr.cpp b/source/gameengine/Expressions/intern/IdentifierExpr.cpp deleted file mode 100644 index 8fbbf41cd63..00000000000 --- a/source/gameengine/Expressions/intern/IdentifierExpr.cpp +++ /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 gameengine/Expressions/IdentifierExpr.cpp - * \ingroup expressions - */ - - -#include "EXP_IdentifierExpr.h" - -CIdentifierExpr::CIdentifierExpr(const STR_String& identifier,CValue* id_context) -:m_identifier(identifier) -{ - if (id_context) - m_idContext = id_context->AddRef(); - else - m_idContext=NULL; -} - - -CIdentifierExpr::~CIdentifierExpr() -{ - if (m_idContext) - m_idContext->Release(); -} - - - -CValue* CIdentifierExpr::Calculate() -{ - CValue* result = NULL; - if (m_idContext) - result = m_idContext->FindIdentifier(m_identifier); - - return result; -} - - - -bool CIdentifierExpr::MergeExpression(CExpression* otherexpr) -{ - return false; -} - - - -unsigned char CIdentifierExpr::GetExpressionID() -{ - return CIDENTIFIEREXPRESSIONID; -} - - - -bool CIdentifierExpr::NeedsRecalculated() -{ - return true; -} - - - -CExpression* CIdentifierExpr::CheckLink(std::vector& brokenlinks) -{ - assertd(false); // not implemented yet - return NULL; -} - - - -void CIdentifierExpr::ClearModified() -{ - assertd(false); // not implemented yet -} - - - -void CIdentifierExpr::BroadcastOperators(VALUE_OPERATOR op) -{ - assertd(false); // not implemented yet -} diff --git a/source/gameengine/Expressions/intern/IfExpr.cpp b/source/gameengine/Expressions/intern/IfExpr.cpp deleted file mode 100644 index b4e2fe7315b..00000000000 --- a/source/gameengine/Expressions/intern/IfExpr.cpp +++ /dev/null @@ -1,144 +0,0 @@ -/** \file gameengine/Expressions/IfExpr.cpp - * \ingroup expressions - */ -// IfExpr.cpp: implementation of the CIfExpr class. -/* - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -#include "EXP_IfExpr.h" -#include "EXP_EmptyValue.h" -#include "EXP_ErrorValue.h" -#include "EXP_BoolValue.h" - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - - -CIfExpr::CIfExpr() -{ -} - - - -/* - * pre: - * effect: constructs an CifExpr-object corresponding to IF(guard, e1, e2) - */ -CIfExpr::CIfExpr(CExpression *guard, CExpression *e1, CExpression *e2) -{ - m_guard = guard; - m_e1 = e1; - m_e2 = e2; -} - - - -/* - * pre: - * effect: dereferences the object - */ -CIfExpr::~CIfExpr() -{ - if (m_guard) - m_guard->Release(); - - if (m_e1) - m_e1->Release(); - - if (m_e2) - m_e2->Release(); -} - - - -/** - * pre: - * ret: a new object containing the value of m_e1 if m_guard is a boolean true - * a new object containing the value of m_e2 if m_guard is a boolean false - * an new errorvalue if m_guard is not a boolean - */ -CValue* CIfExpr::Calculate() -{ - CValue *guardval; - guardval = m_guard->Calculate(); - const STR_String& text = guardval->GetText(); - guardval->Release(); - - if (&text == &CBoolValue::sTrueString) - { - return m_e1->Calculate(); - } - else if (&text == &CBoolValue::sFalseString) - { - return m_e2->Calculate(); - } - else - { - return new CErrorValue("Guard should be of boolean type"); - } -} - - - -bool CIfExpr::MergeExpression(CExpression *otherexpr) -{ - assertd(false); - return false; -} - - - -bool CIfExpr::IsInside(float x,float y,float z,bool bBorderInclude) -{ - assertd(false); - return false; -} - - - -bool CIfExpr::NeedsRecalculated() -{ - return (m_guard->NeedsRecalculated() || - m_e1->NeedsRecalculated() || - m_e2->NeedsRecalculated()); -} - - - -CExpression* CIfExpr::CheckLink(std::vector& brokenlinks) -{ - assertd(false); - return NULL; -} - - - -void CIfExpr::ClearModified() -{ - assertd(false); -} - - - -void CIfExpr::BroadcastOperators(VALUE_OPERATOR op) -{ - assertd(false); -} - - - -unsigned char CIfExpr::GetExpressionID() -{ - return CIFEXPRESSIONID; -} diff --git a/source/gameengine/Expressions/intern/InputParser.cpp b/source/gameengine/Expressions/intern/InputParser.cpp deleted file mode 100644 index 583d8da63cb..00000000000 --- a/source/gameengine/Expressions/intern/InputParser.cpp +++ /dev/null @@ -1,669 +0,0 @@ -/** \file gameengine/Expressions/InputParser.cpp - * \ingroup expressions - */ -// Parser.cpp: implementation of the CParser class. -/* - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -#include - -#include "MT_assert.h" - -#include "EXP_Value.h" -#include "EXP_InputParser.h" -#include "EXP_ErrorValue.h" -#include "EXP_IntValue.h" -#include "EXP_StringValue.h" -#include "EXP_FloatValue.h" -#include "EXP_BoolValue.h" -#include "EXP_EmptyValue.h" -#include "EXP_ConstExpr.h" -#include "EXP_Operator2Expr.h" -#include "EXP_Operator1Expr.h" -#include "EXP_IdentifierExpr.h" - -// this is disable at the moment, I expected a memleak from it, but the error-cleanup was the reason -// well, looks we don't need it anyway, until maybe the Curved Surfaces are integrated into CSG -// cool things like (IF(LOD==1,CCurvedValue,IF(LOD==2,CCurvedValue2)) etc... -#include "EXP_IfExpr.h" - -#if defined(WIN32) || defined(WIN64) -#define strcasecmp _stricmp - -#ifndef strtoll -#define strtoll _strtoi64 -#endif - -#endif /* Def WIN32 or Def WIN64 */ - -#define NUM_PRIORITY 6 -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -CParser::CParser() : m_identifierContext(NULL) -{ -} - - - -CParser::~CParser() -{ - if (m_identifierContext) - m_identifierContext->Release(); -} - - - -void CParser::ScanError(const char *str) -{ - // sets the global variable errmsg to an errormessage with - // contents str, appending if it already exists - // AfxMessageBox("Parse Error:"+str,MB_ICONERROR); - if (errmsg) - errmsg = new COperator2Expr(VALUE_ADD_OPERATOR, errmsg, Error(str)); - else - errmsg = Error(str); - - sym = errorsym; -} - - - -CExpression* CParser::Error(const char *str) -{ - // makes and returns a new CConstExpr filled with an CErrorValue - // with string str - // AfxMessageBox("Error:"+str,MB_ICONERROR); - return new CConstExpr(new CErrorValue(str)); -} - - - -void CParser::NextCh() -{ - // sets the global variable ch to the next character, if it exists - // and increases the global variable chcount - chcount++; - - if (chcount < text.Length()) - ch = text[chcount]; - else - ch = 0x00; -} - - - -void CParser::TermChar(char c) -{ - // generates an error if the next char isn't the specified char c, - // otherwise, skip the char - if (ch == c) - { - NextCh(); - } - else - { - STR_String str; - str.Format("Warning: %c expected\ncontinuing without it", c); - trace(str); - } -} - - - -void CParser::DigRep() -{ - // changes the current character to the first character that - // isn't a decimal - while ((ch >= '0') && (ch <= '9')) - NextCh(); -} - - - -void CParser::CharRep() -{ - // changes the current character to the first character that - // isn't an alphanumeric character - while (((ch >= '0') && (ch <= '9')) - || ((ch >= 'a') && (ch <= 'z')) - || ((ch >= 'A') && (ch <= 'Z')) - || (ch == '.') || (ch == '_')) - NextCh(); -} - - - -void CParser::GrabString(int start) -{ - // puts part of the input string into the global variable - // const_as_string, from position start, to position chchount - const_as_string = text.Mid(start, chcount-start); -} - - - -void CParser::GrabRealString(int start) -{ - // works like GrabString but converting \\n to \n - // puts part of the input string into the global variable - // const_as_string, from position start, to position chchount - - int i; - char tmpch; - - const_as_string = STR_String(); - for (i=start;i': - sym = opsym; - NextCh(); - if (ch == '=') - { - opkind = OPgreaterequal; - NextCh(); - } - else - { - opkind = OPgreater; - } - break; - case '<': - sym = opsym; - NextCh(); - if (ch == '=') { - opkind = OPlessequal; - NextCh(); - } else { - opkind = OPless; - } - break; - case '\"' : - { - int start; - sym = constsym; - constkind = stringtype; - NextCh(); - start = chcount; - while ((ch != '\"') && (ch != 0x0)) - NextCh(); - GrabRealString(start); - TermChar('\"'); // check for eol before '\"' - break; - } - case 0x0: sym = eolsym; break; - default: - { - int start; - start = chcount; - DigRep(); - if ((start != chcount) || (ch == '.')) { // number - sym = constsym; - if (ch == '.') { - constkind = floattype; - NextCh(); - DigRep(); - } - else constkind = inttype; - if ((ch == 'e') || (ch == 'E')) { - int mark; - constkind = floattype; - NextCh(); - if ((ch == '+') || (ch == '-')) NextCh(); - mark = chcount; - DigRep(); - if (mark == chcount) { - ScanError("Number expected after 'E'"); - return; - } - } - GrabString(start); - } else if (((ch >= 'a') && (ch <= 'z')) - || ((ch >= 'A') && (ch <= 'Z'))) - { // reserved word? - - start = chcount; - CharRep(); - GrabString(start); - if (!strcasecmp(const_as_string, "SUM")) { - sym = sumsym; - } - else if (!strcasecmp(const_as_string, "NOT")) { - sym = opsym; - opkind = OPnot; - } - else if (!strcasecmp(const_as_string, "AND")) { - sym = opsym; opkind = OPand; - } - else if (!strcasecmp(const_as_string, "OR")) { - sym = opsym; opkind = OPor; - } - else if (!strcasecmp(const_as_string, "IF")) - sym = ifsym; - else if (!strcasecmp(const_as_string, "WHOMADE")) - sym = whocodedsym; - else if (!strcasecmp(const_as_string, "FALSE")) { - sym = constsym; constkind = booltype; boolvalue = false; - } else if (!strcasecmp(const_as_string, "TRUE")) { - sym = constsym; constkind = booltype; boolvalue = true; - } else { - sym = idsym; - //STR_String str; - //str.Format("'%s' makes no sense here", (const char*)funstr); - //ScanError(str); - } - } else { // unknown symbol - STR_String str; - str.Format("Unexpected character '%c'", ch); - NextCh(); - ScanError(str); - return; - } - } - } -} - -#if 0 -int CParser::MakeInt() -{ - // returns the integer representation of the value in the global - // variable const_as_string - // pre: const_as_string contains only numercal chars - return atoi(const_as_string); -} -#endif - -const char *CParser::Symbol2Str(int s) -{ - // returns a string representation of of symbol s, - // for use in Term when generating an error - switch (s) { - case errorsym: return "error"; - case lbracksym: return "("; - case rbracksym: return ")"; - case commasym: return ","; - case opsym: return "operator"; - case constsym: return "constant"; - case sumsym: return "SUM"; - case ifsym: return "IF"; - case whocodedsym: return "WHOMADE"; - case eolsym: return "end of line"; - case idsym: return "identifier"; - } - return "unknown"; // should not happen -} - -void CParser::Term(int s) -{ - // generates an error if the next symbol isn't the specified symbol s - // otherwise, skip the symbol - if (s == sym) { - NextSym(); - } - else { - STR_String msg; - msg.Format("Warning: %s expected\ncontinuing without it", Symbol2Str(s)); - -// AfxMessageBox(msg,MB_ICONERROR); - - trace(msg); - } -} - -int CParser::Priority(int optorkind) -{ - // returns the priority of an operator - // higher number means higher priority - switch (optorkind) { - case OPor: return 1; - case OPand: return 2; - case OPgreater: - case OPless: - case OPgreaterequal: - case OPlessequal: - case OPequal: - case OPunequal: return 3; - case OPplus: - case OPminus: return 4; - case OPmodulus: - case OPtimes: - case OPdivide: return 5; - } - MT_assert(false); - return 0; // should not happen -} - -CExpression *CParser::Ex(int i) -{ - // parses an expression in the imput, starting at priority i, and - // returns an CExpression, containing the parsed input - CExpression *e1 = NULL, *e2 = NULL; - int opkind2; - - if (i < NUM_PRIORITY) { - e1 = Ex(i + 1); - while ((sym == opsym) && (Priority(opkind) == i)) { - opkind2 = opkind; - NextSym(); - e2 = Ex(i + 1); - switch (opkind2) { - case OPmodulus: e1 = new COperator2Expr(VALUE_MOD_OPERATOR,e1, e2); break; - case OPplus: e1 = new COperator2Expr(VALUE_ADD_OPERATOR,e1, e2); break; - case OPminus: e1 = new COperator2Expr(VALUE_SUB_OPERATOR,e1, e2); break; - case OPtimes: e1 = new COperator2Expr(VALUE_MUL_OPERATOR,e1, e2); break; - case OPdivide: e1 = new COperator2Expr(VALUE_DIV_OPERATOR,e1, e2); break; - case OPand: e1 = new COperator2Expr(VALUE_AND_OPERATOR,e1, e2); break; - case OPor: e1 = new COperator2Expr(VALUE_OR_OPERATOR,e1, e2); break; - case OPequal: e1 = new COperator2Expr(VALUE_EQL_OPERATOR,e1, e2); break; - case OPunequal: e1 = new COperator2Expr(VALUE_NEQ_OPERATOR,e1, e2); break; - case OPgreater: e1 = new COperator2Expr(VALUE_GRE_OPERATOR,e1, e2); break; - case OPless: e1 = new COperator2Expr(VALUE_LES_OPERATOR,e1, e2); break; - case OPgreaterequal: e1 = new COperator2Expr(VALUE_GEQ_OPERATOR,e1, e2); break; - case OPlessequal: e1 = new COperator2Expr(VALUE_LEQ_OPERATOR,e1, e2); break; - default: MT_assert(false); break; // should not happen - } - } - } else if (i == NUM_PRIORITY) { - if ((sym == opsym) - && ( (opkind == OPminus) || (opkind == OPnot) || (opkind == OPplus) ) - ) - { - NextSym(); - switch (opkind) { - /* +1 is also a valid number! */ - case OPplus: e1 = new COperator1Expr(VALUE_POS_OPERATOR, Ex(NUM_PRIORITY)); break; - case OPminus: e1 = new COperator1Expr(VALUE_NEG_OPERATOR, Ex(NUM_PRIORITY)); break; - case OPnot: e1 = new COperator1Expr(VALUE_NOT_OPERATOR, Ex(NUM_PRIORITY)); break; - default: - { - // should not happen - e1 = Error("operator +, - or ! expected"); - } - } - } - else { - switch (sym) { - case constsym: - { - switch (constkind) { - case booltype: - e1 = new CConstExpr(new CBoolValue(boolvalue)); - break; - case inttype: - { - cInt temp; - temp = strtoll(const_as_string, NULL, 10); /* atoi is for int only */ - e1 = new CConstExpr(new CIntValue(temp)); - break; - } - case floattype: - { - double temp; - temp = atof(const_as_string); - e1 = new CConstExpr(new CFloatValue(temp)); - break; - } - case stringtype: - e1 = new CConstExpr(new CStringValue(const_as_string,"")); - break; - default : - MT_assert(false); - break; - } - NextSym(); - break; - } - case lbracksym: - NextSym(); - e1 = Ex(1); - Term(rbracksym); - break; - case ifsym: - { - CExpression *e3; - NextSym(); - Term(lbracksym); - e1 = Ex(1); - Term(commasym); - e2 = Ex(1); - if (sym == commasym) { - NextSym(); - e3 = Ex(1); - } else { - e3 = new CConstExpr(new CEmptyValue()); - } - Term(rbracksym); - e1 = new CIfExpr(e1, e2, e3); - break; - } - case idsym: - { - e1 = new CIdentifierExpr(const_as_string,m_identifierContext); - NextSym(); - - break; - } - case errorsym: - { - MT_assert(!e1); - STR_String errtext="[no info]"; - if (errmsg) - { - CValue* errmsgval = errmsg->Calculate(); - errtext=errmsgval->GetText(); - errmsgval->Release(); - - //e1 = Error(errmsg->Calculate()->GetText());//new CConstExpr(errmsg->Calculate()); - - if ( !(errmsg->Release()) ) - { - errmsg=NULL; - } else { - // does this happen ? - MT_assert("does this happen"); - } - } - e1 = Error(errtext); - - break; - } - default: - NextSym(); - //return Error("Expression expected"); - MT_assert(!e1); - e1 = Error("Expression expected"); - } - } - } - return e1; -} - -CExpression *CParser::Expr() -{ - // parses an expression in the imput, and - // returns an CExpression, containing the parsed input - return Ex(1); -} - -CExpression* CParser::ProcessText -(const char *intext) { - - // and parses the string in intext and returns it. - - - CExpression* expr; - text = intext; - - - chcount = 0; - if (text.Length() == 0) { - return NULL; - } - - ch = text[0]; - /* if (ch != '=') { - * expr = new CConstExpr(new CStringValue(text)); - * *dependent = deplist; - * return expr; - * } else - */ - // NextCh(); - NextSym(); - expr = Expr(); - if (sym != eolsym) { - CExpression* oldexpr = expr; - expr = new COperator2Expr(VALUE_ADD_OPERATOR, - oldexpr, Error(STR_String("Extra characters after expression")));//new CConstExpr(new CErrorValue("Extra characters after expression"))); - } - if (errmsg) - errmsg->Release(); - - return expr; -} - - - -float CParser::GetFloat(STR_String& txt) -{ - // returns parsed text into a float - // empty string returns -1 - -// AfxMessageBox("parsed string="+txt); - CValue* val=NULL; - float result=-1; -// String tmpstr; - - CExpression* expr = ProcessText(txt); - if (expr) { - val = expr->Calculate(); - result=(float)val->GetNumber(); - - - - val->Release(); - expr->Release(); - } -// tmpstr.Format("parseresult=%g",result); -// AfxMessageBox(tmpstr); - return result; -} - -CValue* CParser::GetValue(STR_String& txt, bool bFallbackToText) -{ - // returns parsed text into a value, - // empty string returns NULL value ! - // if bFallbackToText then unparsed stuff is put into text - - CValue* result=NULL; - CExpression* expr = ProcessText(txt); - if (expr) { - result = expr->Calculate(); - expr->Release(); - } - if (result) - { - // if the parsed stuff lead to an errorvalue, don't return errors, just NULL - if (result->IsError()) { - result->Release(); - result=NULL; - if (bFallbackToText) { - if (txt.Length()>0) - { - result = new CStringValue(txt,""); - } - } - } - } - return result; -} - -void CParser::SetContext(CValue* context) -{ - if (m_identifierContext) - { - m_identifierContext->Release(); - } - m_identifierContext = context; -} diff --git a/source/gameengine/Expressions/intern/IntValue.cpp b/source/gameengine/Expressions/intern/IntValue.cpp deleted file mode 100644 index 7b2e841f13f..00000000000 --- a/source/gameengine/Expressions/intern/IntValue.cpp +++ /dev/null @@ -1,344 +0,0 @@ -/** \file gameengine/Expressions/IntValue.cpp - * \ingroup expressions - */ -// IntValue.cpp: implementation of the CIntValue class. -/* - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -#include - -#include "EXP_IntValue.h" -#include "EXP_ErrorValue.h" -#include "EXP_FloatValue.h" -#include "EXP_BoolValue.h" -#include "EXP_StringValue.h" -#include "EXP_VoidValue.h" - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -CIntValue::CIntValue() -/* -pre: false -effect: constructs a new CIntValue -*/ -{ - -#ifdef DEBUG_ - m_textval = "Int illegal constructor"; -#endif - m_pstrRep=NULL; -} - - - -CIntValue::CIntValue(cInt innie) -/* -pre: -effect: constructs a new CIntValue containing cInt innie -*/ -{ - m_int = innie; - m_pstrRep=NULL; -} - - - -CIntValue::CIntValue(cInt innie,const char *name,AllocationTYPE alloctype) -{ - m_int = innie; - SetName(name); - - if (alloctype==CValue::STACKVALUE) - { - CValue::DisableRefCount(); - } - m_pstrRep=NULL; - -} - - - -CIntValue::~CIntValue() -/* -pre: -effect: deletes the object -*/ -{ - if (m_pstrRep) - delete m_pstrRep; -} - - - -CValue* CIntValue::Calc(VALUE_OPERATOR op, CValue *val) -/* -pre: -ret: a new object containing the result of applying operator op to this -object and val -*/ -{ - //return val->CalcInt(op, this); - switch (op) { - case VALUE_POS_OPERATOR: - return new CIntValue (m_int); - break; - case VALUE_NEG_OPERATOR: - return new CIntValue (-m_int); - break; - case VALUE_NOT_OPERATOR: - return new CBoolValue (m_int == 0); - break; - case VALUE_AND_OPERATOR: - case VALUE_OR_OPERATOR: - return new CErrorValue(val->GetText() + op2str(op) + "only allowed on booleans"); - break; - default: - return val->CalcFinal(VALUE_INT_TYPE, op, this); - break; - } -} - -/* - * pre: the type of val is dtype - * ret: a new object containing the result of applying operator op to val and - * this object - */ -CValue* CIntValue::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val) -{ - CValue *ret; - - switch (dtype) { - case VALUE_EMPTY_TYPE: - case VALUE_INT_TYPE: - { - switch (op) { - case VALUE_MOD_OPERATOR: - ret = new CIntValue (((CIntValue *) val)->GetInt() % m_int); - break; - case VALUE_ADD_OPERATOR: - ret = new CIntValue (((CIntValue *) val)->GetInt() + m_int); - break; - case VALUE_SUB_OPERATOR: - ret = new CIntValue (((CIntValue *) val)->GetInt() - m_int); - break; - case VALUE_MUL_OPERATOR: - ret = new CIntValue (((CIntValue *) val)->GetInt() * m_int); - break; - case VALUE_DIV_OPERATOR: - if (m_int == 0) { - if (val->GetNumber() == 0) { - ret = new CErrorValue("Not a Number"); - } - else { - ret = new CErrorValue("Division by zero"); - } - } - else - ret = new CIntValue (((CIntValue *) val)->GetInt() / m_int); - break; - case VALUE_EQL_OPERATOR: - ret = new CBoolValue(((CIntValue *) val)->GetInt() == m_int); - break; - case VALUE_NEQ_OPERATOR: - ret = new CBoolValue(((CIntValue *) val)->GetInt() != m_int); - break; - case VALUE_GRE_OPERATOR: - ret = new CBoolValue(((CIntValue *) val)->GetInt() > m_int); - break; - case VALUE_LES_OPERATOR: - ret = new CBoolValue(((CIntValue *) val)->GetInt() < m_int); - break; - case VALUE_GEQ_OPERATOR: - ret = new CBoolValue(((CIntValue *) val)->GetInt() >= m_int); - break; - case VALUE_LEQ_OPERATOR: - ret = new CBoolValue(((CIntValue *) val)->GetInt() <= m_int); - break; - case VALUE_NEG_OPERATOR: - ret = new CIntValue (-m_int); - break; - case VALUE_POS_OPERATOR: - ret = new CIntValue (m_int); - break; - case VALUE_NOT_OPERATOR: - ret = new CBoolValue(m_int == 0); - break; - default: - printf("Found op: %d\n", op); - ret = new CErrorValue("illegal operator. please send a bug report."); - break; - } - break; - } - case VALUE_FLOAT_TYPE: - { - switch (op) { - case VALUE_MOD_OPERATOR: - ret = new CFloatValue(fmod(((CFloatValue *) val)->GetFloat(), m_int)); - break; - case VALUE_ADD_OPERATOR: - ret = new CFloatValue (((CFloatValue *) val)->GetFloat() + m_int); - break; - case VALUE_SUB_OPERATOR: - ret = new CFloatValue (((CFloatValue *) val)->GetFloat() - m_int); - break; - case VALUE_MUL_OPERATOR: - ret = new CFloatValue (((CFloatValue *) val)->GetFloat() * m_int); - break; - case VALUE_DIV_OPERATOR: - if (m_int == 0) - ret = new CErrorValue("Division by zero"); - else - ret = new CFloatValue (((CFloatValue *) val)->GetFloat() / m_int); - break; - case VALUE_EQL_OPERATOR: - ret = new CBoolValue(((CFloatValue *) val)->GetFloat() == m_int); - break; - case VALUE_NEQ_OPERATOR: - ret = new CBoolValue(((CFloatValue *) val)->GetFloat() != m_int); - break; - case VALUE_GRE_OPERATOR: - ret = new CBoolValue(((CFloatValue *) val)->GetFloat() > m_int); - break; - case VALUE_LES_OPERATOR: - ret = new CBoolValue(((CFloatValue *) val)->GetFloat() < m_int); - break; - case VALUE_GEQ_OPERATOR: - ret = new CBoolValue(((CFloatValue *) val)->GetFloat() >= m_int); - break; - case VALUE_LEQ_OPERATOR: - ret = new CBoolValue(((CFloatValue *) val)->GetFloat() <= m_int); - break; - case VALUE_NOT_OPERATOR: - ret = new CBoolValue(m_int == 0); - break; - default: - ret = new CErrorValue("illegal operator. please send a bug report."); - break; - } - break; - } - case VALUE_STRING_TYPE: - { - switch (op) { - case VALUE_ADD_OPERATOR: - ret = new CStringValue(val->GetText() + GetText(),""); - break; - case VALUE_EQL_OPERATOR: - case VALUE_NEQ_OPERATOR: - case VALUE_GRE_OPERATOR: - case VALUE_LES_OPERATOR: - case VALUE_GEQ_OPERATOR: - case VALUE_LEQ_OPERATOR: - ret = new CErrorValue("[Cannot compare string with integer]" + op2str(op) + GetText()); - break; - default: - ret = new CErrorValue("[operator not allowed on strings]" + op2str(op) + GetText()); - break; - } - break; - } - case VALUE_BOOL_TYPE: - ret = new CErrorValue("[operator not valid on boolean and integer]" + op2str(op) + GetText()); - break; -#if 0 - case VALUE_EMPTY_TYPE: - { - switch (op) { - case VALUE_ADD_OPERATOR: - ret = new CIntValue (m_int); - break; - case VALUE_SUB_OPERATOR: - ret = new CIntValue (-m_int); - break; - default: - { - ret = new CErrorValue(op2str(op) + GetText()); - } - } - break; - } -#endif - case VALUE_ERROR_TYPE: - ret = new CErrorValue(val->GetText() + op2str(op) + GetText()); - break; - default: - ret = new CErrorValue("illegal type. contact your dealer (if any)"); - break; - } - return ret; -} - - -/** - * pre: - * ret: the cInt stored in the object - */ -cInt CIntValue::GetInt() -{ - return m_int; -} - - - -double CIntValue::GetNumber() -{ - return (double) m_int; -} - - - -int CIntValue::GetValueType() -{ - return VALUE_INT_TYPE; -} - - - -const STR_String & CIntValue::GetText() -{ - if (!m_pstrRep) - m_pstrRep=new STR_String(); - m_pstrRep->Format("%lld",m_int); - - return *m_pstrRep; -} - - - -CValue* CIntValue::GetReplica() -{ - CIntValue* replica = new CIntValue(*this); - replica->ProcessReplica(); - replica->m_pstrRep = NULL; - - return replica; -} - - - -void CIntValue::SetValue(CValue* newval) -{ - m_int = (cInt)newval->GetNumber(); - SetModified(true); -} - - -#ifdef WITH_PYTHON -PyObject *CIntValue::ConvertValueToPython() -{ - return PyLong_FromLongLong(m_int); -} -#endif // WITH_PYTHON diff --git a/source/gameengine/Expressions/intern/ListValue.cpp b/source/gameengine/Expressions/intern/ListValue.cpp deleted file mode 100644 index 557ce7be300..00000000000 --- a/source/gameengine/Expressions/intern/ListValue.cpp +++ /dev/null @@ -1,702 +0,0 @@ -/** \file gameengine/Expressions/ListValue.cpp - * \ingroup expressions - */ -// ListValue.cpp: implementation of the CListValue class. -// -////////////////////////////////////////////////////////////////////// -/* - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -#include - -#include "EXP_ListValue.h" -#include "EXP_StringValue.h" -#include "EXP_VoidValue.h" -#include -#include "EXP_BoolValue.h" - -#include "BLI_sys_types.h" /* for intptr_t support */ - - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -CListValue::CListValue() -: CPropValue() -{ - m_bReleaseContents=true; -} - - - -CListValue::~CListValue() -{ - - if (m_bReleaseContents) { - for (unsigned int i=0;iRelease(); - } - } -} - - -static STR_String gstrListRep=STR_String("List"); - -const STR_String & CListValue::GetText() -{ - gstrListRep = "["; - STR_String commastr = ""; - - for (int i=0;iGetText(); - commastr = ","; - } - gstrListRep += "]"; - - return gstrListRep; -} - - - -CValue* CListValue::GetReplica() -{ - CListValue* replica = new CListValue(*this); - - replica->ProcessReplica(); - - replica->m_bReleaseContents=true; // for copy, complete array is copied for now... - // copy all values - int numelements = m_pValueArray.size(); - unsigned int i=0; - replica->m_pValueArray.resize(numelements); - for (i=0;im_pValueArray[i] = m_pValueArray[i]->GetReplica(); - - - return replica; -}; - - - -void CListValue::SetValue(int i, CValue *val) -{ - assertd(i < m_pValueArray.size()); - m_pValueArray[i]=val; -} - - - -void CListValue::Resize(int num) -{ - m_pValueArray.resize(num); -} - - - -void CListValue::Remove(int i) -{ - assertd(iRelease(); - m_pValueArray.clear();//.Clear(); -} - - - -CValue* CListValue::FindValue(const STR_String &name) -{ - for (int i=0; i < GetCount(); i++) - if (GetValue(i)->GetName() == name) - return GetValue(i); - - return NULL; -} - -CValue* CListValue::FindValue(const char *name) -{ - for (int i=0; i < GetCount(); i++) - if (GetValue(i)->GetName() == name) - return GetValue(i); - - return NULL; -} - -bool CListValue::SearchValue(CValue *val) -{ - for (int i=0;i=0;i--) - if (val == GetValue(i)) - { - Remove(i); - result=true; - } - return result; -} - - - -void CListValue::MergeList(CListValue *otherlist) -{ - - int numelements = this->GetCount(); - int numotherelements = otherlist->GetCount(); - - - Resize(numelements+numotherelements); - - for (int i=0;iGetValue(i)->AddRef()); - } -} - -bool CListValue::CheckEqual(CValue* first,CValue* second) -{ - bool result = false; - - CValue* eqval = ((CValue*)first)->Calc(VALUE_EQL_OPERATOR,(CValue*)second); - - if (eqval==NULL) - return false; - const STR_String& text = eqval->GetText(); - if (&text==&CBoolValue::sTrueString) - { - result = true; - } - eqval->Release(); - return result; - -} - - -/* --------------------------------------------------------------------- - * Some stuff taken from the header - * --------------------------------------------------------------------- */ -CValue* CListValue::Calc(VALUE_OPERATOR op,CValue *val) -{ - //assert(false); // todo: implement me! - static int error_printed = 0; - if (error_printed==0) { - fprintf(stderr, "CValueList::Calc not yet implemented\n"); - error_printed = 1; - } - return NULL; -} - -CValue* CListValue::CalcFinal(VALUE_DATA_TYPE dtype, - VALUE_OPERATOR op, - CValue* val) -{ - //assert(false); // todo: implement me! - static int error_printed = 0; - if (error_printed==0) { - fprintf(stderr, "CValueList::CalcFinal not yet implemented\n"); - error_printed = 1; - } - return NULL; -} - - - -void CListValue::Add(CValue* value) -{ - m_pValueArray.push_back(value); -} - - - -double CListValue::GetNumber() -{ - return -1; -} - - - -int CListValue::GetValueType() -{ - return VALUE_LIST_TYPE; -} - - - -void CListValue::SetModified(bool bModified) -{ - CValue::SetModified(bModified); - int numels = GetCount(); - - for (int i=0;iSetModified(bModified); -} - - - -bool CListValue::IsModified() -{ - bool bmod = CValue::IsModified(); //normal own flag - int numels = GetCount(); - - for (int i=0;iIsModified(); - - return bmod; -} - -#ifdef WITH_PYTHON - -/* --------------------------------------------------------------------- */ -/* Python interface ---------------------------------------------------- */ -/* --------------------------------------------------------------------- */ - -static Py_ssize_t listvalue_bufferlen(PyObject *self) -{ - CListValue *list= static_cast(BGE_PROXY_REF(self)); - if (list==NULL) - return 0; - - return (Py_ssize_t)list->GetCount(); -} - -static PyObject *listvalue_buffer_item(PyObject *self, Py_ssize_t index) -{ - CListValue *list= static_cast(BGE_PROXY_REF(self)); - CValue *cval; - - if (list==NULL) { - PyErr_SetString(PyExc_SystemError, "val = CList[i], " BGE_PROXY_ERROR_MSG); - return NULL; - } - - int count = list->GetCount(); - - if (index < 0) - index = count+index; - - if (index < 0 || index >= count) { - PyErr_SetString(PyExc_IndexError, "CList[i]: Python ListIndex out of range in CValueList"); - return NULL; - } - - cval= list->GetValue(index); - - PyObject *pyobj = cval->ConvertValueToPython(); - if (pyobj) - return pyobj; - else - return cval->GetProxy(); -} - - -/* just slice it into a python list... */ -static PyObject *listvalue_buffer_slice(CListValue *list, Py_ssize_t start, Py_ssize_t stop) -{ - PyObject *newlist; - Py_ssize_t i, j; - - /* caller needs to validate negative index */ -#if 0 - Py_ssize_t len = list->GetCount(); - - if (start > len) start = len; - if (stop > len) stop = len; -#endif - - newlist = PyList_New(stop - start); - if (!newlist) - return NULL; - - for (i = start, j = 0; i < stop; i++, j++) { - PyObject *pyobj = list->GetValue(i)->ConvertValueToPython(); - if (!pyobj) { - pyobj = list->GetValue(i)->GetProxy(); - } - PyList_SET_ITEM(newlist, j, pyobj); - } - return newlist; -} - - -static PyObject *listvalue_mapping_subscript(PyObject *self, PyObject *key) -{ - CListValue *list= static_cast(BGE_PROXY_REF(self)); - if (list==NULL) { - PyErr_SetString(PyExc_SystemError, "value = CList[i], " BGE_PROXY_ERROR_MSG); - return NULL; - } - - if (PyUnicode_Check(key)) { - CValue *item = ((CListValue*) list)->FindValue(_PyUnicode_AsString(key)); - if (item) { - PyObject *pyobj = item->ConvertValueToPython(); - if (pyobj) - return pyobj; - else - return item->GetProxy(); - } - } - else if (PyIndex_Check(key)) { - Py_ssize_t index = PyLong_AsSsize_t(key); - return listvalue_buffer_item(self, index); /* wont add a ref */ - } - else if (PySlice_Check(key)) { - Py_ssize_t start, stop, step, slicelength; - - if (PySlice_GetIndicesEx(key, list->GetCount(), &start, &stop, &step, &slicelength) < 0) - return NULL; - - if (slicelength <= 0) { - return PyList_New(0); - } - else if (step == 1) { - return listvalue_buffer_slice(list, start, stop); - } - else { - PyErr_SetString(PyExc_TypeError, "CList[slice]: slice steps not supported"); - return NULL; - } - } - - PyErr_Format(PyExc_KeyError, - "CList[key]: '%R' key not in list", key); - return NULL; -} - -/* clist + list, return a list that python owns */ -static PyObject *listvalue_buffer_concat(PyObject *self, PyObject *other) -{ - CListValue *listval= static_cast(BGE_PROXY_REF(self)); - Py_ssize_t i, numitems, numitems_orig; - - if (listval==NULL) { - PyErr_SetString(PyExc_SystemError, "CList+other, " BGE_PROXY_ERROR_MSG); - return NULL; - } - - numitems_orig= listval->GetCount(); - - // for now, we support CListValue concatenated with items - // and CListValue concatenated to Python Lists - // and CListValue concatenated with another CListValue - - /* Shallow copy, don't use listval->GetReplica(), it will screw up with KX_GameObjects */ - CListValue* listval_new = new CListValue(); - - if (PyList_Check(other)) - { - CValue* listitemval; - bool error = false; - - numitems = PyList_GET_SIZE(other); - - /* copy the first part of the list */ - listval_new->Resize(numitems_orig + numitems); - for (i=0;iSetValue(i, listval->GetValue(i)->AddRef()); - - for (i=0;iConvertPythonToValue(PyList_GET_ITEM(other, i), true, "cList + pyList: CListValue, "); - - if (listitemval) { - listval_new->SetValue(i+numitems_orig, listitemval); - } else { - error= true; - break; - } - } - - if (error) { - listval_new->Resize(numitems_orig+i); /* resize so we don't try release NULL pointers */ - listval_new->Release(); - return NULL; /* ConvertPythonToValue above sets the error */ - } - - } - else if (PyObject_TypeCheck(other, &CListValue::Type)) { - // add items from otherlist to this list - CListValue* otherval = static_cast(BGE_PROXY_REF(other)); - if (otherval==NULL) { - listval_new->Release(); - PyErr_SetString(PyExc_SystemError, "CList+other, " BGE_PROXY_ERROR_MSG); - return NULL; - } - - numitems = otherval->GetCount(); - - /* copy the first part of the list */ - listval_new->Resize(numitems_orig + numitems); /* resize so we don't try release NULL pointers */ - for (i=0;iSetValue(i, listval->GetValue(i)->AddRef()); - - /* now copy the other part of the list */ - for (i=0;iSetValue(i+numitems_orig, otherval->GetValue(i)->AddRef()); - - } - return listval_new->NewProxy(true); /* python owns this list */ -} - -static int listvalue_buffer_contains(PyObject *self_v, PyObject *value) -{ - CListValue *self = static_cast(BGE_PROXY_REF(self_v)); - - if (self == NULL) { - PyErr_SetString(PyExc_SystemError, "val in CList, " BGE_PROXY_ERROR_MSG); - return -1; - } - - if (PyUnicode_Check(value)) { - if (self->FindValue((const char *)_PyUnicode_AsString(value))) { - return 1; - } - } - else if (PyObject_TypeCheck(value, &CValue::Type)) { /* not dict like at all but this worked before __contains__ was used */ - CValue *item= static_cast(BGE_PROXY_REF(value)); - for (int i=0; i < self->GetCount(); i++) - if (self->GetValue(i) == item) // Com - return 1; - - } // not using CheckEqual - - return 0; -} - - -static PySequenceMethods listvalue_as_sequence = { - listvalue_bufferlen,//(inquiry)buffer_length, /*sq_length*/ - listvalue_buffer_concat, /*sq_concat*/ - NULL, /*sq_repeat*/ - listvalue_buffer_item, /*sq_item*/ -// TODO, slicing in py3 - NULL, // listvalue_buffer_slice, /*sq_slice*/ - NULL, /*sq_ass_item*/ - NULL, /*sq_ass_slice*/ - (objobjproc)listvalue_buffer_contains, /* sq_contains */ - (binaryfunc) NULL, /* sq_inplace_concat */ - (ssizeargfunc) NULL, /* sq_inplace_repeat */ -}; - - - -/* Is this one used ? */ -static PyMappingMethods instance_as_mapping = { - listvalue_bufferlen, /*mp_length*/ - listvalue_mapping_subscript, /*mp_subscript*/ - NULL /*mp_ass_subscript*/ -}; - - - -PyTypeObject CListValue::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "CListValue", /*tp_name*/ - sizeof(PyObjectPlus_Proxy), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - py_base_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - py_base_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - &listvalue_as_sequence, /*tp_as_sequence*/ - &instance_as_mapping, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call */ - 0, - NULL, - NULL, - 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 CListValue::Methods[] = { - /* List style access */ - {"append", (PyCFunction)CListValue::sPyappend,METH_O}, - {"reverse", (PyCFunction)CListValue::sPyreverse,METH_NOARGS}, - {"index", (PyCFunction)CListValue::sPyindex,METH_O}, - {"count", (PyCFunction)CListValue::sPycount,METH_O}, - - /* Dict style access */ - {"get", (PyCFunction)CListValue::sPyget,METH_VARARGS}, - - /* Own cvalue funcs */ - {"from_id", (PyCFunction)CListValue::sPyfrom_id,METH_O}, - - {NULL,NULL} //Sentinel -}; - -PyAttributeDef CListValue::Attributes[] = { - { NULL } //Sentinel -}; - -PyObject *CListValue::Pyappend(PyObject *value) -{ - CValue *objval = ConvertPythonToValue(value, true, "CList.append(i): CValueList, "); - - if (!objval) /* ConvertPythonToValue sets the error */ - return NULL; - - if (!BGE_PROXY_PYOWNS(m_proxy)) { - PyErr_SetString(PyExc_TypeError, - "CList.append(i): internal values can't be modified"); - return NULL; - } - - Add(objval); - - Py_RETURN_NONE; -} - -PyObject *CListValue::Pyreverse() -{ - if (!BGE_PROXY_PYOWNS(m_proxy)) { - PyErr_SetString(PyExc_TypeError, - "CList.reverse(): internal values can't be modified"); - return NULL; - } - - std::reverse(m_pValueArray.begin(),m_pValueArray.end()); - Py_RETURN_NONE; -} - -PyObject *CListValue::Pyindex(PyObject *value) -{ - PyObject *result = NULL; - - CValue *checkobj = ConvertPythonToValue(value, true, "val = cList[i]: CValueList, "); - if (checkobj==NULL) - return NULL; /* ConvertPythonToValue sets the error */ - - int numelem = GetCount(); - for (int i=0;iRelease(); - - if (result==NULL) { - PyErr_SetString(PyExc_ValueError, "CList.index(x): x not in CListValue"); - } - return result; - -} - - - -PyObject *CListValue::Pycount(PyObject *value) -{ - int numfound = 0; - - CValue *checkobj = ConvertPythonToValue(value, false, ""); /* error ignored */ - - if (checkobj==NULL) { /* in this case just return that there are no items in the list */ - PyErr_Clear(); - return PyLong_FromLong(0); - } - - int numelem = GetCount(); - for (int i=0;iRelease(); - - return PyLong_FromLong(numfound); -} - -/* Matches python dict.get(key, [default]) */ -PyObject *CListValue::Pyget(PyObject *args) -{ - char *key; - PyObject *def = Py_None; - - if (!PyArg_ParseTuple(args, "s|O:get", &key, &def)) - return NULL; - - CValue *item = FindValue((const char *)key); - if (item) { - PyObject *pyobj = item->ConvertValueToPython(); - if (pyobj) - return pyobj; - else - return item->GetProxy(); - } - Py_INCREF(def); - return def; -} - - -PyObject *CListValue::Pyfrom_id(PyObject *value) -{ - uintptr_t id= (uintptr_t)PyLong_AsVoidPtr(value); - - if (PyErr_Occurred()) - return NULL; - - int numelem = GetCount(); - for (int i=0;i(m_pValueArray[i]->m_proxy) == id) - return GetValue(i)->GetProxy(); - } - PyErr_SetString(PyExc_IndexError, "from_id(#): id not found in CValueList"); - return NULL; - -} - -#endif // WITH_PYTHON diff --git a/source/gameengine/Expressions/intern/ListWrapper.cpp b/source/gameengine/Expressions/intern/ListWrapper.cpp deleted file mode 100644 index db1518a4388..00000000000 --- a/source/gameengine/Expressions/intern/ListWrapper.cpp +++ /dev/null @@ -1,424 +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): Porteries Tristan. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file ListWrapper.cpp - * \ingroup expressions - */ - -#ifdef WITH_PYTHON - -#include "EXP_ListWrapper.h" - -static STR_String pythonGeneratorList = "ListWrapper"; - -CListWrapper::CListWrapper(void *client, - PyObject *base, - bool (*checkValid)(void *), - int (*getSize)(void *), - PyObject *(*getItem)(void *, int), - const char *(*getItemName)(void *, int), - bool (*setItem)(void *, int, PyObject *)) -:m_client(client), -m_base(base), -m_checkValid(checkValid), -m_getSize(getSize), -m_getItem(getItem), -m_getItemName(getItemName), -m_setItem(setItem) -{ - // Incref to always have a existing pointer. - Py_INCREF(m_base); -} - -CListWrapper::~CListWrapper() -{ - Py_DECREF(m_base); -} - -bool CListWrapper::CheckValid() -{ - if (m_base && !BGE_PROXY_REF(m_base)) { - return false; - } - return m_checkValid ? (*m_checkValid)(m_client) : true; -} - -int CListWrapper::GetSize() -{ - return (*m_getSize)(m_client); -} - -PyObject *CListWrapper::GetItem(int index) -{ - return (*m_getItem)(m_client, index); -} - -const char *CListWrapper::GetItemName(int index) -{ - return (*m_getItemName)(m_client, index); -} - -bool CListWrapper::SetItem(int index, PyObject *item) -{ - return (*m_setItem)(m_client, index, item); -} - -bool CListWrapper::AllowSetItem() -{ - return m_setItem != NULL; -} - -bool CListWrapper::AllowGetItemByName() -{ - return m_getItemName != NULL; -} - -// ================================================================ - -const STR_String &CListWrapper::GetText() -{ - return pythonGeneratorList; -} - -void CListWrapper::SetName(const char *name) -{ -} - -STR_String &CListWrapper::GetName() -{ - return pythonGeneratorList; -} - -CValue *CListWrapper::GetReplica() -{ - return NULL; -} - -CValue *CListWrapper::Calc(VALUE_OPERATOR op, CValue *val) -{ - return NULL; -} - -CValue *CListWrapper::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val) -{ - return NULL; -} - -double CListWrapper::GetNumber() -{ - return -1; -} - -int CListWrapper::GetValueType() -{ - return -1; -} - -// We convert all elements to python objects to make a proper repr string. -PyObject *CListWrapper::py_repr() -{ - if (!CheckValid()) { - PyErr_SetString(PyExc_SystemError, "CListWrapper : repr, " BGE_PROXY_ERROR_MSG); - return NULL; - } - - PyObject *py_proxy = GetProxy(); - PyObject *py_list = PySequence_List(py_proxy); - PyObject *py_string = PyObject_Repr(py_list); - Py_DECREF(py_list); - Py_DECREF(py_proxy); - return py_string; -} - - -Py_ssize_t CListWrapper::py_len(PyObject *self) -{ - CListWrapper *list = (CListWrapper *)BGE_PROXY_REF(self); - // Invalid list. - if (!list->CheckValid()) { - PyErr_SetString(PyExc_SystemError, "len(CListWrapper), " BGE_PROXY_ERROR_MSG); - return 0; - } - - return (Py_ssize_t)list->GetSize(); -} - -PyObject *CListWrapper::py_get_item(PyObject *self, Py_ssize_t index) -{ - CListWrapper *list = (CListWrapper *)BGE_PROXY_REF(self); - // Invalid list. - if (!list->CheckValid()) { - PyErr_SetString(PyExc_SystemError, "val = CListWrapper[i], " BGE_PROXY_ERROR_MSG); - return NULL; - } - - int size = list->GetSize(); - - if (index < 0) { - index = size + index; - } - if (index < 0 || index >= size) { - PyErr_SetString(PyExc_IndexError, "CListWrapper[i]: List index out of range in CListWrapper"); - return NULL; - } - - PyObject *pyobj = list->GetItem(index); - - return pyobj; -} - -int CListWrapper::py_set_item(PyObject *self, Py_ssize_t index, PyObject *value) -{ - CListWrapper *list = (CListWrapper *)BGE_PROXY_REF(self); - // Invalid list. - if (!list->CheckValid()) { - PyErr_SetString(PyExc_SystemError, "CListWrapper[i] = val, " BGE_PROXY_ERROR_MSG); - return -1; - } - - if (!list->AllowSetItem()) { - PyErr_SetString(PyExc_TypeError, "CListWrapper's item type doesn't support assignment"); - return -1; - } - - if (!value) { - PyErr_SetString(PyExc_TypeError, "CListWrapper doesn't support item deletion"); - return -1; - } - - int size = list->GetSize(); - - if (index < 0) { - index = size + index; - } - if (index < 0 || index >= size) { - PyErr_SetString(PyExc_IndexError, "CListWrapper[i]: List index out of range in CListWrapper"); - return -1; - } - - if (!list->SetItem(index, value)) { - return -1; - } - return 0; -} - -PyObject *CListWrapper::py_mapping_subscript(PyObject *self, PyObject *key) -{ - CListWrapper *list = (CListWrapper *)BGE_PROXY_REF(self); - // Invalid list. - if (!list->CheckValid()) { - PyErr_SetString(PyExc_SystemError, "val = CListWrapper[key], " BGE_PROXY_ERROR_MSG); - return NULL; - } - - if (PyIndex_Check(key)) { - Py_ssize_t index = PyLong_AsSsize_t(key); - return py_get_item(self, index); - } - else if (PyUnicode_Check(key)) { - if (!list->AllowGetItemByName()) { - PyErr_SetString(PyExc_SystemError, "CListWrapper's item type doesn't support access by key"); - return NULL; - } - - const char *name = _PyUnicode_AsString(key); - int size = list->GetSize(); - - for (unsigned int i = 0; i < size; ++i) { - if (strcmp(list->GetItemName(i), name) == 0) { - return list->GetItem(i); - } - } - - PyErr_Format(PyExc_KeyError, "requested item \"%s\" does not exist", name); - return NULL; - } - - PyErr_Format(PyExc_KeyError, "CListWrapper[key]: '%R' key not in list", key); - return NULL; -} - -int CListWrapper::py_mapping_ass_subscript(PyObject *self, PyObject *key, PyObject *value) -{ - CListWrapper *list = (CListWrapper *)BGE_PROXY_REF(self); - // Invalid list. - if (!list->CheckValid()) { - PyErr_SetString(PyExc_SystemError, "val = CListWrapper[key], " BGE_PROXY_ERROR_MSG); - return -1; - } - - if (!list->AllowSetItem()) { - PyErr_SetString(PyExc_TypeError, "CListWrapper's item type doesn't support assignment"); - return -1; - } - - if (PyIndex_Check(key)) { - Py_ssize_t index = PyLong_AsSsize_t(key); - return py_set_item(self, index, value); - } - else if (PyUnicode_Check(key)) { - if (!list->AllowGetItemByName()) { - PyErr_SetString(PyExc_SystemError, "CListWrapper's item type doesn't support access by key"); - return -1; - } - - const char *name = _PyUnicode_AsString(key); - int size = list->GetSize(); - - for (unsigned int i = 0; i < size; ++i) { - if (strcmp(list->GetItemName(i), name) == 0) { - if (!list->SetItem(i, value)) { - return -1; - } - return 0; - } - } - - PyErr_Format(PyExc_KeyError, "requested item \"%s\" does not exist", name); - return -1; - } - - PyErr_Format(PyExc_KeyError, "CListWrapper[key]: '%R' key not in list", key); - return -1; -} - -int CListWrapper::py_contains(PyObject *self, PyObject *key) -{ - CListWrapper *list = (CListWrapper *)BGE_PROXY_REF(self); - // Invalid list. - if (!list->CheckValid()) { - PyErr_SetString(PyExc_SystemError, "val = CListWrapper[i], " BGE_PROXY_ERROR_MSG); - return -1; - } - - if (!list->AllowGetItemByName()) { - PyErr_SetString(PyExc_SystemError, "CListWrapper's item type doesn't support access by key"); - return -1; - } - - if (!PyUnicode_Check(key)) { - PyErr_SetString(PyExc_SystemError, "key in list, CListWrapper: key must be a string"); - return -1; - } - - const char *name = _PyUnicode_AsString(key); - int size = list->GetSize(); - - for (unsigned int i = 0; i < size; ++i) { - if (strcmp(list->GetItemName(i), name) == 0) { - return 1; - } - } - - return 0; -} - -PySequenceMethods CListWrapper::py_as_sequence = { - py_len, // sq_length - NULL, // sq_concat - NULL, // sq_repeat - py_get_item, // sq_item - NULL, // sq_slice - py_set_item, // sq_ass_item - NULL, // sq_ass_slice - (objobjproc)py_contains, // sq_contains - (binaryfunc) NULL, // sq_inplace_concat - (ssizeargfunc) NULL, // sq_inplace_repeat -}; - -PyMappingMethods CListWrapper::py_as_mapping = { - py_len, // mp_length - py_mapping_subscript, // mp_subscript - py_mapping_ass_subscript // mp_ass_subscript -}; - -PyTypeObject CListWrapper::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "CListWrapper", // tp_name - sizeof(PyObjectPlus_Proxy), // tp_basicsize - 0, // tp_itemsize - py_base_dealloc, // tp_dealloc - 0, // tp_print - 0, // tp_getattr - 0, // tp_setattr - 0, // tp_compare - py_base_repr, // tp_repr - 0, // tp_as_number - &py_as_sequence, // tp_as_sequence - &py_as_mapping, // tp_as_mapping - 0, // tp_hash - 0, // tp_call - 0, - NULL, - NULL, - 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 CListWrapper::Methods[] = { - {"get", (PyCFunction)CListWrapper::sPyGet, METH_VARARGS}, - {NULL, NULL} //Sentinel -}; - -PyAttributeDef CListWrapper::Attributes[] = { - {NULL} //Sentinel -}; - -/* Matches python dict.get(key, [default]) */ -PyObject *CListWrapper::PyGet(PyObject *args) -{ - char *name; - PyObject *def = Py_None; - - // Invalid list. - if (!CheckValid()) { - PyErr_SetString(PyExc_SystemError, "val = CListWrapper[i], " BGE_PROXY_ERROR_MSG); - return NULL; - } - - if (!AllowGetItemByName()) { - PyErr_SetString(PyExc_SystemError, "CListWrapper's item type doesn't support access by key"); - return NULL; - } - - if (!PyArg_ParseTuple(args, "s|O:get", &name, &def)) { - return NULL; - } - - for (unsigned int i = 0; i < GetSize(); ++i) { - if (strcmp(GetItemName(i), name) == 0) { - return GetItem(i); - } - } - - Py_INCREF(def); - return def; -} - -#endif // WITH_PYTHON diff --git a/source/gameengine/Expressions/intern/Operator1Expr.cpp b/source/gameengine/Expressions/intern/Operator1Expr.cpp deleted file mode 100644 index add0376f487..00000000000 --- a/source/gameengine/Expressions/intern/Operator1Expr.cpp +++ /dev/null @@ -1,151 +0,0 @@ -/** \file gameengine/Expressions/Operator1Expr.cpp - * \ingroup expressions - */ -// Operator1Expr.cpp: implementation of the COperator1Expr class. -/* - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -#include "EXP_Operator1Expr.h" -#include "EXP_EmptyValue.h" - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -COperator1Expr::COperator1Expr() -/* -pre: -effect: constucts an empty COperator1Expr -*/ -{ - m_lhs = NULL; -} - -COperator1Expr::COperator1Expr(VALUE_OPERATOR op, CExpression *lhs) -/* -pre: -effect: constucts a COperator1Expr with op and lhs in it -*/ -{ - m_lhs = lhs; - m_op = op; -} - -COperator1Expr::~COperator1Expr() -/* -pre: -effect: deletes the object -*/ -{ - if (m_lhs) m_lhs->Release(); -} - -CValue * COperator1Expr::Calculate() -/* -pre: -ret: a new object containing the result of applying the operator m_op to the - value of m_lhs -*/ -{ - CValue *ret; - CValue *temp = m_lhs->Calculate(); - CValue* empty = new CEmptyValue(); - ret = empty->Calc(m_op, temp); - empty->Release(); - temp->Release(); - - return ret; -} - -/* -bool COperator1Expr::IsInside(float x, float y, float z,bool bBorderInclude) -{ - - bool result = true; - switch (m_op) - { - - case VALUE_ADD_OPERATOR: - { - - if (m_lhs) - { - result = result || m_lhs->IsInside(x,y,z,bBorderInclude); - } - break; - } - case VALUE_SUB_OPERATOR: - { - result = true; - if (m_lhs) - { - result = result && (!m_lhs->IsInside(x,y,z,bBorderInclude)); - } - break; - } - } - return result; -} - -*/ -bool COperator1Expr::NeedsRecalculated() -{ - return m_lhs->NeedsRecalculated(); -} - -CExpression* COperator1Expr::CheckLink(std::vector& brokenlinks) -{ - - CExpression* newlhs = m_lhs->CheckLink(brokenlinks); - - if (newlhs) - { - if (newlhs==m_lhs) { - // not changed - } else { - // changed - //numchanges++; - newlhs->AddRef(); - - //m_lhs->Release(); - brokenlinks.push_back(new CBrokenLinkInfo(&m_lhs,m_lhs)); - - m_lhs = newlhs; - } - return this; - } else { - //numchanges++; - AddRef(); - - return Release(); - } - -} - -void COperator1Expr::BroadcastOperators(VALUE_OPERATOR op) -{ - if (m_lhs) - m_lhs->BroadcastOperators(m_op); -} - - - - -bool COperator1Expr::MergeExpression(CExpression *otherexpr) -{ - if (m_lhs) - return m_lhs->MergeExpression(otherexpr); - - assertd(false); // should not get here, expression is not compatible for merge - return false; -} diff --git a/source/gameengine/Expressions/intern/Operator2Expr.cpp b/source/gameengine/Expressions/intern/Operator2Expr.cpp deleted file mode 100644 index 0a7f30b8cc8..00000000000 --- a/source/gameengine/Expressions/intern/Operator2Expr.cpp +++ /dev/null @@ -1,276 +0,0 @@ -/** \file gameengine/Expressions/Operator2Expr.cpp - * \ingroup expressions - */ -// Operator2Expr.cpp: implementation of the COperator2Expr class. -/* - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ -// 31 dec 1998 - big update: try to use the cached data for updating, instead of -// rebuilding completely it from left and right node. Modified flags and bounding boxes -// have to do the trick -// when expression is cached, there will be a call to UpdateCalc() instead of Calc() - -#include "EXP_Operator2Expr.h" -#include "EXP_StringValue.h" -#include "EXP_VoidValue.h" - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -COperator2Expr::COperator2Expr(VALUE_OPERATOR op, CExpression *lhs, CExpression *rhs) -: -m_rhs(rhs), -m_lhs(lhs), -m_cached_calculate(NULL), -m_op(op) -/* -pre: -effect: constucts a COperator2Expr with op, lhs and rhs in it -*/ -{ - -} - -COperator2Expr::COperator2Expr(): -m_rhs(NULL), -m_lhs(NULL), -m_cached_calculate(NULL) - -/* -pre: -effect: constucts an empty COperator2Expr -*/ -{ - -} - -COperator2Expr::~COperator2Expr() -/* -pre: -effect: deletes the object -*/ -{ - if (m_lhs) - m_lhs->Release(); - if (m_rhs) - m_rhs->Release(); - if (m_cached_calculate) - m_cached_calculate->Release(); - -} -CValue* COperator2Expr::Calculate() -/* -pre: -ret: a new object containing the result of applying operator m_op to m_lhs -and m_rhs -*/ -{ - - bool leftmodified,rightmodified; - leftmodified = m_lhs->NeedsRecalculated(); - rightmodified = m_rhs->NeedsRecalculated(); - - // if no modifications on both left and right subtree, and result is already calculated - // then just return cached result... - if (!leftmodified && !rightmodified && (m_cached_calculate)) - { - // not modified, just return m_cached_calculate - } else { - // if not yet calculated, or modified... - - - if (m_cached_calculate) { - m_cached_calculate->Release(); - m_cached_calculate=NULL; - } - - CValue* ffleft = m_lhs->Calculate(); - CValue* ffright = m_rhs->Calculate(); - - ffleft->SetOwnerExpression(this);//->m_pOwnerExpression=this; - ffright->SetOwnerExpression(this);//->m_pOwnerExpression=this; - - m_cached_calculate = ffleft->Calc(m_op,ffright); - - //if (m_cached_calculate) - // m_cached_calculate->Action(CValue::SETOWNEREXPR,&CVoidValue(this,false,CValue::STACKVALUE)); - - ffleft->Release(); - ffright->Release(); - } - - return m_cached_calculate->AddRef(); - -} - -#if 0 -bool COperator2Expr::IsInside(float x, float y, float z,bool bBorderInclude) -{ - bool inside; - inside = false; - - switch (m_op) { - case VALUE_ADD_OPERATOR: - { - // inside = first || second; // optimized with early out if first is inside - // todo: calculate smallest leaf first ! is much faster... - - bool second;//first ;//,second; - - //first = m_lhs->IsInside(x,y,z); - second = m_rhs->IsInside(x,y,z,bBorderInclude); - if (second) - return true; //early out - - // second = m_rhs->IsInside(x,y,z); - - return m_lhs->IsInside(x,y,z,bBorderInclude); - - break; - } - - case VALUE_SUB_OPERATOR: - { - //inside = first && !second; // optimized with early out - // todo: same as with add_operator: calc smallest leaf first - - bool second;//first ;//,second; - //first = m_lhs->IsInside(x,y,z); - second = m_rhs->IsInside(x,y,z,bBorderInclude); - if (second) - return false; - - // second space get subtracted -> negate! - //second = m_rhs->IsInside(x,y,z); - - return (m_lhs->IsInside(x,y,z,bBorderInclude)); - - - break; - } - default: - { - assert(false); - // not yet implemented, only add or sub csg operations - } - } - - return inside; -} - -bool COperator2Expr::IsRightInside(float x, float y, float z,bool bBorderInclude) -{ - return m_rhs->IsInside(x,y,z,bBorderInclude); -} - -bool COperator2Expr::IsLeftInside(float x, float y, float z,bool bBorderInclude) -{ - return m_lhs->IsInside(x,y,z,bBorderInclude); -} -#endif - -bool COperator2Expr::NeedsRecalculated() -{ - // added some lines, just for debugging purposes, it could be a one-liner :) - //bool modleft - //bool modright; - assertd(m_lhs); - assertd(m_rhs); - - //modright = m_rhs->NeedsRecalculated(); - if (m_rhs->NeedsRecalculated()) // early out - return true; - return m_lhs->NeedsRecalculated(); - //modleft = m_lhs->NeedsRecalculated(); - //return (modleft || modright); - -} - - - -CExpression* COperator2Expr::CheckLink(std::vector& brokenlinks) -{ -// if both children are 'dead', return NULL -// if only one child is alive, return that child -// if both childresn are alive, return this - - -// bool leftalive = true,rightalive=true; - /* Does this mean the function will always bomb? */ - assertd(false); - assert(m_lhs); - assert(m_rhs); -/* - if (m_cached_calculate) - m_cached_calculate->Action(CValue::REFRESH_CACHE); - - CExpression* newlhs = m_lhs->CheckLink(brokenlinks); - CExpression* newrhs = m_rhs->CheckLink(brokenlinks); - - if (m_lhs != newlhs) - { - brokenlinks.push_back(new CBrokenLinkInfo(&m_lhs,m_lhs)); - } - - if (m_rhs != newrhs) - { - brokenlinks.push_back(new CBrokenLinkInfo(&m_rhs,m_rhs)); - } - - - - m_lhs = newlhs; - m_rhs = newrhs; - - if (m_lhs && m_rhs) { - return this; - } - - AddRef(); - if (m_lhs) - return Release(m_lhs->AddRef()); - - if (m_rhs) - return Release(m_rhs->AddRef()); -/ - - */ - return Release(); -} - - -bool COperator2Expr::MergeExpression(CExpression *otherexpr) -{ - if (m_lhs) - { - if (m_lhs->GetExpressionID() == CExpression::CCONSTEXPRESSIONID) - { - // cross fingers ;) replace constexpr by new tree... - m_lhs->Release(); - m_lhs = otherexpr->AddRef(); - return true; - } - } - - assertd(false); - return false; -} - - -void COperator2Expr::BroadcastOperators(VALUE_OPERATOR op) -{ - if (m_lhs) - m_lhs->BroadcastOperators(m_op); - if (m_rhs) - m_rhs->BroadcastOperators(m_op); -} diff --git a/source/gameengine/Expressions/intern/PyObjectPlus.cpp b/source/gameengine/Expressions/intern/PyObjectPlus.cpp deleted file mode 100644 index 1e4a59aeb5c..00000000000 --- a/source/gameengine/Expressions/intern/PyObjectPlus.cpp +++ /dev/null @@ -1,1226 +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/Expressions/PyObjectPlus.cpp - * \ingroup expressions - */ - - -/*------------------------------ - * PyObjectPlus cpp - * - * C++ library routines for Crawl 3.2 - * - * Derived from work by - * David Redish - * graduate student - * Computer Science Department - * Carnegie Mellon University (CMU) - * Center for the Neural Basis of Cognition (CNBC) - * http://www.python.org/doc/PyCPP.html - * - * ----------------------------- */ -#include -#include - -#include "EXP_PyObjectPlus.h" -#include "STR_String.h" -#include "MT_Vector3.h" -#include "MEM_guardedalloc.h" - -PyObjectPlus::~PyObjectPlus() -{ -#ifdef WITH_PYTHON - if (m_proxy) { - BGE_PROXY_REF(m_proxy)= NULL; - Py_DECREF(m_proxy); /* Remove own reference, python may still have 1 */ - } -// assert(ob_refcnt==0); -#endif -} - -PyObjectPlus::PyObjectPlus() : SG_QList() // constructor -{ -#ifdef WITH_PYTHON - m_proxy= NULL; -#endif -}; - -void PyObjectPlus::ProcessReplica() -{ -#ifdef WITH_PYTHON - /* Clear the proxy, will be created again if needed with GetProxy() - * otherwise the PyObject will point to the wrong reference */ - m_proxy= NULL; -#endif -} - -/* Sometimes we might want to manually invalidate a BGE type even if - * it hasn't been released by the BGE, say for example when an object - * is removed from a scene, accessing it may cause problems. - * - * In this case the current proxy is made invalid, disowned, - * and will raise an error on access. However if python can get access - * to this class again it will make a new proxy and work as expected. - */ -void PyObjectPlus::InvalidateProxy() // check typename of each parent -{ -#ifdef WITH_PYTHON - if (m_proxy) { - BGE_PROXY_REF(m_proxy)=NULL; - Py_DECREF(m_proxy); - m_proxy= NULL; - } -#endif -} - - -#ifdef WITH_PYTHON - -/*------------------------------ - * PyObjectPlus Type -- Every class, even the abstract one should have a Type - * ----------------------------- */ - - -PyTypeObject PyObjectPlus::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "PyObjectPlus", /*tp_name*/ - sizeof(PyObjectPlus_Proxy), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - py_base_dealloc, /* tp_dealloc */ - 0, /* printfunc tp_print; */ - 0, /* getattrfunc tp_getattr; */ - 0, /* setattrfunc tp_setattr; */ - 0, /* tp_compare */ /* DEPRECATED in python 3.0! */ - py_base_repr, /* tp_repr */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Method suites for standard classes */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* long tp_flags; */ - 0, 0, 0, 0, - /* weak reference enabler */ -#ifdef USE_WEAKREFS - offsetof(PyObjectPlus_Proxy, in_weakreflist), /* long tp_weaklistoffset; */ -#else - 0, -#endif - 0, 0, - Methods, - 0, - 0, - NULL // no subtype -}; - -PyObject *PyObjectPlus::py_base_repr(PyObject *self) // This should be the entry in Type. -{ - PyObjectPlus *self_plus= BGE_PROXY_REF(self); - if (self_plus==NULL) { - PyErr_SetString(PyExc_SystemError, BGE_PROXY_ERROR_MSG); - return NULL; - } - return self_plus->py_repr(); -} - - -PyObject *PyObjectPlus::py_base_new(PyTypeObject *type, PyObject *args, PyObject *kwds) -{ - PyTypeObject *base_type; - - /* one or more args is needed */ - if (!PyTuple_GET_SIZE(args)) { - PyErr_SetString(PyExc_TypeError, - "Expected at least one argument"); - return NULL; - } - - PyObjectPlus_Proxy *base = (PyObjectPlus_Proxy *)PyTuple_GET_ITEM(args, 0); - - /** - * the 'base' PyObject may be subclassed (multiple times even) - * we need to find the first C++ defined class to check 'type' - * is a subclass of the base arguments type. - * - * This way we can share one tp_new function for every PyObjectPlus - * - * eg. - * - * # CustomOb is called 'type' in this C code - * \code{.py} - * class CustomOb(GameTypes.KX_GameObject): - * pass - * - * # this calls py_base_new(...), the type of 'CustomOb' is checked to be a subclass of the 'cont.owner' type - * ob = CustomOb(cont.owner) - * \endcode - * */ - base_type= Py_TYPE(base); - while (base_type && !BGE_PROXY_CHECK_TYPE(base_type)) - base_type= base_type->tp_base; - - if (base_type==NULL || !BGE_PROXY_CHECK_TYPE(base_type)) { - PyErr_SetString(PyExc_TypeError, "can't subclass from a blender game type because the argument given is not a game class or subclass"); - return NULL; - } - - /* use base_type rather than Py_TYPE(base) because we could already be subtyped */ - if (!PyType_IsSubtype(type, base_type)) { - PyErr_Format(PyExc_TypeError, "can't subclass blender game type <%s> from <%s> because it is not a subclass", base_type->tp_name, type->tp_name); - return NULL; - } - - /* invalidate the existing base and return a new subclassed one, - * this is a bit dodgy in that it also attaches its self to the existing object - * which is not really 'correct' python OO but for our use its OK. */ - - PyObjectPlus_Proxy *ret = (PyObjectPlus_Proxy *) type->tp_alloc(type, 0); /* starts with 1 ref, used for the return ref' */ - ret->ref= base->ref; - ret->ptr= base->ptr; - ret->py_owns= base->py_owns; - ret->py_ref = base->py_ref; - - if (ret->py_ref) { - base->ref= NULL; /* invalidate! disallow further access */ - base->ptr = NULL; - if (ret->ref) - ret->ref->m_proxy= NULL; - /* 'base' may be freed after this func finished but not necessarily - * there is no reference to the BGE data now so it will throw an error on access */ - Py_DECREF(base); - if (ret->ref) { - ret->ref->m_proxy= (PyObject *)ret; /* no need to add a ref because one is added when creating. */ - Py_INCREF(ret); /* we return a new ref but m_proxy holds a ref so we need to add one */ - } - } else { - // generic structures don't hold a reference to this proxy, so don't increment ref count - if (ret->py_owns) - // but if the proxy owns the structure, there can be only one owner - base->ptr= NULL; - } - - return (PyObject *)ret; -} - -/** - * \param self A PyObjectPlus_Proxy - */ -void PyObjectPlus::py_base_dealloc(PyObject *self) // python wrapper -{ -#ifdef USE_WEAKREFS - if (BGE_PROXY_WKREF(self) != NULL) - PyObject_ClearWeakRefs((PyObject *) self); -#endif - - if (BGE_PROXY_PYREF(self)) { - PyObjectPlus *self_plus= BGE_PROXY_REF(self); - if (self_plus) { - if (BGE_PROXY_PYOWNS(self)) { /* Does python own this?, then delete it */ - self_plus->m_proxy = NULL; /* Need this to stop ~PyObjectPlus from decrefing m_proxy otherwise its decref'd twice and py-debug crashes */ - delete self_plus; - } - BGE_PROXY_REF(self)= NULL; // not really needed - } - // the generic pointer is not deleted directly, only through self_plus - BGE_PROXY_PTR(self)= NULL; // not really needed - } else { - void *ptr= BGE_PROXY_PTR(self); - if (ptr) { - if (BGE_PROXY_PYOWNS(self)) { /* Does python own this?, then delete it */ - // generic structure owned by python MUST be created though MEM_alloc - MEM_freeN(ptr); - } - BGE_PROXY_PTR(self)= NULL; // not really needed - } - } -#if 0 - /* is ok normally but not for subtyping, use tp_free instead. */ - PyObject_DEL( self ); -#else - Py_TYPE(self)->tp_free(self); -#endif -}; - -/*------------------------------ - * PyObjectPlus Methods -- Every class, even the abstract one should have a Methods -------------------------------*/ -PyMethodDef PyObjectPlus::Methods[] = { - {NULL, NULL} /* Sentinel */ -}; - -#define BGE_PY_ATTR_INVALID (&(PyObjectPlus::Attributes[0])) -PyAttributeDef PyObjectPlus::Attributes[] = { - KX_PYATTRIBUTE_RO_FUNCTION("invalid", PyObjectPlus, pyattr_get_invalid), - {NULL} //Sentinel -}; - - - -PyObject *PyObjectPlus::pyattr_get_invalid(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - return PyBool_FromLong(self_v ? 0:1); -} - -/* note, this is called as a python 'getset, where the PyAttributeDef is the closure */ -PyObject *PyObjectPlus::py_get_attrdef(PyObject *self_py, const PyAttributeDef *attrdef) -{ - PyObjectPlus *ref= (BGE_PROXY_REF(self_py)); - char* ptr = (attrdef->m_usePtr) ? (char*)BGE_PROXY_PTR(self_py) : (char*)ref; - if (ptr == NULL || (BGE_PROXY_PYREF(self_py) && (ref==NULL || !ref->py_is_valid()))) { - if (attrdef == BGE_PY_ATTR_INVALID) - Py_RETURN_TRUE; // don't bother running the function - - PyErr_SetString(PyExc_SystemError, BGE_PROXY_ERROR_MSG); - return NULL; - } - - if (attrdef->m_type == KX_PYATTRIBUTE_TYPE_DUMMY) - { - // fake attribute, ignore - return NULL; - } - if (attrdef->m_type == KX_PYATTRIBUTE_TYPE_FUNCTION) - { - // the attribute has no field correspondence, handover processing to function. - if (attrdef->m_getFunction == NULL) - return NULL; - return (*attrdef->m_getFunction)(ptr, attrdef); - } - ptr += attrdef->m_offset; - if (attrdef->m_length > 1) - { - PyObject *resultlist = PyList_New(attrdef->m_length); - for (unsigned int i=0; im_length; i++) - { - switch (attrdef->m_type) { - case KX_PYATTRIBUTE_TYPE_BOOL: - { - bool *val = reinterpret_cast(ptr); - ptr += sizeof(bool); - PyList_SET_ITEM(resultlist, i, PyBool_FromLong(*val)); - break; - } - case KX_PYATTRIBUTE_TYPE_SHORT: - { - short int *val = reinterpret_cast(ptr); - ptr += sizeof(short int); - PyList_SET_ITEM(resultlist, i, PyLong_FromLong(*val)); - break; - } - case KX_PYATTRIBUTE_TYPE_ENUM: - // enum are like int, just make sure the field size is the same - if (sizeof(int) != attrdef->m_size) - { - Py_DECREF(resultlist); - return NULL; - } - ATTR_FALLTHROUGH; - case KX_PYATTRIBUTE_TYPE_INT: - { - int *val = reinterpret_cast(ptr); - ptr += sizeof(int); - PyList_SET_ITEM(resultlist, i, PyLong_FromLong(*val)); - break; - } - case KX_PYATTRIBUTE_TYPE_FLOAT: - { - float *val = reinterpret_cast(ptr); - ptr += sizeof(float); - PyList_SET_ITEM(resultlist, i, PyFloat_FromDouble(*val)); - break; - } - default: - // no support for array of complex data - Py_DECREF(resultlist); - return NULL; - } - } - return resultlist; - } - else - { - switch (attrdef->m_type) { - case KX_PYATTRIBUTE_TYPE_FLAG: - { - bool bval; - switch (attrdef->m_size) { - case 1: - { - unsigned char *val = reinterpret_cast(ptr); - bval = (*val & attrdef->m_imin); - break; - } - case 2: - { - unsigned short *val = reinterpret_cast(ptr); - bval = (*val & attrdef->m_imin); - break; - } - case 4: - { - unsigned int *val = reinterpret_cast(ptr); - bval = (*val & attrdef->m_imin); - break; - } - default: - return NULL; - } - if (attrdef->m_imax) - bval = !bval; - return PyBool_FromLong(bval); - } - case KX_PYATTRIBUTE_TYPE_BOOL: - { - bool *val = reinterpret_cast(ptr); - return PyBool_FromLong(*val); - } - case KX_PYATTRIBUTE_TYPE_SHORT: - { - short int *val = reinterpret_cast(ptr); - return PyLong_FromLong(*val); - } - case KX_PYATTRIBUTE_TYPE_ENUM: - // enum are like int, just make sure the field size is the same - if (sizeof(int) != attrdef->m_size) - { - return NULL; - } - ATTR_FALLTHROUGH; - case KX_PYATTRIBUTE_TYPE_INT: - { - int *val = reinterpret_cast(ptr); - return PyLong_FromLong(*val); - } - case KX_PYATTRIBUTE_TYPE_FLOAT: - { - float *val = reinterpret_cast(ptr); - if (attrdef->m_imin == 0) { - if (attrdef->m_imax == 0) { - return PyFloat_FromDouble(*val); - } else { - // vector, verify size - if (attrdef->m_size != attrdef->m_imax*sizeof(float)) - { - return NULL; - } -#ifdef USE_MATHUTILS - return Vector_CreatePyObject(val, attrdef->m_imax, NULL); -#else - PyObject *resultlist = PyList_New(attrdef->m_imax); - for (unsigned int i=0; im_imax; i++) - { - PyList_SET_ITEM(resultlist, i, PyFloat_FromDouble(val[i])); - } - return resultlist; -#endif - } - } else { - // matrix case - if (attrdef->m_size != attrdef->m_imax*attrdef->m_imin*sizeof(float)) - { - return NULL; - } -#ifdef USE_MATHUTILS - return Matrix_CreatePyObject_wrap(val, attrdef->m_imin, attrdef->m_imax, NULL); -#else - PyObject *collist = PyList_New(attrdef->m_imin); - for (unsigned int i=0; im_imin; i++) - { - PyObject *col = PyList_New(attrdef->m_imax); - for (unsigned int j=0; jm_imax; j++) - { - PyList_SET_ITEM(col, j, PyFloat_FromDouble(val[j])); - } - PyList_SET_ITEM(collist, i, col); - val += attrdef->m_imax; - } - return collist; -#endif - } - } - case KX_PYATTRIBUTE_TYPE_VECTOR: - { - MT_Vector3 *val = reinterpret_cast(ptr); -#ifdef USE_MATHUTILS - float fval[3]; - val->getValue(fval); - return Vector_CreatePyObject(fval, 3, NULL); -#else - PyObject *resultlist = PyList_New(3); - for (unsigned int i=0; i<3; i++) - { - PyList_SET_ITEM(resultlist, i, PyFloat_FromDouble((*val)[i])); - } - return resultlist; -#endif - } - case KX_PYATTRIBUTE_TYPE_STRING: - { - STR_String *val = reinterpret_cast(ptr); - return PyUnicode_From_STR_String(*val); - } - case KX_PYATTRIBUTE_TYPE_CHAR: - { - return PyUnicode_FromString(ptr); - } - default: - return NULL; - } - } -} - - -static bool py_check_attr_float(float *var, PyObject *value, const PyAttributeDef *attrdef) -{ - float val = PyFloat_AsDouble(value); - if (val == -1.0f && PyErr_Occurred()) - { - PyErr_Format(PyExc_TypeError, "expected float value for attribute \"%s\"", attrdef->m_name); - return false; - } - if (attrdef->m_clamp) - { - if (val < attrdef->m_fmin) - val = attrdef->m_fmin; - else if (val > attrdef->m_fmax) - val = attrdef->m_fmax; - } - else if (val < attrdef->m_fmin || val > attrdef->m_fmax) - { - PyErr_Format(PyExc_ValueError, "value out of range for attribute \"%s\"", attrdef->m_name); - return false; - } - *var = (float)val; - return true; -} - -/* note, this is called as a python getset */ -int PyObjectPlus::py_set_attrdef(PyObject *self_py, PyObject *value, const PyAttributeDef *attrdef) -{ - PyObjectPlus *ref= (BGE_PROXY_REF(self_py)); - char* ptr = (attrdef->m_usePtr) ? (char*)BGE_PROXY_PTR(self_py) : (char*)ref; - if (ref==NULL || !ref->py_is_valid() || ptr==NULL) { - PyErr_SetString(PyExc_SystemError, BGE_PROXY_ERROR_MSG); - return PY_SET_ATTR_FAIL; - } - - void *undoBuffer = NULL; - void *sourceBuffer = NULL; - size_t bufferSize = 0; - PyObject *item = NULL; // to store object that must be dereferenced in case of error - PyObject *list = NULL; // to store object that must be dereferenced in case of error - - ptr += attrdef->m_offset; - if (attrdef->m_length > 1) - { - if (!PySequence_Check(value)) - { - PyErr_Format(PyExc_TypeError, "expected a sequence for attribute \"%s\"", attrdef->m_name); - return PY_SET_ATTR_FAIL; - } - if (PySequence_Size(value) != attrdef->m_length) - { - PyErr_Format(PyExc_TypeError, "incorrect number of elements in sequence for attribute \"%s\"", attrdef->m_name); - return PY_SET_ATTR_FAIL; - } - switch (attrdef->m_type) - { - case KX_PYATTRIBUTE_TYPE_FUNCTION: - if (attrdef->m_setFunction == NULL) - { - PyErr_Format(PyExc_AttributeError, "function attribute without function for attribute \"%s\", report to blender.org", attrdef->m_name); - return PY_SET_ATTR_FAIL; - } - return (*attrdef->m_setFunction)(ref, attrdef, value); - case KX_PYATTRIBUTE_TYPE_BOOL: - bufferSize = sizeof(bool); - break; - case KX_PYATTRIBUTE_TYPE_SHORT: - bufferSize = sizeof(short int); - break; - case KX_PYATTRIBUTE_TYPE_ENUM: - case KX_PYATTRIBUTE_TYPE_INT: - bufferSize = sizeof(int); - break; - case KX_PYATTRIBUTE_TYPE_FLOAT: - bufferSize = sizeof(float); - break; - default: - // should not happen - PyErr_Format(PyExc_AttributeError, "Unsupported attribute type for attribute \"%s\", report to blender.org", attrdef->m_name); - return PY_SET_ATTR_FAIL; - } - // let's implement a smart undo method - bufferSize *= attrdef->m_length; - undoBuffer = malloc(bufferSize); - sourceBuffer = ptr; - if (undoBuffer) - { - memcpy(undoBuffer, sourceBuffer, bufferSize); - } - for (int i=0; im_length; i++) - { - item = PySequence_GetItem(value, i); /* new ref */ - switch (attrdef->m_type) - { - case KX_PYATTRIBUTE_TYPE_BOOL: - { - bool *var = reinterpret_cast(ptr); - ptr += sizeof(bool); - if (PyLong_Check(item)) - { - *var = (PyLong_AsLong(item) != 0); - } - else if (PyBool_Check(item)) - { - *var = (item == Py_True); - } - else - { - PyErr_Format(PyExc_TypeError, "expected an integer or a bool for attribute \"%s\"", attrdef->m_name); - goto UNDO_AND_ERROR; - } - break; - } - case KX_PYATTRIBUTE_TYPE_SHORT: - { - short int *var = reinterpret_cast(ptr); - ptr += sizeof(short int); - if (PyLong_Check(item)) - { - int val = PyLong_AsLong(item); - if (attrdef->m_clamp) - { - if (val < attrdef->m_imin) - val = attrdef->m_imin; - else if (val > attrdef->m_imax) - val = attrdef->m_imax; - } - else if (val < attrdef->m_imin || val > attrdef->m_imax) - { - PyErr_Format(PyExc_ValueError, "item value out of range for attribute \"%s\"", attrdef->m_name); - goto UNDO_AND_ERROR; - } - *var = (short int)val; - } - else - { - PyErr_Format(PyExc_TypeError, "expected an integer for attribute \"%s\"", attrdef->m_name); - goto UNDO_AND_ERROR; - } - break; - } - case KX_PYATTRIBUTE_TYPE_ENUM: - // enum are equivalent to int, just make sure that the field size matches: - if (sizeof(int) != attrdef->m_size) - { - PyErr_Format(PyExc_AttributeError, "Size check error for attribute, \"%s\", report to blender.org", attrdef->m_name); - goto UNDO_AND_ERROR; - } - ATTR_FALLTHROUGH; - case KX_PYATTRIBUTE_TYPE_INT: - { - int *var = reinterpret_cast(ptr); - ptr += sizeof(int); - if (PyLong_Check(item)) - { - int val = PyLong_AsLong(item); - if (attrdef->m_clamp) - { - if (val < attrdef->m_imin) - val = attrdef->m_imin; - else if (val > attrdef->m_imax) - val = attrdef->m_imax; - } - else if (val < attrdef->m_imin || val > attrdef->m_imax) - { - PyErr_Format(PyExc_ValueError, "item value out of range for attribute \"%s\"", attrdef->m_name); - goto UNDO_AND_ERROR; - } - *var = (int)val; - } - else - { - PyErr_Format(PyExc_TypeError, "expected an integer for attribute \"%s\"", attrdef->m_name); - goto UNDO_AND_ERROR; - } - break; - } - case KX_PYATTRIBUTE_TYPE_FLOAT: - { - float *var = reinterpret_cast(ptr); - ptr += sizeof(float); - float val = PyFloat_AsDouble(item); - if (val == -1.0f && PyErr_Occurred()) - { - PyErr_Format(PyExc_TypeError, "expected a float for attribute \"%s\"", attrdef->m_name); - goto UNDO_AND_ERROR; - } - else if (attrdef->m_clamp) - { - if (val < attrdef->m_fmin) - val = attrdef->m_fmin; - else if (val > attrdef->m_fmax) - val = attrdef->m_fmax; - } - else if (val < attrdef->m_fmin || val > attrdef->m_fmax) - { - PyErr_Format(PyExc_ValueError, "item value out of range for attribute \"%s\"", attrdef->m_name); - goto UNDO_AND_ERROR; - } - *var = (float)val; - break; - } - default: - // should not happen - PyErr_Format(PyExc_AttributeError, "type check error for attribute \"%s\", report to blender.org", attrdef->m_name); - goto UNDO_AND_ERROR; - } - // finished using item, release - Py_DECREF(item); - item = NULL; - } - // no error, call check function if any - if (attrdef->m_checkFunction != NULL) - { - if ((*attrdef->m_checkFunction)(ref, attrdef) != 0) - { - // if the checing function didnt set an error then set a generic one here so we don't set an error with no exception - if (PyErr_Occurred()==0) - PyErr_Format(PyExc_AttributeError, "type check error for attribute \"%s\", reasion unknown", attrdef->m_name); - - // post check returned an error, restore values - UNDO_AND_ERROR: - if (undoBuffer) - { - memcpy(sourceBuffer, undoBuffer, bufferSize); - free(undoBuffer); - } - if (item) - Py_DECREF(item); - return PY_SET_ATTR_FAIL; - } - } - if (undoBuffer) - free(undoBuffer); - return PY_SET_ATTR_SUCCESS; - } - else // simple attribute value - { - if (attrdef->m_type == KX_PYATTRIBUTE_TYPE_FUNCTION) - { - if (attrdef->m_setFunction == NULL) - { - PyErr_Format(PyExc_AttributeError, "function attribute without function \"%s\", report to blender.org", attrdef->m_name); - return PY_SET_ATTR_FAIL; - } - return (*attrdef->m_setFunction)(ref, attrdef, value); - } - if (attrdef->m_checkFunction != NULL || attrdef->m_type == KX_PYATTRIBUTE_TYPE_VECTOR) - { - // post check function is provided, prepare undo buffer - sourceBuffer = ptr; - switch (attrdef->m_type) - { - case KX_PYATTRIBUTE_TYPE_BOOL: - bufferSize = sizeof(bool); - break; - case KX_PYATTRIBUTE_TYPE_SHORT: - bufferSize = sizeof(short); - break; - case KX_PYATTRIBUTE_TYPE_ENUM: - case KX_PYATTRIBUTE_TYPE_FLAG: - case KX_PYATTRIBUTE_TYPE_CHAR: - bufferSize = attrdef->m_size; - break; - case KX_PYATTRIBUTE_TYPE_INT: - bufferSize = sizeof(int); - break; - case KX_PYATTRIBUTE_TYPE_FLOAT: - bufferSize = sizeof(float); - if (attrdef->m_imax) - bufferSize *= attrdef->m_imax; - if (attrdef->m_imin) - bufferSize *= attrdef->m_imin; - break; - case KX_PYATTRIBUTE_TYPE_STRING: - sourceBuffer = reinterpret_cast(ptr)->Ptr(); - if (sourceBuffer) - bufferSize = strlen(reinterpret_cast(sourceBuffer))+1; - break; - case KX_PYATTRIBUTE_TYPE_VECTOR: - bufferSize = sizeof(MT_Vector3); - break; - default: - PyErr_Format(PyExc_AttributeError, "unknown type for attribute \"%s\", report to blender.org", attrdef->m_name); - return PY_SET_ATTR_FAIL; - } - if (bufferSize) - { - undoBuffer = malloc(bufferSize); - if (undoBuffer) - { - memcpy(undoBuffer, sourceBuffer, bufferSize); - } - } - } - - switch (attrdef->m_type) - { - case KX_PYATTRIBUTE_TYPE_BOOL: - { - bool *var = reinterpret_cast(ptr); - if (PyLong_Check(value)) - { - *var = (PyLong_AsLong(value) != 0); - } - else if (PyBool_Check(value)) - { - *var = (value == Py_True); - } - else - { - PyErr_Format(PyExc_TypeError, "expected an integer or a bool for attribute \"%s\"", attrdef->m_name); - goto FREE_AND_ERROR; - } - break; - } - case KX_PYATTRIBUTE_TYPE_FLAG: - { - bool bval; - if (PyLong_Check(value)) - { - bval = (PyLong_AsLong(value) != 0); - } - else if (PyBool_Check(value)) - { - bval = (value == Py_True); - } - else - { - PyErr_Format(PyExc_TypeError, "expected an integer or a bool for attribute \"%s\"", attrdef->m_name); - goto FREE_AND_ERROR; - } - if (attrdef->m_imax) - bval = !bval; - switch (attrdef->m_size) { - case 1: - { - unsigned char *val = reinterpret_cast(ptr); - *val = (*val & ~attrdef->m_imin) | ((bval)?attrdef->m_imin:0); - break; - } - case 2: - { - unsigned short *val = reinterpret_cast(ptr); - *val = (*val & ~attrdef->m_imin) | ((bval)?attrdef->m_imin:0); - break; - } - case 4: - { - unsigned int *val = reinterpret_cast(ptr); - *val = (*val & ~attrdef->m_imin) | ((bval)?attrdef->m_imin:0); - break; - } - default: - PyErr_Format(PyExc_TypeError, "internal error: unsupported flag field \"%s\"", attrdef->m_name); - goto FREE_AND_ERROR; - } - break; - } - case KX_PYATTRIBUTE_TYPE_SHORT: - { - short int *var = reinterpret_cast(ptr); - if (PyLong_Check(value)) - { - int val = PyLong_AsLong(value); - if (attrdef->m_clamp) - { - if (val < attrdef->m_imin) - val = attrdef->m_imin; - else if (val > attrdef->m_imax) - val = attrdef->m_imax; - } - else if (val < attrdef->m_imin || val > attrdef->m_imax) - { - PyErr_Format(PyExc_ValueError, "value out of range for attribute \"%s\"", attrdef->m_name); - goto FREE_AND_ERROR; - } - *var = (short int)val; - } - else - { - PyErr_Format(PyExc_TypeError, "expected an integer for attribute \"%s\"", attrdef->m_name); - goto FREE_AND_ERROR; - } - break; - } - case KX_PYATTRIBUTE_TYPE_ENUM: - // enum are equivalent to int, just make sure that the field size matches: - if (sizeof(int) != attrdef->m_size) - { - PyErr_Format(PyExc_AttributeError, "attribute size check error for attribute \"%s\", report to blender.org", attrdef->m_name); - goto FREE_AND_ERROR; - } - ATTR_FALLTHROUGH; - case KX_PYATTRIBUTE_TYPE_INT: - { - int *var = reinterpret_cast(ptr); - if (PyLong_Check(value)) - { - int val = PyLong_AsLong(value); - if (attrdef->m_clamp) - { - if (val < attrdef->m_imin) - val = attrdef->m_imin; - else if (val > attrdef->m_imax) - val = attrdef->m_imax; - } - else if (val < attrdef->m_imin || val > attrdef->m_imax) - { - PyErr_Format(PyExc_ValueError, "value out of range for attribute \"%s\"", attrdef->m_name); - goto FREE_AND_ERROR; - } - *var = (int)val; - } - else - { - PyErr_Format(PyExc_TypeError, "expected an integer for attribute \"%s\"", attrdef->m_name); - goto FREE_AND_ERROR; - } - break; - } - case KX_PYATTRIBUTE_TYPE_FLOAT: - { - float *var = reinterpret_cast(ptr); - if (attrdef->m_imin != 0) - { - if (attrdef->m_size != attrdef->m_imin*attrdef->m_imax*sizeof(float)) - { - PyErr_Format(PyExc_TypeError, "internal error: incorrect field size for attribute \"%s\"", attrdef->m_name); - goto FREE_AND_ERROR; - } - if (!PySequence_Check(value) || PySequence_Size(value) != attrdef->m_imin) - { - PyErr_Format(PyExc_TypeError, "expected a sequence of [%d][%d] floats for attribute \"%s\"", attrdef->m_imin, attrdef->m_imax, attrdef->m_name); - goto FREE_AND_ERROR; - } - for (int i=0; im_imin; i++) - { - PyObject *list = PySequence_GetItem(value, i); /* new ref */ - if (!PySequence_Check(list) || PySequence_Size(list) != attrdef->m_imax) - { - PyErr_Format(PyExc_TypeError, "expected a sequence of [%d][%d] floats for attribute \"%s\"", attrdef->m_imin, attrdef->m_imax, attrdef->m_name); - goto RESTORE_AND_ERROR; - } - for (int j=0; jm_imax; j++) - { - item = PySequence_GetItem(list, j); /* new ref */ - if (!py_check_attr_float(var, item, attrdef)) - { - PyErr_Format(PyExc_TypeError, "expected a sequence of [%d][%d] floats for attribute \"%s\"", attrdef->m_imin, attrdef->m_imax, attrdef->m_name); - goto RESTORE_AND_ERROR; - } - Py_DECREF(item); - item = NULL; - ++var; - } - Py_DECREF(list); - list = NULL; - } - } - else if (attrdef->m_imax != 0) - { - if (attrdef->m_size != attrdef->m_imax*sizeof(float)) - { - PyErr_Format(PyExc_TypeError, "internal error: incorrect field size for attribute \"%s\"", attrdef->m_name); - goto FREE_AND_ERROR; - } - if (!PySequence_Check(value) || PySequence_Size(value) != attrdef->m_imax) - { - PyErr_Format(PyExc_TypeError, "expected a sequence of [%d] floats for attribute \"%s\"", attrdef->m_imax, attrdef->m_name); - goto FREE_AND_ERROR; - } - for (int i=0; im_imax; i++) - { - item = PySequence_GetItem(value, i); /* new ref */ - if (!py_check_attr_float(var, item, attrdef)) - { - goto RESTORE_AND_ERROR; - } - Py_DECREF(item); - item = NULL; - ++var; - } - } - else - { - if (!py_check_attr_float(var, value, attrdef)) - goto FREE_AND_ERROR; - } - break; - } - case KX_PYATTRIBUTE_TYPE_VECTOR: - { - if (!PySequence_Check(value) || PySequence_Size(value) != 3) - { - PyErr_Format(PyExc_TypeError, "expected a sequence of 3 floats for attribute \"%s\"", attrdef->m_name); - goto FREE_AND_ERROR; - } - MT_Vector3 *var = reinterpret_cast(ptr); - for (int i=0; i<3; i++) - { - item = PySequence_GetItem(value, i); /* new ref */ - float val = PyFloat_AsDouble(item); - Py_DECREF(item); - item = NULL; - if (val == -1.0f && PyErr_Occurred()) - { - PyErr_Format(PyExc_TypeError, "expected a sequence of 3 floats for attribute \"%s\"", attrdef->m_name); - goto RESTORE_AND_ERROR; - } - else if (attrdef->m_clamp) - { - if (val < attrdef->m_fmin) - val = attrdef->m_fmin; - else if (val > attrdef->m_fmax) - val = attrdef->m_fmax; - } - else if (val < attrdef->m_fmin || val > attrdef->m_fmax) - { - PyErr_Format(PyExc_ValueError, "value out of range for attribute \"%s\"", attrdef->m_name); - goto RESTORE_AND_ERROR; - } - (*var)[i] = (MT_Scalar)val; - } - break; - } - case KX_PYATTRIBUTE_TYPE_CHAR: - { - if (PyUnicode_Check(value)) - { - Py_ssize_t val_size; - const char *val = _PyUnicode_AsStringAndSize(value, &val_size); - strncpy(ptr, val, attrdef->m_size); - ptr[attrdef->m_size-1] = 0; - } - else - { - PyErr_Format(PyExc_TypeError, "expected a string for attribute \"%s\"", attrdef->m_name); - goto FREE_AND_ERROR; - } - break; - } - case KX_PYATTRIBUTE_TYPE_STRING: - { - STR_String *var = reinterpret_cast(ptr); - if (PyUnicode_Check(value)) - { - Py_ssize_t val_len; - const char *val = _PyUnicode_AsStringAndSize(value, &val_len); /* XXX, should be 'const' but we do a silly trick to have a shorter string */ - if (attrdef->m_clamp) - { - if (val_len < attrdef->m_imin) - { - // can't increase the length of the string - PyErr_Format(PyExc_ValueError, "string length too short for attribute \"%s\"", attrdef->m_name); - goto FREE_AND_ERROR; - } - else if (val_len > attrdef->m_imax) - { - // trim the string - var->SetLength(attrdef->m_imax); - memcpy(var->Ptr(), val, attrdef->m_imax - 1); - break; - } - } else if (val_len < attrdef->m_imin || val_len > attrdef->m_imax) - { - PyErr_Format(PyExc_ValueError, "string length out of range for attribute \"%s\"", attrdef->m_name); - goto FREE_AND_ERROR; - } - *var = val; - } - else - { - PyErr_Format(PyExc_TypeError, "expected a string for attribute \"%s\"", attrdef->m_name); - goto FREE_AND_ERROR; - } - break; - } - default: - // should not happen - PyErr_Format(PyExc_AttributeError, "unknown type for attribute \"%s\", report to blender.org", attrdef->m_name); - goto FREE_AND_ERROR; - } - } - // check if post processing is needed - if (attrdef->m_checkFunction != NULL) - { - if ((*attrdef->m_checkFunction)(ref, attrdef) != 0) - { - // restore value - RESTORE_AND_ERROR: - if (undoBuffer) - { - if (attrdef->m_type == KX_PYATTRIBUTE_TYPE_STRING) - { - // special case for STR_String: restore the string - STR_String *var = reinterpret_cast(ptr); - *var = reinterpret_cast(undoBuffer); - } - else - { - // other field type have direct values - memcpy(ptr, undoBuffer, bufferSize); - } - } - FREE_AND_ERROR: - if (undoBuffer) - free(undoBuffer); - if (list) - Py_DECREF(list); - if (item) - Py_DECREF(item); - return 1; - } - } - if (undoBuffer) - free(undoBuffer); - return 0; -} - - - -/*------------------------------ - * PyObjectPlus repr -- representations -------------------------------*/ -PyObject *PyObjectPlus::py_repr(void) -{ - PyErr_SetString(PyExc_SystemError, "Representation not overridden by object."); - return NULL; -} - -PyObject *PyObjectPlus::GetProxyPlus_Ext(PyObjectPlus *self, PyTypeObject *tp, void *ptr) -{ - if (self->m_proxy==NULL) - { - self->m_proxy = reinterpret_castPyObject_NEW( PyObjectPlus_Proxy, tp); - BGE_PROXY_PYOWNS(self->m_proxy) = false; - BGE_PROXY_PYREF(self->m_proxy) = true; -#ifdef USE_WEAKREFS - BGE_PROXY_WKREF(self->m_proxy) = NULL; -#endif - } - //PyObject_Print(self->m_proxy, stdout, 0); - //printf("ref %d\n", self->m_proxy->ob_refcnt); - - BGE_PROXY_REF(self->m_proxy) = self; /* Its possible this was set to NULL, so set it back here */ - BGE_PROXY_PTR(self->m_proxy) = ptr; - Py_INCREF(self->m_proxy); /* we own one, thos ones fore the return */ - return self->m_proxy; -} - -PyObject *PyObjectPlus::NewProxyPlus_Ext(PyObjectPlus *self, PyTypeObject *tp, void *ptr, bool py_owns) -{ - if (!self) - { - // in case of proxy without reference to game object - PyObject *proxy = reinterpret_castPyObject_NEW( PyObjectPlus_Proxy, tp); - BGE_PROXY_PYREF(proxy) = false; - BGE_PROXY_PYOWNS(proxy) = py_owns; - BGE_PROXY_REF(proxy) = NULL; - BGE_PROXY_PTR(proxy) = ptr; -#ifdef USE_WEAKREFS - BGE_PROXY_WKREF(proxy) = NULL; -#endif - return proxy; - } - if (self->m_proxy) - { - if (py_owns) - { /* Free */ - BGE_PROXY_REF(self->m_proxy) = NULL; - Py_DECREF(self->m_proxy); - self->m_proxy= NULL; - } - else { - Py_INCREF(self->m_proxy); - return self->m_proxy; - } - - } - - GetProxyPlus_Ext(self, tp, ptr); - if (py_owns) { - BGE_PROXY_PYOWNS(self->m_proxy) = py_owns; - Py_DECREF(self->m_proxy); /* could avoid thrashing here but for now its ok */ - } - return self->m_proxy; -} - -PyObject *PyUnicode_From_STR_String(const STR_String& str) -{ - return PyUnicode_FromStringAndSize(str.ReadPtr(), str.Length()); -} - -/////////////////////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////////////////////// -/* deprecation warning management */ - -bool PyObjectPlus::m_ignore_deprecation_warnings(false); -void PyObjectPlus::SetDeprecationWarnings(bool ignoreDeprecationWarnings) -{ - m_ignore_deprecation_warnings = ignoreDeprecationWarnings; -} - -void PyObjectPlus::ShowDeprecationWarning_func(const char *old_way, const char *new_way) -{ - printf("Method %s is deprecated, please use %s instead.\n", old_way, new_way); - PyC_LineSpit(); -} - -void PyObjectPlus::ClearDeprecationWarning() -{ - WarnLink *wlink_next; - WarnLink *wlink = GetDeprecationWarningLinkFirst(); - - while (wlink) { - wlink->warn_done= false; /* no need to NULL the link, its cleared before adding to the list next time round */ - wlink_next= reinterpret_cast(wlink->link); - wlink->link= NULL; - wlink= wlink_next; - } - NullDeprecationWarning(); -} - -static WarnLink *m_base_wlink_first = NULL; -static WarnLink *m_base_wlink_last = NULL; - -WarnLink* PyObjectPlus::GetDeprecationWarningLinkFirst(void) {return m_base_wlink_first;} -WarnLink* PyObjectPlus::GetDeprecationWarningLinkLast(void) {return m_base_wlink_last;} -void PyObjectPlus::SetDeprecationWarningFirst(WarnLink* wlink) {m_base_wlink_first= wlink;} -void PyObjectPlus::SetDeprecationWarningLinkLast(WarnLink* wlink) {m_base_wlink_last= wlink;} -void PyObjectPlus::NullDeprecationWarning() {m_base_wlink_first= m_base_wlink_last= NULL;} - -#endif // WITH_PYTHON diff --git a/source/gameengine/Expressions/intern/PythonCallBack.cpp b/source/gameengine/Expressions/intern/PythonCallBack.cpp deleted file mode 100644 index 3fb84569eca..00000000000 --- a/source/gameengine/Expressions/intern/PythonCallBack.cpp +++ /dev/null @@ -1,119 +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): Porteries Tristan. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/Expressions/intern/PythonCallBack.cpp - * \ingroup expressions - */ - -#include "EXP_PythonCallBack.h" -#include -#include - -#include "BLI_alloca.h" - -/** Check if a python value is a function and have the correct number of arguments. - * \param value The python value to check. - * \param minargcount The minimum of arguments possible. - * \param maxargcount The maximum of arguments possible. - * \param r_argcount The number of argument of this function, this variable will be - * changed in the function. - */ -static PyObject *CheckPythonFunction(PyObject *value, unsigned int minargcount, unsigned int maxargcount, unsigned int &r_argcount) -{ - if (PyMethod_Check(value)) { - PyCodeObject *code = ((PyCodeObject *)PyFunction_GET_CODE(PyMethod_GET_FUNCTION(value))); - // *args support - r_argcount = (code->co_flags & CO_VARARGS) ? maxargcount : (code->co_argcount - 1); - } - else if (PyFunction_Check(value)) { - PyCodeObject *code = ((PyCodeObject *)PyFunction_GET_CODE(value)); - // *args support - r_argcount = (code->co_flags & CO_VARARGS) ? maxargcount : code->co_argcount; - } - else { // is not a methode or a function - PyErr_Format(PyExc_TypeError, "items must be functions or methodes, not %s", - Py_TYPE(value)->tp_name); - return NULL; - } - - if (r_argcount < minargcount || r_argcount > maxargcount) { - // wrong number of arguments - PyErr_Format(PyExc_TypeError, "methode or function (%s) has invalid number of arguments (%i) must be between %i and %i", - Py_TYPE(value)->tp_name, r_argcount, minargcount, maxargcount); - return NULL; - } - - return value; -} - -/** Create a python tuple to call a python function - * \param argcount The lenght of the tuple. - * \param arglist The fully list of python arguments [size >= argcount]. - */ -static PyObject *CreatePythonTuple(unsigned int argcount, PyObject **arglist) -{ - PyObject *tuple = PyTuple_New(argcount); - - for (unsigned int i = 0; i < argcount; ++i) { - PyObject *item = arglist[i]; - // increment reference and copy it in a new tuple - Py_INCREF(item); - PyTuple_SET_ITEM(tuple, i, item); - } - - return tuple; -} - -void RunPythonCallBackList(PyObject *functionlist, PyObject **arglist, unsigned int minargcount, unsigned int maxargcount) -{ - unsigned int size = PyList_Size(functionlist); - PyObject **argTuples = (PyObject **)BLI_array_alloca(argTuples, maxargcount - minargcount + 1); - memset(argTuples, 0, sizeof(PyObject *) * (maxargcount - minargcount + 1)); - - for (unsigned int i = 0; i < size; ++i) { - unsigned int funcargcount = 0; - - PyObject *item = PyList_GET_ITEM(functionlist, i); - PyObject *func = CheckPythonFunction(item, minargcount, maxargcount, funcargcount); - if (!func) { // this item fails the check - PyErr_Print(); - PyErr_Clear(); - continue; - } - - // get correct argument tuple. - PyObject *tuple = argTuples[funcargcount - minargcount]; - if (!tuple) - argTuples[funcargcount - minargcount] = tuple = CreatePythonTuple(funcargcount, arglist); - - PyObject *ret = PyObject_Call(func, tuple, NULL); - if (!ret) { // if ret is NULL this seems that the function doesn't work ! - PyErr_Print(); - PyErr_Clear(); - } - else - Py_DECREF(ret); - } - - for (unsigned int i = 0; i <= (maxargcount - minargcount); ++i) - Py_XDECREF(argTuples[i]); -} diff --git a/source/gameengine/Expressions/intern/StringValue.cpp b/source/gameengine/Expressions/intern/StringValue.cpp deleted file mode 100644 index ddf61dc441c..00000000000 --- a/source/gameengine/Expressions/intern/StringValue.cpp +++ /dev/null @@ -1,147 +0,0 @@ -/** \file gameengine/Expressions/StringValue.cpp - * \ingroup expressions - */ -// StringValue.cpp: implementation of the CStringValue class. -/* - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -#include "EXP_StringValue.h" -#include "EXP_BoolValue.h" -#include "EXP_ErrorValue.h" -#include "EXP_VoidValue.h" - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -/** - * pre: false - * effect: constructs a new CStringValue - */ -CStringValue::CStringValue() -{ - m_strString = "[Illegal String constructor call]"; -} - -/** - * pre: - * effect: constructs a new CStringValue containing text txt - */ -CStringValue::CStringValue(const char *txt,const char *name,AllocationTYPE alloctype) -{ - m_strString = txt; - SetName(name); - - if (alloctype==CValue::STACKVALUE) - { - CValue::DisableRefCount(); - - } - - -} - - -/** - * pre: - * ret: a new object containing the result of applying operator op to this - * object and val - */ -CValue* CStringValue::Calc(VALUE_OPERATOR op, CValue *val) -{ - //return val->CalrcString(op, this); - return val->CalcFinal(VALUE_STRING_TYPE, op, this); -} - -/** - * pre: the type of val is dtype - * ret: a new object containing the result of applying operator op to val and - * this object - */ -CValue* CStringValue::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val) -{ - CValue *ret; - - if (op == VALUE_ADD_OPERATOR) { - if (dtype == VALUE_ERROR_TYPE) - ret = new CErrorValue(val->GetText() + op2str(op) + GetText()); - else - ret = new CStringValue(val->GetText() + GetText(),""); - } - else { - if (dtype == VALUE_STRING_TYPE || dtype == VALUE_EMPTY_TYPE) { - switch (op) { - case VALUE_EQL_OPERATOR: - ret = new CBoolValue(val->GetText() == GetText()); - break; - case VALUE_NEQ_OPERATOR: - ret = new CBoolValue(val->GetText() != GetText()); - break; - case VALUE_GRE_OPERATOR: - ret = new CBoolValue(val->GetText() > GetText()); - break; - case VALUE_LES_OPERATOR: - ret = new CBoolValue(val->GetText() < GetText()); - break; - case VALUE_GEQ_OPERATOR: - ret = new CBoolValue(val->GetText() >= GetText()); - break; - case VALUE_LEQ_OPERATOR: - ret = new CBoolValue(val->GetText() <= GetText()); - break; - default: - ret = new CErrorValue(val->GetText() + op2str(op) + "[operator not allowed on strings]"); - break; - } - } - else { - ret = new CErrorValue(val->GetText() + op2str(op) + "[operator not allowed on strings]"); - } - } - return ret; -} - - - -double CStringValue::GetNumber() -{ - return -1; -} - - - -int CStringValue::GetValueType() -{ - return VALUE_STRING_TYPE; -} - - - -const STR_String & CStringValue::GetText() -{ - return m_strString; -} - -bool CStringValue::IsEqual(const STR_String & other) -{ - return (m_strString == other); -} - -CValue* CStringValue::GetReplica() -{ - CStringValue* replica = new CStringValue(*this); - replica->ProcessReplica(); - return replica; -}; - - diff --git a/source/gameengine/Expressions/intern/Value.cpp b/source/gameengine/Expressions/intern/Value.cpp deleted file mode 100644 index f8796a76e76..00000000000 --- a/source/gameengine/Expressions/intern/Value.cpp +++ /dev/null @@ -1,672 +0,0 @@ -/** \file gameengine/Expressions/Value.cpp - * \ingroup expressions - */ -// Value.cpp: implementation of the CValue class. -// developed at Eindhoven University of Technology, 1997 -// by the OOPS team -////////////////////////////////////////////////////////////////////// -/* - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ -#include "EXP_Value.h" -#include "EXP_BoolValue.h" -#include "EXP_FloatValue.h" -#include "EXP_IntValue.h" -#include "EXP_VectorValue.h" -#include "EXP_VoidValue.h" -#include "EXP_StringValue.h" -#include "EXP_ErrorValue.h" -#include "EXP_ListValue.h" - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -double CValue::m_sZeroVec[3] = {0.0,0.0,0.0}; - -#ifdef WITH_PYTHON - -PyTypeObject CValue::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "CValue", - sizeof(PyObjectPlus_Proxy), - 0, - py_base_dealloc, - 0, - 0, - 0, - 0, - py_base_repr, - 0, - 0,0,0,0,0, - NULL, - NULL, - 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 CValue::Methods[] = { - {NULL,NULL} //Sentinel -}; -#endif // WITH_PYTHON - - -/*#define CVALUE_DEBUG*/ -#ifdef CVALUE_DEBUG -int gRefCount; -struct SmartCValueRef -{ - CValue *m_ref; - int m_count; - SmartCValueRef(CValue *ref) - { - m_ref = ref; - m_count = gRefCount++; - } -}; - -#include - -std::vector gRefList; -#endif - -#ifdef DEBUG -//int gRefCountValue; -#endif - -CValue::CValue() - : PyObjectPlus(), - -m_pNamedPropertyArray(NULL), -m_refcount(1) -/* -pre: false -effect: constucts a CValue -*/ -{ - //debug(gRefCountValue++) // debugging -#ifdef DEBUG - //gRefCountValue++; -#ifdef CVALUE_DEBUG - gRefList.push_back(SmartCValueRef(this)); -#endif -#endif -} - - - -CValue::~CValue() -/* -pre: -effect: deletes the object -*/ -{ - ClearProperties(); - - assertd (m_refcount==0); -#ifdef CVALUE_DEBUG - std::vector::iterator it; - for (it=gRefList.begin(); it!=gRefList.end(); it++) - { - if (it->m_ref == this) - { - *it = gRefList.back(); - gRefList.pop_back(); - break; - } - } -#endif -} - - -/* UNUSED */ -#if 0 -#define VALUE_SUB(val1, val2) (val1)->Calc(VALUE_SUB_OPERATOR, val2) -#define VALUE_MUL(val1, val2) (val1)->Calc(VALUE_MUL_OPERATOR, val2) -#define VALUE_DIV(val1, val2) (val1)->Calc(VALUE_DIV_OPERATOR, val2) -#define VALUE_NEG(val1) (val1)->Calc(VALUE_NEG_OPERATOR, val1) -#define VALUE_POS(val1) (val1)->Calc(VALUE_POS_OPERATOR, val1) -#endif - -STR_String CValue::op2str(VALUE_OPERATOR op) -{ - //pre: - //ret: the stringrepresentation of operator op - - STR_String opmsg; - switch (op) { - case VALUE_MOD_OPERATOR: - opmsg = " % "; - break; - case VALUE_ADD_OPERATOR: - opmsg = " + "; - break; - case VALUE_SUB_OPERATOR: - opmsg = " - "; - break; - case VALUE_MUL_OPERATOR: - opmsg = " * "; - break; - case VALUE_DIV_OPERATOR: - opmsg = " / "; - break; - case VALUE_NEG_OPERATOR: - opmsg = " -"; - break; - case VALUE_POS_OPERATOR: - opmsg = " +"; - break; - case VALUE_AND_OPERATOR: - opmsg = " & "; - break; - case VALUE_OR_OPERATOR: - opmsg = " | "; - break; - case VALUE_EQL_OPERATOR: - opmsg = " = "; - break; - case VALUE_NEQ_OPERATOR: - opmsg = " != "; - break; - case VALUE_NOT_OPERATOR: - opmsg = " !"; - break; - default: - opmsg="Error in Errorhandling routine."; - // AfxMessageBox("Invalid operator"); - break; - } - return opmsg; -} - - - - - -//--------------------------------------------------------------------------------------------------------------------- -// Property Management -//--------------------------------------------------------------------------------------------------------------------- - - - -// -// Set property , overwrites and releases a previous property with the same name if needed -// -void CValue::SetProperty(const STR_String & name,CValue* ioProperty) -{ - if (ioProperty==NULL) - { // Check if somebody is setting an empty property - trace("Warning:trying to set empty property!"); - return; - } - - if (m_pNamedPropertyArray) - { // Try to replace property (if so -> exit as soon as we replaced it) - CValue* oldval = (*m_pNamedPropertyArray)[name]; - if (oldval) - oldval->Release(); - } - else { // Make sure we have a property array - m_pNamedPropertyArray = new std::map; - } - - // Add property at end of array - (*m_pNamedPropertyArray)[name] = ioProperty->AddRef();//->Add(ioProperty); -} - -void CValue::SetProperty(const char* name,CValue* ioProperty) -{ - if (ioProperty==NULL) - { // Check if somebody is setting an empty property - trace("Warning:trying to set empty property!"); - return; - } - - if (m_pNamedPropertyArray) - { // Try to replace property (if so -> exit as soon as we replaced it) - CValue* oldval = (*m_pNamedPropertyArray)[name]; - if (oldval) - oldval->Release(); - } - else { // Make sure we have a property array - m_pNamedPropertyArray = new std::map; - } - - // Add property at end of array - (*m_pNamedPropertyArray)[name] = ioProperty->AddRef();//->Add(ioProperty); -} - -// -// Get pointer to a property with name , returns NULL if there is no property named -// -CValue* CValue::GetProperty(const STR_String & inName) -{ - if (m_pNamedPropertyArray) { - std::map::iterator it = m_pNamedPropertyArray->find(inName); - if (it != m_pNamedPropertyArray->end()) - return (*it).second; - } - return NULL; -} - -CValue* CValue::GetProperty(const char *inName) -{ - if (m_pNamedPropertyArray) { - std::map::iterator it = m_pNamedPropertyArray->find(inName); - if (it != m_pNamedPropertyArray->end()) - return (*it).second; - } - return NULL; -} - -// -// Get text description of property with name , returns an empty string if there is no property named -// -const STR_String& CValue::GetPropertyText(const STR_String & inName) -{ - const static STR_String sEmpty(""); - - CValue *property = GetProperty(inName); - if (property) - return property->GetText(); - else - return sEmpty; -} - -float CValue::GetPropertyNumber(const STR_String& inName,float defnumber) -{ - CValue *property = GetProperty(inName); - if (property) - return property->GetNumber(); - else - return defnumber; -} - - - -// -// Remove the property named , returns true if the property was succesfully removed, false if property was not found or could not be removed -// -bool CValue::RemoveProperty(const char *inName) -{ - // Check if there are properties at all which can be removed - if (m_pNamedPropertyArray) - { - std::map::iterator it = m_pNamedPropertyArray->find(inName); - if (it != m_pNamedPropertyArray->end()) - { - ((*it).second)->Release(); - m_pNamedPropertyArray->erase(it); - return true; - } - } - - return false; -} - -// -// Get Property Names -// -vector CValue::GetPropertyNames() -{ - vector result; - if (!m_pNamedPropertyArray) return result; - result.reserve(m_pNamedPropertyArray->size()); - - std::map::iterator it; - for (it= m_pNamedPropertyArray->begin(); (it != m_pNamedPropertyArray->end()); it++) - { - result.push_back((*it).first); - } - return result; -} - -// -// Clear all properties -// -void CValue::ClearProperties() -{ - // Check if we have any properties - if (m_pNamedPropertyArray == NULL) - return; - - // Remove all properties - std::map::iterator it; - for (it= m_pNamedPropertyArray->begin();(it != m_pNamedPropertyArray->end()); it++) - { - CValue* tmpval = (*it).second; - //STR_String name = (*it).first; - tmpval->Release(); - } - - // Delete property array - delete m_pNamedPropertyArray; - m_pNamedPropertyArray=NULL; -} - - - -// -// Set all properties' modified flag to -// -void CValue::SetPropertiesModified(bool inModified) -{ - if (!m_pNamedPropertyArray) return; - std::map::iterator it; - - for (it= m_pNamedPropertyArray->begin();(it != m_pNamedPropertyArray->end()); it++) - ((*it).second)->SetModified(inModified); -} - - - -// -// Check if any of the properties in this value have been modified -// -bool CValue::IsAnyPropertyModified() -{ - if (!m_pNamedPropertyArray) return false; - std::map::iterator it; - - for (it= m_pNamedPropertyArray->begin();(it != m_pNamedPropertyArray->end()); it++) - if (((*it).second)->IsModified()) - return true; - - return false; -} - - - -// -// Get property number -// -CValue* CValue::GetProperty(int inIndex) -{ - - int count=0; - CValue* result = NULL; - - if (m_pNamedPropertyArray) - { - std::map::iterator it; - for (it= m_pNamedPropertyArray->begin(); (it != m_pNamedPropertyArray->end()); it++) - { - if (count++ == inIndex) - { - result = (*it).second; - break; - } - } - - } - return result; -} - - - -// -// Get the amount of properties assiocated with this value -// -int CValue::GetPropertyCount() -{ - if (m_pNamedPropertyArray) - return m_pNamedPropertyArray->size(); - else - return 0; -} - - -double* CValue::GetVector3(bool bGetTransformedVec) -{ - assertd(false); // don't get vector from me - return m_sZeroVec;//::sZero; -} - - -/*--------------------------------------------------------------------------------------------------------------------- - Reference Counting ----------------------------------------------------------------------------------------------------------------------*/ - - - -// -// Release a reference to this value (when reference count reaches 0, the value is removed from the heap) -// - - - -// -// Disable reference counting for this value -// -void CValue::DisableRefCount() -{ - assertd(m_refcount == 1); - m_refcount--; - - //debug(gRefCountValue--); -#ifdef DEBUG - //gRefCountValue--; -#endif - m_ValFlags.RefCountDisabled=true; -} - - - -void CValue::ProcessReplica() /* was AddDataToReplica in 2.48 */ -{ - m_refcount = 1; - -#ifdef DEBUG - //gRefCountValue++; -#endif - PyObjectPlus::ProcessReplica(); - - m_ValFlags.RefCountDisabled = false; - - /* copy all props */ - if (m_pNamedPropertyArray) - { - std::map *pOldArray = m_pNamedPropertyArray; - m_pNamedPropertyArray=NULL; - std::map::iterator it; - for (it= pOldArray->begin(); (it != pOldArray->end()); it++) - { - CValue *val = (*it).second->GetReplica(); - SetProperty((*it).first,val); - val->Release(); - } - } -} - - - -int CValue::GetValueType() -{ - return VALUE_NO_TYPE; -} - - - -CValue* CValue::FindIdentifier(const STR_String& identifiername) -{ - - CValue* result = NULL; - - int pos = 0; - // if a dot exists, explode the name into pieces to get the subcontext - if ((pos=identifiername.Find('.'))>=0) - { - const STR_String rightstring = identifiername.Right(identifiername.Length() -1 - pos); - const STR_String leftstring = identifiername.Left(pos); - CValue* tempresult = GetProperty(leftstring); - if (tempresult) - { - result=tempresult->FindIdentifier(rightstring); - } - } else - { - result = GetProperty(identifiername); - if (result) - return result->AddRef(); - } - if (!result) - { - // warning here !!! - result = new CErrorValue(identifiername+" not found"); - } - return result; -} - -#ifdef WITH_PYTHON - -PyAttributeDef CValue::Attributes[] = { - KX_PYATTRIBUTE_RO_FUNCTION("name", CValue, pyattr_get_name), - { NULL } //Sentinel -}; - -PyObject *CValue::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - CValue * self = static_cast (self_v); - return PyUnicode_From_STR_String(self->GetName()); -} - -/** - * There are 2 reasons this could return NULL - * - unsupported type. - * - error converting (overflow). - * - * \param do_type_exception Use to skip raising an exception for unknown types. - */ -CValue *CValue::ConvertPythonToValue(PyObject *pyobj, const bool do_type_exception, const char *error_prefix) -{ - - CValue *vallie; - /* refcounting is broking here! - this crashes anyway, just store a python list for KX_GameObject */ -#if 0 - if (PyList_Check(pyobj)) - { - CListValue* listval = new CListValue(); - bool error = false; - - Py_ssize_t i; - Py_ssize_t numitems = PyList_GET_SIZE(pyobj); - for (i=0;iAdd(listitemval); - } else - { - error = true; - } - } - if (!error) - { - // jippie! could be converted - vallie = listval; - } else - { - // list could not be converted... bad luck - listval->Release(); - } - - } else -#endif - /* note: Boolean check should go before Int check [#34677] */ - if (PyBool_Check(pyobj)) - { - vallie = new CBoolValue( (bool)PyLong_AsLongLong(pyobj) ); - } else - if (PyFloat_Check(pyobj)) - { - const double tval = PyFloat_AsDouble(pyobj); - if (tval > (double)FLT_MAX || tval < (double)-FLT_MAX) { - PyErr_Format(PyExc_OverflowError, "%soverflow converting from float, out of internal range", error_prefix); - vallie = NULL; - } - else { - vallie = new CFloatValue((float)tval); - } - } else - if (PyLong_Check(pyobj)) - { - vallie = new CIntValue( (cInt)PyLong_AsLongLong(pyobj) ); - } else - if (PyUnicode_Check(pyobj)) - { - vallie = new CStringValue(_PyUnicode_AsString(pyobj),""); - } else - if (PyObject_TypeCheck(pyobj, &CValue::Type)) /* Note, don't let these get assigned to GameObject props, must check elsewhere */ - { - vallie = (static_cast(BGE_PROXY_REF(pyobj)))->AddRef(); - } - else { - if (do_type_exception) { - /* return an error value from the caller */ - PyErr_Format(PyExc_TypeError, "%scould convert python value to a game engine property", error_prefix); - } - vallie = NULL; - } - return vallie; - -} - -PyObject *CValue::ConvertKeysToPython(void) -{ - if (m_pNamedPropertyArray) - { - PyObject *pylist= PyList_New(m_pNamedPropertyArray->size()); - Py_ssize_t i= 0; - - std::map::iterator it; - for (it= m_pNamedPropertyArray->begin(); (it != m_pNamedPropertyArray->end()); it++) - { - PyList_SET_ITEM(pylist, i++, PyUnicode_From_STR_String((*it).first)); - } - - return pylist; - } - else { - return PyList_New(0); - } -} - -#endif // WITH_PYTHON - - -/////////////////////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////////////////////// -/* These implementations were moved out of the header */ - -void CValue::SetOwnerExpression(class CExpression* expr) -{ - /* intentionally empty */ -} - -void CValue::SetColorOperator(VALUE_OPERATOR op) -{ - /* intentionally empty */ -} -void CValue::SetValue(CValue* newval) -{ - // no one should get here - assertd(newval->GetNumber() == 10121969); -} diff --git a/source/gameengine/Expressions/intern/VectorValue.cpp b/source/gameengine/Expressions/intern/VectorValue.cpp deleted file mode 100644 index a3d44116317..00000000000 --- a/source/gameengine/Expressions/intern/VectorValue.cpp +++ /dev/null @@ -1,225 +0,0 @@ -/** \file gameengine/Expressions/VectorValue.cpp - * \ingroup expressions - */ -// VectorValue.cpp: implementation of the CVectorValue class. -/* - * Copyright (c) 1996-2000 Erwin Coumans - * - * Permission to use, copy, modify, distribute and sell this software - * and its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and - * that both that copyright notice and this permission notice appear - * in supporting documentation. Erwin Coumans makes no - * representations about the suitability of this software for any - * purpose. It is provided "as is" without express or implied warranty. - * - */ - -#ifdef _MSC_VER -# pragma warning (disable:4786) -#endif - -#include "EXP_Value.h" -#include "EXP_VectorValue.h" -#include "EXP_ErrorValue.h" -//#include "MatrixValue.h" -#include "EXP_VoidValue.h" -#include "EXP_StringValue.h" -//#include "FactoryManager.h" - - - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -CVectorValue::CVectorValue(float x,float y,float z, AllocationTYPE alloctype) -{ - SetCustomFlag1(false);//FancyOutput=false; - - if (alloctype == STACKVALUE) - { - CValue::DisableRefCount(); - }; - - m_vec[KX_X] = m_transformedvec[KX_X] = x; - m_vec[KX_Y] = m_transformedvec[KX_Y] = y; - m_vec[KX_Z] = m_transformedvec[KX_Z] = z; - -} -CVectorValue::CVectorValue(double vec[3], const char *name,AllocationTYPE alloctype) -{ - - SetCustomFlag1(false);//FancyOutput=false; - - m_vec[KX_X] = m_transformedvec[KX_X] = vec[KX_X]; - m_vec[KX_Y] = m_transformedvec[KX_Y] = vec[KX_Y]; - m_vec[KX_Z] = m_transformedvec[KX_Z] = vec[KX_Z]; - - if (alloctype == STACKVALUE) - { - CValue::DisableRefCount(); - - } - - SetName(name); -} - -CVectorValue::CVectorValue(double vec[3], AllocationTYPE alloctype) -{ - - SetCustomFlag1(false);//FancyOutput=false; - - m_vec[KX_X] = m_transformedvec[KX_X] = vec[KX_X]; - m_vec[KX_Y] = m_transformedvec[KX_Y] = vec[KX_Y]; - m_vec[KX_Z] = m_transformedvec[KX_Z] = vec[KX_Z]; - - if (alloctype == STACKVALUE) - { - CValue::DisableRefCount(); - - } - - -} -CVectorValue::~CVectorValue() -{ - -} - -/** - * pre: the type of val is dtype - * ret: a new object containing the result of applying operator op to val and - * this object - */ -CValue* CVectorValue::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val) -{ - CValue *ret = NULL; - - switch (op) { - case VALUE_ADD_OPERATOR: - { - switch (dtype) - { - case VALUE_EMPTY_TYPE: - case VALUE_VECTOR_TYPE: - { - ret = new CVectorValue( - val->GetVector3()[KX_X] + GetVector3()[KX_X], - val->GetVector3()[KX_Y] + GetVector3()[KX_Y], - val->GetVector3()[KX_Z] + GetVector3()[KX_Z], - CValue::HEAPVALUE); - ret->SetName(GetName()); - break; - } - - default: - ret = new CErrorValue(val->GetText() + op2str(op) + GetText()); - } - break; - } - case VALUE_MUL_OPERATOR: - { - switch (dtype) - { - - case VALUE_EMPTY_TYPE: - case VALUE_VECTOR_TYPE: - { - //MT_Vector3 supports 'scaling' by another vector, instead of using general transform, Gino? - //ret = new CVectorValue(val->GetVector3().Scaled(GetVector3()),GetName()); - break; - } - case VALUE_FLOAT_TYPE: - { - ret = new CVectorValue( - val->GetVector3()[KX_X] * GetVector3()[KX_X], - val->GetVector3()[KX_Y] * GetVector3()[KX_Y], - val->GetVector3()[KX_Z] * GetVector3()[KX_Z], - CValue::HEAPVALUE); - ret->SetName(GetName()); - break; - } - - default: - ret = new CErrorValue(val->GetText() + op2str(op) + GetText()); - } - break; - - } - - default: - ret = new CErrorValue(val->GetText() + op2str(op) + GetText()); - } - - - return ret; -} - -double CVectorValue::GetNumber() -{ - return m_vec[KX_X]; -} - - - -int CVectorValue::GetValueType() -{ - return VALUE_VECTOR_TYPE; -} - - - -double* CVectorValue::GetVector3(bool bGetTransformedVec) -{ - if (bGetTransformedVec) - return m_transformedvec; - // else - return m_vec; -} - - - - - -void CVectorValue::SetVector(double newvec[]) -{ - m_vec[KX_X] = m_transformedvec[KX_X] = newvec[KX_X]; - m_vec[KX_Y] = m_transformedvec[KX_Y] = newvec[KX_Y]; - m_vec[KX_Z] = m_transformedvec[KX_Z] = newvec[KX_Z]; - - SetModified(true); -} - - -void CVectorValue::SetValue(CValue *newval) -{ - - double* newvec = ((CVectorValue*)newval)->GetVector3(); - m_vec[KX_X] = m_transformedvec[KX_X] = newvec[KX_X]; - m_vec[KX_Y] = m_transformedvec[KX_Y] = newvec[KX_Y]; - m_vec[KX_Z] = m_transformedvec[KX_Z] = newvec[KX_Z]; - - SetModified(true); -} - -static const STR_String gstrVectorStr=STR_String(); -const STR_String & CVectorValue::GetText() -{ - assertd(false); - return gstrVectorStr; -} - -CValue* CVectorValue::GetReplica() -{ - CVectorValue* replica = new CVectorValue(*this); - replica->ProcessReplica(); - return replica; -}; - -#if 0 -void CVectorValue::Transform(rcMatrix4x4 mat) -{ - m_transformedvec = mat*m_vec; -} -#endif diff --git a/source/gameengine/GameLogic/CMakeLists.txt b/source/gameengine/GameLogic/CMakeLists.txt deleted file mode 100644 index b9eec74f6f4..00000000000 --- a/source/gameengine/GameLogic/CMakeLists.txt +++ /dev/null @@ -1,147 +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 - ../Rasterizer - ../SceneGraph - ../../blender/blenlib - ../../../intern/container - ../../../intern/string - ../../../intern/ghost -) - -set(INC_SYS - ../../../intern/moto/include -) - -set(SRC - SCA_2DFilterActuator.cpp - SCA_ANDController.cpp - SCA_ActuatorEventManager.cpp - SCA_ActuatorSensor.cpp - SCA_AlwaysEventManager.cpp - SCA_AlwaysSensor.cpp - SCA_BasicEventManager.cpp - SCA_DelaySensor.cpp - SCA_EventManager.cpp - SCA_ExpressionController.cpp - SCA_IActuator.cpp - SCA_IController.cpp - SCA_IInputDevice.cpp - SCA_ILogicBrick.cpp - SCA_IObject.cpp - SCA_IScene.cpp - SCA_ISensor.cpp - SCA_JoystickManager.cpp - SCA_JoystickSensor.cpp - SCA_KeyboardManager.cpp - SCA_KeyboardSensor.cpp - SCA_LogicManager.cpp - SCA_MouseManager.cpp - SCA_MouseSensor.cpp - SCA_NANDController.cpp - SCA_NORController.cpp - SCA_ORController.cpp - SCA_PropertyActuator.cpp - SCA_PropertyEventManager.cpp - SCA_PropertySensor.cpp - SCA_PythonController.cpp - SCA_PythonJoystick.cpp - SCA_PythonKeyboard.cpp - SCA_PythonMouse.cpp - SCA_RandomActuator.cpp - SCA_RandomEventManager.cpp - SCA_RandomNumberGenerator.cpp - SCA_RandomSensor.cpp - SCA_TimeEventManager.cpp - SCA_XNORController.cpp - SCA_XORController.cpp - Joystick/SCA_Joystick.cpp - Joystick/SCA_JoystickEvents.cpp - - SCA_2DFilterActuator.h - SCA_ANDController.h - SCA_ActuatorEventManager.h - SCA_ActuatorSensor.h - SCA_AlwaysEventManager.h - SCA_AlwaysSensor.h - SCA_BasicEventManager.h - SCA_DelaySensor.h - SCA_EventManager.h - SCA_ExpressionController.h - SCA_IActuator.h - SCA_IController.h - SCA_IInputDevice.h - SCA_ILogicBrick.h - SCA_IObject.h - SCA_IScene.h - SCA_ISensor.h - SCA_JoystickManager.h - SCA_JoystickSensor.h - SCA_KeyboardManager.h - SCA_KeyboardSensor.h - SCA_LogicManager.h - SCA_MouseManager.h - SCA_MouseSensor.h - SCA_NANDController.h - SCA_NORController.h - SCA_ORController.h - SCA_PropertyActuator.h - SCA_PropertyEventManager.h - SCA_PropertySensor.h - SCA_PythonController.h - SCA_PythonJoystick.h - SCA_PythonKeyboard.h - SCA_PythonMouse.h - SCA_RandomActuator.h - SCA_RandomEventManager.h - SCA_RandomNumberGenerator.h - SCA_RandomSensor.h - SCA_TimeEventManager.h - SCA_XNORController.h - SCA_XORController.h - Joystick/SCA_Joystick.h - Joystick/SCA_JoystickDefines.h - Joystick/SCA_JoystickPrivate.h -) - -if(WITH_SDL) - list(APPEND INC_SYS - ${SDL_INCLUDE_DIR} - ) - - add_definitions(-DWITH_SDL) - - if(WITH_GHOST_SDL) - add_definitions(-DWITH_GHOST_SDL) - endif() - if(WITH_SDL_DYNLOAD) - add_definitions(-DWITH_SDL_DYNLOAD) - endif() -endif() - -blender_add_lib(ge_logic "${SRC}" "${INC}" "${INC_SYS}") diff --git a/source/gameengine/GameLogic/Joystick/SCA_Joystick.cpp b/source/gameengine/GameLogic/Joystick/SCA_Joystick.cpp deleted file mode 100644 index 9f532527a80..00000000000 --- a/source/gameengine/GameLogic/Joystick/SCA_Joystick.cpp +++ /dev/null @@ -1,382 +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): snailrose. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/GameLogic/Joystick/SCA_Joystick.cpp - * \ingroup gamelogic - */ - -#include -#include - -#include "SCA_Joystick.h" -#include "SCA_JoystickPrivate.h" - -#include "BLI_path_util.h" - -#ifdef WITH_SDL -# ifdef WITH_SDL_DYNLOAD -# define SDL_CHECK(x) ((x) != (void *)0) -# else -# define SDL_CHECK(x) true -# endif -#endif - -SCA_Joystick::SCA_Joystick(short int index) - : - m_joyindex(index), - m_prec(3200), - m_axismax(-1), - m_buttonmax(-1), - m_hatmax(-1), - m_isinit(0), - m_istrig_axis(0), - m_istrig_button(0), - m_istrig_hat(0) -{ - for (int i=0; i < JOYAXIS_MAX; i++) - m_axis_array[i] = 0; - - for (int i=0; i < JOYHAT_MAX; i++) - m_hat_array[i] = 0; - -#ifdef WITH_SDL - m_private = new PrivateData(); -#endif -} - - -SCA_Joystick::~SCA_Joystick() - -{ -#ifdef WITH_SDL - delete m_private; -#endif -} - -SCA_Joystick *SCA_Joystick::m_instance[JOYINDEX_MAX]; -int SCA_Joystick::m_joynum = 0; -int SCA_Joystick::m_refCount = 0; - -SCA_Joystick *SCA_Joystick::GetInstance( short int joyindex ) -{ -#ifndef WITH_SDL - return NULL; -#else /* WITH_SDL */ - if (!SDL_CHECK(SDL_InitSubSystem)) { - return NULL; - } - if (joyindex < 0 || joyindex >= JOYINDEX_MAX) { - JOYSTICK_ECHO("Error-invalid joystick index: " << joyindex); - return NULL; - } - - if (m_refCount == 0) - { - int i; - - /* The video subsystem is required for joystick input to work. However, - * when GHOST is running under SDL, video is initialized elsewhere. We - * also need to set the videodriver to dummy, and do it here to avoid - * interfering with addons that may use SDL too. - * - * We also init SDL once only. */ -# ifdef WITH_GHOST_SDL - int success = (SDL_InitSubSystem(SDL_INIT_JOYSTICK) != -1 ); -# else - /* set and restore environment variable */ - char *videodriver = getenv("SDL_VIDEODRIVER"); - BLI_setenv("SDL_VIDEODRIVER", "dummy"); - -#if SDL_VERSION_ATLEAST(2, 0, 0) - int success = (SDL_InitSubSystem(SDL_INIT_JOYSTICK) != -1 ); -#else - int success = (SDL_InitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_VIDEO) != -1 ); -#endif - - BLI_setenv("SDL_VIDEODRIVER", videodriver); -# endif - - if (!success) { - JOYSTICK_ECHO("Error-Initializing-SDL: " << SDL_GetError()); - return NULL; - } - - m_joynum = SDL_NumJoysticks(); - - for (i = 0; i < m_joynum; i++) { - m_instance[i] = new SCA_Joystick(i); - m_instance[i]->CreateJoystickDevice(); - } - m_refCount = 1; - } - else - { - m_refCount++; - } - return m_instance[joyindex]; -#endif /* WITH_SDL */ -} - -void SCA_Joystick::ReleaseInstance() -{ - if (--m_refCount == 0) - { -#ifdef WITH_SDL - if (!SDL_CHECK(SDL_QuitSubSystem)) { - return; - } - for (int i = 0; i < m_joynum; i++) { - if (m_instance[i]) { - m_instance[i]->DestroyJoystickDevice(); - delete m_instance[i]; - } - m_instance[i] = NULL; - } - - /* The video subsystem is required for joystick input to work. However, - * when GHOST is running under SDL, video is freed elsewhere. - * Do this once only. */ -#if SDL_VERSION_ATLEAST(2, 0, 0) - SDL_QuitSubSystem(SDL_INIT_JOYSTICK); -#else - SDL_QuitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_VIDEO); -#endif -#endif /* WITH_SDL */ - } -} - -void SCA_Joystick::cSetPrecision(int val) -{ - m_prec = val; -} - - -bool SCA_Joystick::aAxisPairIsPositive(int axis) -{ - return (pAxisTest(axis) > m_prec) ? true:false; -} - -bool SCA_Joystick::aAxisPairDirectionIsPositive(int axis, int dir) -{ - - int res; - - if (dir==JOYAXIS_UP || dir==JOYAXIS_DOWN) - res = pGetAxis(axis, 1); - else /* JOYAXIS_LEFT || JOYAXIS_RIGHT */ - res = pGetAxis(axis, 0); - - if (dir==JOYAXIS_DOWN || dir==JOYAXIS_RIGHT) - return (res > m_prec) ? true : false; - else /* JOYAXIS_UP || JOYAXIS_LEFT */ - return (res < -m_prec) ? true : false; -} - -bool SCA_Joystick::aAxisIsPositive(int axis_single) -{ - return abs(m_axis_array[axis_single]) > m_prec ? true:false; -} - -bool SCA_Joystick::aAnyButtonPressIsPositive(void) -{ -#ifdef WITH_SDL - if (!SDL_CHECK(SDL_JoystickGetButton)) { - return false; - } - /* this is needed for the "all events" option - * so we know if there are no buttons pressed */ - for (int i=0; im_joystick, i)) - return true; -#endif - return false; -} - -bool SCA_Joystick::aButtonPressIsPositive(int button) -{ -#ifndef WITH_SDL - return false; -#else - bool result; - result = SDL_CHECK(SDL_JoystickGetButton) && SDL_JoystickGetButton(m_private->m_joystick, button); - return result; -#endif -} - - -bool SCA_Joystick::aButtonReleaseIsPositive(int button) -{ -#ifndef WITH_SDL - return false; -#else - bool result; - result = !(SDL_CHECK(SDL_JoystickGetButton) && SDL_JoystickGetButton(m_private->m_joystick, button)); - return result; -#endif -} - - -bool SCA_Joystick::aHatIsPositive(int hatnum, int dir) -{ - return (GetHat(hatnum)==dir) ? true : false; -} - -int SCA_Joystick::GetNumberOfAxes() -{ - return m_axismax; -} - - -int SCA_Joystick::GetNumberOfButtons() -{ - return m_buttonmax; -} - - -int SCA_Joystick::GetNumberOfHats() -{ - return m_hatmax; -} - -bool SCA_Joystick::CreateJoystickDevice(void) -{ -#ifndef WITH_SDL - m_isinit = true; - m_axismax = m_buttonmax = m_hatmax = 0; - return false; -#else /* WITH_SDL */ - if (m_isinit == false && SDL_CHECK(SDL_JoystickOpen)) { - if (m_joyindex>=m_joynum) { - /* don't print a message, because this is done anyway */ - //JOYSTICK_ECHO("Joystick-Error: " << SDL_NumJoysticks() << " avaiable joystick(s)"); - - /* Need this so python args can return empty lists */ - m_axismax = m_buttonmax = m_hatmax = 0; - return false; - } - - m_private->m_joystick = SDL_JoystickOpen(m_joyindex); - SDL_JoystickEventState(SDL_ENABLE); - m_isinit = true; - - JOYSTICK_ECHO("Joystick " << m_joyindex << " initialized"); - - /* must run after being initialized */ - m_axismax = SDL_JoystickNumAxes(m_private->m_joystick); - m_buttonmax = SDL_JoystickNumButtons(m_private->m_joystick); - m_hatmax = SDL_JoystickNumHats(m_private->m_joystick); - - if (m_axismax > JOYAXIS_MAX) m_axismax = JOYAXIS_MAX; /* very unlikely */ - else if (m_axismax < 0) m_axismax = 0; - - if (m_hatmax > JOYHAT_MAX) m_hatmax = JOYHAT_MAX; /* very unlikely */ - else if (m_hatmax < 0) m_hatmax = 0; - - if (m_buttonmax < 0) m_buttonmax = 0; - - } - return true; -#endif /* WITH_SDL */ -} - - -void SCA_Joystick::DestroyJoystickDevice(void) -{ -#ifdef WITH_SDL - if (m_isinit) { -#if SDL_VERSION_ATLEAST(2, 0, 0) - if (SDL_CHECK(SDL_JoystickGetAttached) && SDL_JoystickGetAttached(m_private->m_joystick)) -#else - if (SDL_CHECK(SDL_JoystickOpened) && SDL_JoystickOpened(m_joyindex)) -#endif - { - JOYSTICK_ECHO("Closing-joystick " << m_joyindex); - SDL_JoystickClose(m_private->m_joystick); - } - m_isinit = false; - } -#endif /* WITH_SDL */ -} - -int SCA_Joystick::Connected(void) -{ -#ifdef WITH_SDL - if (m_isinit && -#if SDL_VERSION_ATLEAST(2, 0, 0) - SDL_CHECK(SDL_JoystickGetAttached) && SDL_JoystickGetAttached(m_private->m_joystick) -#else - SDL_CHECK(SDL_JoystickOpened) && SDL_JoystickOpened(m_joyindex) -#endif - ) - { - return 1; - } -#endif - return 0; -} - -int SCA_Joystick::pGetAxis(int axisnum, int udlr) -{ -#ifdef WITH_SDL - return m_axis_array[(axisnum*2)+udlr]; -#endif - return 0; -} - -int SCA_Joystick::pAxisTest(int axisnum) -{ -#ifdef WITH_SDL - /* Use ints instead of shorts here to avoid problems when we get -32768. - * When we take the negative of that later, we should get 32768, which is greater - * than what a short can hold. In other words, abs(MIN_SHORT) > MAX_SHRT. */ - int i1 = m_axis_array[(axisnum * 2)]; - int i2 = m_axis_array[(axisnum * 2) + 1]; - - /* long winded way to do: - * return max_ff(absf(i1), absf(i2)) - * ...avoid abs from math.h */ - if (i1 < 0) i1 = -i1; - if (i2 < 0) i2 = -i2; - if (i1 m_joystick) : ""; -#else - return (SDL_CHECK(SDL_JoystickName)) ? SDL_JoystickName(m_joyindex) : ""; -#endif -#else /* WITH_SDL */ - return ""; -#endif /* WITH_SDL */ -} diff --git a/source/gameengine/GameLogic/Joystick/SCA_Joystick.h b/source/gameengine/GameLogic/Joystick/SCA_Joystick.h deleted file mode 100644 index c9221753d45..00000000000 --- a/source/gameengine/GameLogic/Joystick/SCA_Joystick.h +++ /dev/null @@ -1,214 +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): snailrose. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file SCA_Joystick.h - * \ingroup gamelogic - */ - -#ifndef __SCA_JOYSTICK_H__ -#define __SCA_JOYSTICK_H__ - -#include "SCA_JoystickDefines.h" -#ifdef WITH_SDL -/* SDL force defines __SSE__ and __SSE2__ flags, which generates warnings - * because we pass those defines via command line as well. For until there's - * proper ifndef added to SDL headers we ignore the redefinition warning. - */ -# ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable : 4005) -# endif -# include "SDL.h" -# ifdef _MSC_VER -# pragma warning(pop) -# endif -#endif - -/** - * Basic Joystick class - * I will make this class a singleton because there should be only one joystick - * even if there are more than one scene using it and count how many scene are using it. - * The underlying joystick should only be removed when the last scene is removed - */ - -class SCA_Joystick - -{ - static SCA_Joystick *m_instance[JOYINDEX_MAX]; - static int m_joynum; - static int m_refCount; - - class PrivateData; -#ifdef WITH_SDL - PrivateData *m_private; -#endif - int m_joyindex; - - /** - *support for JOYAXIS_MAX axes (in pairs) - */ - int m_axis_array[JOYAXIS_MAX]; - - /** - *support for JOYHAT_MAX hats (each is a direction) - */ - int m_hat_array[JOYHAT_MAX]; - - /** - * Precision or range of the axes - */ - int m_prec; - - /** - * max # of buttons avail - */ - - int m_axismax; - int m_buttonmax; - int m_hatmax; - - /** is the joystick initialized ?*/ - bool m_isinit; - - - /** is triggered for each event type */ - bool m_istrig_axis; - bool m_istrig_button; - bool m_istrig_hat; - -#ifdef WITH_SDL - /** - * event callbacks - */ - void OnAxisMotion(SDL_Event *sdl_event); - void OnHatMotion(SDL_Event *sdl_event); - void OnButtonUp(SDL_Event *sdl_event); - void OnButtonDown(SDL_Event *sdl_event); - void OnNothing(SDL_Event *sdl_event); -#if 0 /* not used yet */ - void OnBallMotion(SDL_Event *sdl_event) {} -#endif - -#endif /* WITH_SDL */ - /** - * Open the joystick - */ - bool CreateJoystickDevice(void); - - /** - * Close the joystick - */ - void DestroyJoystickDevice(void); - - /** - * fills the axis member values - */ - void pFillButtons(void); - - /** - * returns m_axis_array - */ - - int pAxisTest(int axisnum); - /** - * returns m_axis_array - */ - int pGetAxis(int axisnum, int udlr); - - SCA_Joystick(short int index); - - ~SCA_Joystick(); - -public: - - static SCA_Joystick *GetInstance(short int joyindex); - static void HandleEvents(void); - void ReleaseInstance(); - - - /* - */ - bool aAxisPairIsPositive(int axis); - bool aAxisPairDirectionIsPositive(int axis, int dir); /* function assumes joysticks are in axis pairs */ - bool aAxisIsPositive(int axis_single); /* check a single axis only */ - - bool aAnyButtonPressIsPositive(void); - bool aButtonPressIsPositive(int button); - bool aButtonReleaseIsPositive(int button); - bool aHatIsPositive(int hatnum, int dir); - - /** - * precision is default '3200' which is overridden by input - */ - - void cSetPrecision(int val); - - int GetAxisPosition(int index) { - return m_axis_array[index]; - } - - int GetHat(int index) { - return m_hat_array[index]; - } - - int GetThreshold(void) { - return m_prec; - } - - bool IsTrigAxis(void) { - return m_istrig_axis; - } - - bool IsTrigButton(void) { - return m_istrig_button; - } - - bool IsTrigHat(void) { - return m_istrig_hat; - } - - /** - * returns the # of... - */ - - int GetNumberOfAxes(void); - int GetNumberOfButtons(void); - int GetNumberOfHats(void); - - /** - * Test if the joystick is connected - */ - int Connected(void); - - /** - * Name of the joytsick - */ - const char *GetName(); -}; - -#endif - diff --git a/source/gameengine/GameLogic/Joystick/SCA_JoystickDefines.h b/source/gameengine/GameLogic/Joystick/SCA_JoystickDefines.h deleted file mode 100644 index 566e5567507..00000000000 --- a/source/gameengine/GameLogic/Joystick/SCA_JoystickDefines.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): snailrose. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file SCA_JoystickDefines.h - * \ingroup gamelogic - */ - -#ifndef __SCA_JOYSTICKDEFINES_H__ -#define __SCA_JOYSTICKDEFINES_H__ - -#ifdef main -#undef main -#endif - -#ifndef DEBUG -# define JOYSTICK_ECHO(x) -#else -# include -# define JOYSTICK_ECHO(x) std::cout << x << std::endl; -#endif - -#define JOYINDEX_MAX 8 -#define JOYAXIS_MAX 16 -#define JOYBUT_MAX 18 -#define JOYHAT_MAX 4 - -#define JOYAXIS_RIGHT 0 -#define JOYAXIS_UP 1 -#define JOYAXIS_DOWN 3 -#define JOYAXIS_LEFT 2 - -#endif diff --git a/source/gameengine/GameLogic/Joystick/SCA_JoystickEvents.cpp b/source/gameengine/GameLogic/Joystick/SCA_JoystickEvents.cpp deleted file mode 100644 index 1dee1de9de2..00000000000 --- a/source/gameengine/GameLogic/Joystick/SCA_JoystickEvents.cpp +++ /dev/null @@ -1,137 +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): snailrose. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/GameLogic/Joystick/SCA_JoystickEvents.cpp - * \ingroup gamelogic - */ - -#include "SCA_Joystick.h" -#include "SCA_JoystickPrivate.h" - -#ifdef _MSC_VER -# include /* printf */ -#endif - -#ifdef WITH_SDL -void SCA_Joystick::OnAxisMotion(SDL_Event* sdl_event) -{ - if (sdl_event->jaxis.axis >= JOYAXIS_MAX) - return; - - m_axis_array[sdl_event->jaxis.axis] = sdl_event->jaxis.value; - m_istrig_axis = 1; -} - -/* See notes below in the event loop */ -void SCA_Joystick::OnHatMotion(SDL_Event* sdl_event) -{ - if (sdl_event->jhat.hat >= JOYHAT_MAX) - return; - - m_hat_array[sdl_event->jhat.hat] = sdl_event->jhat.value; - m_istrig_hat = 1; -} - -/* See notes below in the event loop */ -void SCA_Joystick::OnButtonUp(SDL_Event* sdl_event) -{ - m_istrig_button = 1; -} - - -void SCA_Joystick::OnButtonDown(SDL_Event* sdl_event) -{ - //if (sdl_event->jbutton.button > m_buttonmax) /* unsigned int so always above 0 */ - // return; - // sdl_event->jbutton.button; - - m_istrig_button = 1; -} - - -void SCA_Joystick::OnNothing(SDL_Event* sdl_event) -{ - m_istrig_axis = m_istrig_button = m_istrig_hat = 0; -} - -void SCA_Joystick::HandleEvents(void) -{ - SDL_Event sdl_event; - -#ifdef WITH_SDL_DYNLOAD - if (SDL_PollEvent == (void*)0) { - return; - } -#endif - - int i; - for (i=0; iOnNothing(&sdl_event); - } - - while (SDL_PollEvent(&sdl_event)) { - /* Note! m_instance[sdl_event.jaxis.which] - * will segfault if over JOYINDEX_MAX, not too nice but what are the chances? */ - - /* Note!, with buttons, this wont care which button is pressed, - * only to set 'm_istrig_button', actual pressed buttons are detected by SDL_JoystickGetButton */ - - /* Note!, if you manage to press and release a button within 1 logic tick - * it wont work as it should */ - - switch (sdl_event.type) { - case SDL_JOYAXISMOTION: - SCA_Joystick::m_instance[sdl_event.jaxis.which]->OnAxisMotion(&sdl_event); - break; - case SDL_JOYHATMOTION: - SCA_Joystick::m_instance[sdl_event.jhat.which]->OnHatMotion(&sdl_event); - break; - case SDL_JOYBUTTONUP: - SCA_Joystick::m_instance[sdl_event.jbutton.which]->OnButtonUp(&sdl_event); - break; - case SDL_JOYBUTTONDOWN: - SCA_Joystick::m_instance[sdl_event.jbutton.which]->OnButtonDown(&sdl_event); - break; -#if 0 /* Not used yet */ - case SDL_JOYBALLMOTION: - SCA_Joystick::m_instance[sdl_event.jball.which]->OnBallMotion(&sdl_event); - break; -#endif -#if SDL_VERSION_ATLEAST(2, 0, 0) - case SDL_JOYDEVICEADDED: - case SDL_JOYDEVICEREMOVED: - /* pass */ - break; -#endif - default: - printf("SCA_Joystick::HandleEvents, Unknown SDL event (%d), this should not happen\n", sdl_event.type); - break; - } - } -} -#endif /* WITH_SDL */ diff --git a/source/gameengine/GameLogic/Joystick/SCA_JoystickPrivate.h b/source/gameengine/GameLogic/Joystick/SCA_JoystickPrivate.h deleted file mode 100644 index 472a7353190..00000000000 --- a/source/gameengine/GameLogic/Joystick/SCA_JoystickPrivate.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): snailrose. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file SCA_JoystickPrivate.h - * \ingroup gamelogic - */ - -#ifndef __SCA_JOYSTICKPRIVATE_H__ -#define __SCA_JOYSTICKPRIVATE_H__ -#include "SCA_Joystick.h" - -#ifdef WITH_SDL -class SCA_Joystick::PrivateData -{ -public: - /* - * The Joystick - */ - SDL_Joystick* m_joystick; - - PrivateData() - : m_joystick(NULL) - { - } -}; -#endif /* WITH_SDL */ - -#endif diff --git a/source/gameengine/GameLogic/SCA_2DFilterActuator.cpp b/source/gameengine/GameLogic/SCA_2DFilterActuator.cpp deleted file mode 100644 index 6a87d3ccb98..00000000000 --- a/source/gameengine/GameLogic/SCA_2DFilterActuator.cpp +++ /dev/null @@ -1,153 +0,0 @@ -/* - * SCA_2DFilterActuator.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. - * - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/GameLogic/SCA_2DFilterActuator.cpp - * \ingroup gamelogic - */ - - -#include - -#include "SCA_IActuator.h" -#include "SCA_2DFilterActuator.h" - -#include - -SCA_2DFilterActuator::~SCA_2DFilterActuator() -{ -} - -SCA_2DFilterActuator::SCA_2DFilterActuator( - SCA_IObject *gameobj, - RAS_2DFilterManager::RAS_2DFILTER_MODE type, - short flag, - float float_arg, - int int_arg, - RAS_IRasterizer* rasterizer, - SCA_IScene* scene) - : SCA_IActuator(gameobj, KX_ACT_2DFILTER), - m_type(type), - m_disableMotionBlur(flag), - m_float_arg(float_arg), - m_int_arg(int_arg), - m_rasterizer(rasterizer), - m_scene(scene) -{ - m_gameobj = NULL; - if (gameobj) { - m_propNames = gameobj->GetPropertyNames(); - m_gameobj = gameobj; - } -} - - -CValue* SCA_2DFilterActuator::GetReplica() -{ - SCA_2DFilterActuator* replica = new SCA_2DFilterActuator(*this); - replica->ProcessReplica(); - return replica; -} - - -bool SCA_2DFilterActuator::Update() -{ - bool bNegativeEvent = IsNegativeEvent(); - RemoveAllEvents(); - - - if (bNegativeEvent) - return false; // do nothing on negative events - - if ( m_type == RAS_2DFilterManager::RAS_2DFILTER_MOTIONBLUR ) - { - if (!m_disableMotionBlur) - m_rasterizer->EnableMotionBlur(m_float_arg); - else - m_rasterizer->DisableMotionBlur(); - - return false; - } - else if (m_type < RAS_2DFilterManager::RAS_2DFILTER_NUMBER_OF_FILTERS) - { - m_scene->Update2DFilter(m_propNames, m_gameobj, m_type, m_int_arg, m_shaderText); - } - // once the filter is in place, no need to update it again => disable the actuator - return false; -} - - -void SCA_2DFilterActuator::SetScene(SCA_IScene *scene) -{ - m_scene = scene; -} - -void SCA_2DFilterActuator::SetShaderText(const char *text) -{ - m_shaderText = text; -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject SCA_2DFilterActuator::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "SCA_2DFilterActuator", - 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 SCA_2DFilterActuator::Methods[] = { - /* add python functions to deal with m_msg... */ - {NULL,NULL} -}; - -PyAttributeDef SCA_2DFilterActuator::Attributes[] = { - KX_PYATTRIBUTE_STRING_RW("shaderText", 0, 64000, false, SCA_2DFilterActuator, m_shaderText), - KX_PYATTRIBUTE_SHORT_RW("disableMotionBlur", 0, 1, true, SCA_2DFilterActuator, m_disableMotionBlur), - KX_PYATTRIBUTE_ENUM_RW("mode",RAS_2DFilterManager::RAS_2DFILTER_ENABLED,RAS_2DFilterManager::RAS_2DFILTER_NUMBER_OF_FILTERS,false,SCA_2DFilterActuator,m_type), - KX_PYATTRIBUTE_INT_RW("passNumber", 0, 100, true, SCA_2DFilterActuator, m_int_arg), - KX_PYATTRIBUTE_FLOAT_RW("value", 0.0, 100.0, SCA_2DFilterActuator, m_float_arg), - { NULL } //Sentinel -}; - -#endif diff --git a/source/gameengine/GameLogic/SCA_2DFilterActuator.h b/source/gameengine/GameLogic/SCA_2DFilterActuator.h deleted file mode 100644 index 4635a8ad9f8..00000000000 --- a/source/gameengine/GameLogic/SCA_2DFilterActuator.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - * SCA_2DFilterActuator.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. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file SCA_2DFilterActuator.h - * \ingroup gamelogic - */ - -#ifndef __SCA_2DFILTERACTUATOR_H__ -#define __SCA_2DFILTERACTUATOR_H__ - -#include "RAS_IRasterizer.h" -#include "SCA_IActuator.h" -#include "SCA_IScene.h" - -class SCA_2DFilterActuator : public SCA_IActuator -{ - Py_Header - -private: - vector m_propNames; - RAS_2DFilterManager::RAS_2DFILTER_MODE m_type; - short m_disableMotionBlur; - float m_float_arg; - int m_int_arg; - STR_String m_shaderText; - RAS_IRasterizer* m_rasterizer; - SCA_IScene* m_scene; - -public: - - SCA_2DFilterActuator( - class SCA_IObject* gameobj, - RAS_2DFilterManager::RAS_2DFILTER_MODE type, - short flag, - float float_arg, - int int_arg, - RAS_IRasterizer* rasterizer, - SCA_IScene* scene); - - void SetShaderText(const char *text); - virtual ~SCA_2DFilterActuator(); - virtual bool Update(); - - void SetScene(SCA_IScene *scene); - - virtual CValue* GetReplica(); -}; -#endif diff --git a/source/gameengine/GameLogic/SCA_ANDController.cpp b/source/gameengine/GameLogic/SCA_ANDController.cpp deleted file mode 100644 index 2cb7406779c..00000000000 --- a/source/gameengine/GameLogic/SCA_ANDController.cpp +++ /dev/null @@ -1,131 +0,0 @@ -/* - * 'And' together all inputs - * - * - * ***** 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/GameLogic/SCA_ANDController.cpp - * \ingroup gamelogic - */ - - -#include "SCA_ANDController.h" -#include "SCA_ISensor.h" -#include "SCA_LogicManager.h" -#include "EXP_BoolValue.h" - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -SCA_ANDController::SCA_ANDController(SCA_IObject* gameobj) - : - SCA_IController(gameobj) -{ -} - - - -SCA_ANDController::~SCA_ANDController() -{ -} - - - -void SCA_ANDController::Trigger(SCA_LogicManager* logicmgr) -{ - - bool sensorresult = true; - - for (vector::const_iterator is=m_linkedsensors.begin(); - !(is==m_linkedsensors.end());is++) - { - SCA_ISensor* sensor = *is; - if (!sensor->GetState()) - { - sensorresult = false; - break; - } - } - - for (vector::const_iterator i=m_linkedactuators.begin(); - !(i==m_linkedactuators.end());i++) - { - SCA_IActuator* actua = *i; - logicmgr->AddActiveActuator(actua,sensorresult); - } -} - - - -CValue* SCA_ANDController::GetReplica() -{ - CValue* replica = new SCA_ANDController(*this); - // this will copy properties and so on... - replica->ProcessReplica(); - - return replica; -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject SCA_ANDController::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "SCA_ANDController", - 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_IController::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef SCA_ANDController::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef SCA_ANDController::Attributes[] = { - { NULL } //Sentinel -}; -#endif // WITH_PYTHON -/* eof */ diff --git a/source/gameengine/GameLogic/SCA_ANDController.h b/source/gameengine/GameLogic/SCA_ANDController.h deleted file mode 100644 index ff152d6d2fb..00000000000 --- a/source/gameengine/GameLogic/SCA_ANDController.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * SCA_ANDController.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 SCA_ANDController.h - * \ingroup gamelogic - */ - -#ifndef __SCA_ANDCONTROLLER_H__ -#define __SCA_ANDCONTROLLER_H__ - -#include "SCA_IController.h" - -class SCA_ANDController : public SCA_IController -{ - Py_Header - //virtual void Trigger(class SCA_LogicManager* logicmgr); -public: - SCA_ANDController(SCA_IObject* gameobj); - virtual ~SCA_ANDController(); - virtual CValue* GetReplica(); - virtual void Trigger(SCA_LogicManager* logicmgr); -}; - -#endif /* __SCA_ANDCONTROLLER_H__ */ diff --git a/source/gameengine/GameLogic/SCA_ActuatorEventManager.cpp b/source/gameengine/GameLogic/SCA_ActuatorEventManager.cpp deleted file mode 100644 index fcb236f0913..00000000000 --- a/source/gameengine/GameLogic/SCA_ActuatorEventManager.cpp +++ /dev/null @@ -1,68 +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/GameLogic/SCA_ActuatorEventManager.cpp - * \ingroup gamelogic - */ - - -#include "SCA_ISensor.h" -#include "SCA_ActuatorEventManager.h" -#include "SCA_ActuatorSensor.h" - - -SCA_ActuatorEventManager::SCA_ActuatorEventManager(class SCA_LogicManager* logicmgr) - : SCA_EventManager(logicmgr, ACTUATOR_EVENTMGR) -{ -} - - - -SCA_ActuatorEventManager::~SCA_ActuatorEventManager() -{ - -} - -void SCA_ActuatorEventManager::NextFrame() -{ - // check for changed actuator - SG_DList::iterator it(m_sensors); - for (it.begin();!it.end();++it) - { - (*it)->Activate(m_logicmgr); - } -} - -void SCA_ActuatorEventManager::UpdateFrame() -{ - // update the state of actuator before executing them - SG_DList::iterator it(m_sensors); - for (it.begin();!it.end();++it) - { - (*it)->Update(); - } -} diff --git a/source/gameengine/GameLogic/SCA_ActuatorEventManager.h b/source/gameengine/GameLogic/SCA_ActuatorEventManager.h deleted file mode 100644 index 997be1145db..00000000000 --- a/source/gameengine/GameLogic/SCA_ActuatorEventManager.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 SCA_ActuatorEventManager.h - * \ingroup gamelogic - */ - -#ifndef __SCA_ACTUATOREVENTMANAGER_H__ -#define __SCA_ACTUATOREVENTMANAGER_H__ - -#include "SCA_EventManager.h" - -#include - -using namespace std; - -class SCA_ActuatorEventManager : public SCA_EventManager -{ -public: - SCA_ActuatorEventManager(class SCA_LogicManager* logicmgr); - virtual ~SCA_ActuatorEventManager(); - virtual void NextFrame(); - virtual void UpdateFrame(); - //SCA_LogicManager* GetLogicManager() { return m_logicmgr;} - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_ActuatorEventManager") -#endif -}; - -#endif /* __SCA_ACTUATOREVENTMANAGER_H__ */ diff --git a/source/gameengine/GameLogic/SCA_ActuatorSensor.cpp b/source/gameengine/GameLogic/SCA_ActuatorSensor.cpp deleted file mode 100644 index 8b7702228ce..00000000000 --- a/source/gameengine/GameLogic/SCA_ActuatorSensor.cpp +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Actuator 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/GameLogic/SCA_ActuatorSensor.cpp - * \ingroup gamelogic - */ - - -#include - -#include -#include "SCA_ActuatorSensor.h" -#include "SCA_EventManager.h" -#include "SCA_LogicManager.h" - -SCA_ActuatorSensor::SCA_ActuatorSensor(SCA_EventManager* eventmgr, - SCA_IObject* gameobj, - const STR_String& actname) - : SCA_ISensor(gameobj,eventmgr), - m_checkactname(actname) -{ - m_actuator = GetParent()->FindActuator(m_checkactname); - Init(); -} - -void SCA_ActuatorSensor::Init() -{ - m_lastresult = m_invert?true:false; - m_midresult = m_lastresult; - m_reset = true; -} - -CValue* SCA_ActuatorSensor::GetReplica() -{ - SCA_ActuatorSensor* replica = new SCA_ActuatorSensor(*this); - // m_range_expr must be recalculated on replica! - replica->ProcessReplica(); - replica->Init(); - - return replica; -} - -void SCA_ActuatorSensor::ReParent(SCA_IObject* parent) -{ - m_actuator = parent->FindActuator(m_checkactname); - SCA_ISensor::ReParent(parent); -} - -bool SCA_ActuatorSensor::IsPositiveTrigger() -{ - bool result = m_lastresult; - if (m_invert) - result = !result; - - return result; -} - - - -SCA_ActuatorSensor::~SCA_ActuatorSensor() -{ -} - - - -bool SCA_ActuatorSensor::Evaluate() -{ - if (m_actuator) - { - bool result = m_actuator->IsActive(); - bool reset = m_reset && m_level; - - m_reset = false; - if (m_lastresult != result || m_midresult != result) - { - m_lastresult = m_midresult = result; - return true; - } - return (reset) ? true : false; - } - return false; -} - -void SCA_ActuatorSensor::Update() -{ - if (m_actuator) - { - m_midresult = m_actuator->IsActive() && !m_actuator->IsNegativeEvent(); - } -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject SCA_ActuatorSensor::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "SCA_ActuatorSensor", - 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 SCA_ActuatorSensor::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef SCA_ActuatorSensor::Attributes[] = { - KX_PYATTRIBUTE_STRING_RW_CHECK("actuator",0,MAX_PROP_NAME,false,SCA_ActuatorSensor,m_checkactname,CheckActuator), - { NULL } //Sentinel -}; - -int SCA_ActuatorSensor::CheckActuator(void *self, const PyAttributeDef*) -{ - SCA_ActuatorSensor* sensor = reinterpret_cast(self); - SCA_IActuator* act = sensor->GetParent()->FindActuator(sensor->m_checkactname); - if (act) { - sensor->m_actuator = act; - return 0; - } - PyErr_SetString(PyExc_AttributeError, "string does not correspond to an actuator"); - return 1; -} - -#endif // WITH_PYTHON - -/* eof */ diff --git a/source/gameengine/GameLogic/SCA_ActuatorSensor.h b/source/gameengine/GameLogic/SCA_ActuatorSensor.h deleted file mode 100644 index 6005bd3ac6c..00000000000 --- a/source/gameengine/GameLogic/SCA_ActuatorSensor.h +++ /dev/null @@ -1,70 +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 ***** - */ - -#ifndef __SCA_ACTUATORSENSOR_H__ -#define __SCA_ACTUATORSENSOR_H__ - -/** \file SCA_ActuatorSensor.h - * \ingroup gamelogic - */ - -#include "SCA_ISensor.h" -#include "SCA_IActuator.h" - -class SCA_ActuatorSensor : public SCA_ISensor -{ - Py_Header - STR_String m_checkactname; - bool m_lastresult; - bool m_midresult; - protected: - SCA_IActuator* m_actuator; -public: - SCA_ActuatorSensor(class SCA_EventManager* eventmgr, - SCA_IObject* gameobj, - const STR_String& actname); - - virtual ~SCA_ActuatorSensor(); - virtual CValue* GetReplica(); - virtual void Init(); - virtual bool Evaluate(); - virtual bool IsPositiveTrigger(); - virtual void ReParent(SCA_IObject* parent); - void Update(); - -#ifdef WITH_PYTHON - - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - - static int CheckActuator(void *self, const PyAttributeDef*); - -#endif /* WITH_PYTHON */ -}; - -#endif /* __SCA_ACTUATORSENSOR_H__ */ diff --git a/source/gameengine/GameLogic/SCA_AlwaysEventManager.cpp b/source/gameengine/GameLogic/SCA_AlwaysEventManager.cpp deleted file mode 100644 index 22746953a27..00000000000 --- a/source/gameengine/GameLogic/SCA_AlwaysEventManager.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Manager for 'always' events. Since always sensors can operate in pulse - * mode, they need to be activated. - * - * - * ***** 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/GameLogic/SCA_AlwaysEventManager.cpp - * \ingroup gamelogic - */ - - -#include "SCA_AlwaysEventManager.h" -#include "SCA_LogicManager.h" -#include -#include "SCA_ISensor.h" - -using namespace std; - -SCA_AlwaysEventManager::SCA_AlwaysEventManager(class SCA_LogicManager* logicmgr) - : SCA_EventManager(logicmgr, ALWAYS_EVENTMGR) -{ -} - - - -void SCA_AlwaysEventManager::NextFrame() -{ - SG_DList::iterator it(m_sensors); - for (it.begin();!it.end();++it) - { - (*it)->Activate(m_logicmgr); - } -} - diff --git a/source/gameengine/GameLogic/SCA_AlwaysEventManager.h b/source/gameengine/GameLogic/SCA_AlwaysEventManager.h deleted file mode 100644 index 47293c75726..00000000000 --- a/source/gameengine/GameLogic/SCA_AlwaysEventManager.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 SCA_AlwaysEventManager.h - * \ingroup gamelogic - */ - -#ifndef __SCA_ALWAYSEVENTMANAGER_H__ -#define __SCA_ALWAYSEVENTMANAGER_H__ -#include "SCA_EventManager.h" -#include - -using namespace std; -class SCA_AlwaysEventManager : public SCA_EventManager -{ -public: - SCA_AlwaysEventManager(class SCA_LogicManager* logicmgr); - virtual void NextFrame(); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_AlwaysEventManager") -#endif -}; - -#endif /* __SCA_ALWAYSEVENTMANAGER_H__ */ diff --git a/source/gameengine/GameLogic/SCA_AlwaysSensor.cpp b/source/gameengine/GameLogic/SCA_AlwaysSensor.cpp deleted file mode 100644 index 1a6a82a33eb..00000000000 --- a/source/gameengine/GameLogic/SCA_AlwaysSensor.cpp +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Always trigger - * - * - * ***** 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/GameLogic/SCA_AlwaysSensor.cpp - * \ingroup gamelogic - */ - -#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 "SCA_AlwaysSensor.h" -#include "SCA_LogicManager.h" -#include "SCA_EventManager.h" - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -SCA_AlwaysSensor::SCA_AlwaysSensor(class SCA_EventManager* eventmgr, - SCA_IObject* gameobj) - : SCA_ISensor(gameobj,eventmgr) -{ - //SetDrawColor(255,0,0); - Init(); -} - -void SCA_AlwaysSensor::Init() -{ - m_alwaysresult = true; -} - -SCA_AlwaysSensor::~SCA_AlwaysSensor() -{ - /* intentionally empty */ -} - - - -CValue* SCA_AlwaysSensor::GetReplica() -{ - CValue* replica = new SCA_AlwaysSensor(*this);//m_float,GetName()); - // this will copy properties and so on... - replica->ProcessReplica(); - - return replica; -} - - - -bool SCA_AlwaysSensor::IsPositiveTrigger() -{ - return (m_invert ? false : true); -} - - - -bool SCA_AlwaysSensor::Evaluate() -{ - /* Nice! :) */ - //return true; - /* even nicer ;) */ - //return false; - - /* nicest ! */ - bool result = m_alwaysresult; - m_alwaysresult = false; - return result; -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject SCA_AlwaysSensor::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "SCA_AlwaysSensor", - 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 SCA_AlwaysSensor::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef SCA_AlwaysSensor::Attributes[] = { - { NULL } //Sentinel -}; - -#endif - -/* eof */ diff --git a/source/gameengine/GameLogic/SCA_AlwaysSensor.h b/source/gameengine/GameLogic/SCA_AlwaysSensor.h deleted file mode 100644 index e0ab4279b1c..00000000000 --- a/source/gameengine/GameLogic/SCA_AlwaysSensor.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - * SCA_AlwaysSensor.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 SCA_AlwaysSensor.h - * \ingroup gamelogic - */ - -#ifndef __SCA_ALWAYSSENSOR_H__ -#define __SCA_ALWAYSSENSOR_H__ -#include "SCA_ISensor.h" - -class SCA_AlwaysSensor : public SCA_ISensor -{ - Py_Header - bool m_alwaysresult; -public: - SCA_AlwaysSensor(class SCA_EventManager* eventmgr, - SCA_IObject* gameobj); - virtual ~SCA_AlwaysSensor(); - virtual CValue* GetReplica(); - virtual bool Evaluate(); - virtual bool IsPositiveTrigger(); - virtual void Init(); -}; - -#endif /* __SCA_ALWAYSSENSOR_H__ */ diff --git a/source/gameengine/GameLogic/SCA_BasicEventManager.cpp b/source/gameengine/GameLogic/SCA_BasicEventManager.cpp deleted file mode 100644 index e87f9b8f0e4..00000000000 --- a/source/gameengine/GameLogic/SCA_BasicEventManager.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Manager for 'always' events. Since always sensors can operate in pulse - * mode, they need to be activated. - * - * - * ***** 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/GameLogic/SCA_BasicEventManager.cpp - * \ingroup gamelogic - */ - - -#include "SCA_BasicEventManager.h" -#include "SCA_LogicManager.h" -#include -#include "SCA_ISensor.h" - -using namespace std; - -SCA_BasicEventManager::SCA_BasicEventManager(class SCA_LogicManager* logicmgr) - : SCA_EventManager(logicmgr, BASIC_EVENTMGR) -{ -} - -SCA_BasicEventManager::~SCA_BasicEventManager() -{ -} - -void SCA_BasicEventManager::NextFrame() -{ - SG_DList::iterator it(m_sensors); - for (it.begin();!it.end();++it) - { - (*it)->Activate(m_logicmgr); - } -} - diff --git a/source/gameengine/GameLogic/SCA_BasicEventManager.h b/source/gameengine/GameLogic/SCA_BasicEventManager.h deleted file mode 100644 index a015233454b..00000000000 --- a/source/gameengine/GameLogic/SCA_BasicEventManager.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Manager for sensor that only need to call Update - * - * - * ***** 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 SCA_BasicEventManager.h - * \ingroup gamelogic - */ - -#ifndef __SCA_BASICEVENTMANAGER_H__ -#define __SCA_BASICEVENTMANAGER_H__ - -#include "SCA_EventManager.h" -#include - -using namespace std; - -class SCA_BasicEventManager : public SCA_EventManager -{ -public: - SCA_BasicEventManager(class SCA_LogicManager* logicmgr); - ~SCA_BasicEventManager(); - - virtual void NextFrame(); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_BasicEventManager") -#endif -}; - -#endif /* __SCA_BASICEVENTMANAGER_H__ */ diff --git a/source/gameengine/GameLogic/SCA_DelaySensor.cpp b/source/gameengine/GameLogic/SCA_DelaySensor.cpp deleted file mode 100644 index af751cffc2e..00000000000 --- a/source/gameengine/GameLogic/SCA_DelaySensor.cpp +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Delay trigger - * - * - * ***** 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/GameLogic/SCA_DelaySensor.cpp - * \ingroup gamelogic - */ - -#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 "SCA_DelaySensor.h" -#include "SCA_LogicManager.h" -#include "SCA_EventManager.h" - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -SCA_DelaySensor::SCA_DelaySensor(class SCA_EventManager* eventmgr, - SCA_IObject* gameobj, - int delay, - int duration, - bool repeat) - : SCA_ISensor(gameobj,eventmgr), - m_repeat(repeat), - m_delay(delay), - m_duration(duration) -{ - Init(); -} - -void SCA_DelaySensor::Init() -{ - m_lastResult = false; - m_frameCount = -1; - m_reset = true; -} - -SCA_DelaySensor::~SCA_DelaySensor() -{ - /* intentionally empty */ -} - -CValue* SCA_DelaySensor::GetReplica() -{ - CValue* replica = new SCA_DelaySensor(*this); - // this will copy properties and so on... - replica->ProcessReplica(); - - return replica; -} - - - -bool SCA_DelaySensor::IsPositiveTrigger() -{ - return (m_invert ? !m_lastResult : m_lastResult); -} - -bool SCA_DelaySensor::Evaluate() -{ - bool trigger = false; - bool result; - - if (m_frameCount==-1) { - // this is needed to ensure ON trigger in case delay==0 - // and avoid spurious OFF trigger when duration==0 - m_lastResult = false; - m_frameCount = 0; - } - - if (m_frameCount 0) { - if (m_frameCount < m_delay+m_duration) { - m_frameCount++; - result = true; - } else { - result = false; - if (m_repeat) - m_frameCount = -1; - } - } else { - result = true; - if (m_repeat) - m_frameCount = -1; - } - if ((m_reset && m_level) || result != m_lastResult) - trigger = true; - m_reset = false; - m_lastResult = result; - return trigger; -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject SCA_DelaySensor::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "SCA_DelaySensor", - 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 SCA_DelaySensor::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef SCA_DelaySensor::Attributes[] = { - KX_PYATTRIBUTE_INT_RW("delay",0,100000,true,SCA_DelaySensor,m_delay), - KX_PYATTRIBUTE_INT_RW("duration",0,100000,true,SCA_DelaySensor,m_duration), - KX_PYATTRIBUTE_BOOL_RW("repeat",SCA_DelaySensor,m_repeat), - { NULL } //Sentinel -}; - -#endif // WITH_PYTHON - -/* eof */ diff --git a/source/gameengine/GameLogic/SCA_DelaySensor.h b/source/gameengine/GameLogic/SCA_DelaySensor.h deleted file mode 100644 index 9b39de7e099..00000000000 --- a/source/gameengine/GameLogic/SCA_DelaySensor.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - * SCA_DelaySensor.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 SCA_DelaySensor.h - * \ingroup gamelogic - */ - -#ifndef __SCA_DELAYSENSOR_H__ -#define __SCA_DELAYSENSOR_H__ -#include "SCA_ISensor.h" - -class SCA_DelaySensor : public SCA_ISensor -{ - Py_Header - bool m_lastResult; - bool m_repeat; - int m_delay; - int m_duration; - int m_frameCount; - -public: - SCA_DelaySensor(class SCA_EventManager* eventmgr, - SCA_IObject* gameobj, - int delay, - int duration, - bool repeat); - virtual ~SCA_DelaySensor(); - virtual CValue* GetReplica(); - virtual bool Evaluate(); - virtual bool IsPositiveTrigger(); - virtual void Init(); - - - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ -}; - -#endif /* __SCA_DELAYSENSOR_H__ */ diff --git a/source/gameengine/GameLogic/SCA_EventManager.cpp b/source/gameengine/GameLogic/SCA_EventManager.cpp deleted file mode 100644 index ffe1ea2dc30..00000000000 --- a/source/gameengine/GameLogic/SCA_EventManager.cpp +++ /dev/null @@ -1,83 +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/GameLogic/SCA_EventManager.cpp - * \ingroup gamelogic - */ - - -#include -#include "SCA_EventManager.h" -#include "SCA_ISensor.h" - - -SCA_EventManager::SCA_EventManager(SCA_LogicManager* logicmgr, EVENT_MANAGER_TYPE mgrtype) - :m_logicmgr(logicmgr), - m_mgrtype(mgrtype) -{ -} - - - -SCA_EventManager::~SCA_EventManager() -{ - // all sensors should be removed - assert(m_sensors.Empty()); -} - -void SCA_EventManager::RegisterSensor(class SCA_ISensor* sensor) -{ - m_sensors.AddBack(sensor); -} - -void SCA_EventManager::RemoveSensor(class SCA_ISensor* sensor) -{ - sensor->Delink(); -} - -void SCA_EventManager::NextFrame(double curtime, double fixedtime) -{ - NextFrame(); -} - -void SCA_EventManager::NextFrame() -{ - assert(false); // && "Event managers should override a NextFrame method"); -} - -void SCA_EventManager::EndFrame() -{ -} - -void SCA_EventManager::UpdateFrame() -{ -} - -int SCA_EventManager::GetType() -{ - return (int) m_mgrtype; -} diff --git a/source/gameengine/GameLogic/SCA_EventManager.h b/source/gameengine/GameLogic/SCA_EventManager.h deleted file mode 100644 index eb9a6d9aca1..00000000000 --- a/source/gameengine/GameLogic/SCA_EventManager.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 SCA_EventManager.h - * \ingroup gamelogic - */ - -#ifndef __SCA_EVENTMANAGER_H__ -#define __SCA_EVENTMANAGER_H__ - -#include -#include -#include - -#include "SG_DList.h" - -class SCA_EventManager -{ -protected: - class SCA_LogicManager* m_logicmgr; /* all event manager subclasses use this (other then TimeEventManager) */ - - // use a set to speed-up insertion/removal - //std::set m_sensors; - SG_DList m_sensors; - -public: - enum EVENT_MANAGER_TYPE { - KEYBOARD_EVENTMGR = 0, - MOUSE_EVENTMGR, - ALWAYS_EVENTMGR, - TOUCH_EVENTMGR, - PROPERTY_EVENTMGR, - TIME_EVENTMGR, - RANDOM_EVENTMGR, - RAY_EVENTMGR, - NETWORK_EVENTMGR, - JOY_EVENTMGR, - ACTUATOR_EVENTMGR, - BASIC_EVENTMGR - }; - - SCA_EventManager(SCA_LogicManager* logicmgr, EVENT_MANAGER_TYPE mgrtype); - virtual ~SCA_EventManager(); - - virtual void RemoveSensor(class SCA_ISensor* sensor); - virtual void NextFrame(double curtime, double fixedtime); - virtual void NextFrame(); - virtual void UpdateFrame(); - virtual void EndFrame(); - virtual void RegisterSensor(class SCA_ISensor* sensor); - int GetType(); - //SG_DList &GetSensors() { return m_sensors; } - - - void Replace_LogicManager(SCA_LogicManager* logicmgr) { m_logicmgr= logicmgr; } - -protected: - EVENT_MANAGER_TYPE m_mgrtype; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_EventManager") -#endif -}; - -#endif - diff --git a/source/gameengine/GameLogic/SCA_ExpressionController.cpp b/source/gameengine/GameLogic/SCA_ExpressionController.cpp deleted file mode 100644 index ef058e215d6..00000000000 --- a/source/gameengine/GameLogic/SCA_ExpressionController.cpp +++ /dev/null @@ -1,159 +0,0 @@ -/* - * 'Expression Controller enables to calculate an expression that wires inputs to output - * - * - * ***** 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/GameLogic/SCA_ExpressionController.cpp - * \ingroup gamelogic - */ - - -#include "SCA_ExpressionController.h" -#include "SCA_ISensor.h" -#include "SCA_LogicManager.h" -#include "EXP_BoolValue.h" -#include "EXP_InputParser.h" -#include "MT_Transform.h" // for fuzzyZero - -#include - - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -SCA_ExpressionController::SCA_ExpressionController(SCA_IObject* gameobj, - const STR_String& exprtext) - :SCA_IController(gameobj), - m_exprText(exprtext), - m_exprCache(NULL) -{ -} - - - -SCA_ExpressionController::~SCA_ExpressionController() -{ - if (m_exprCache) - m_exprCache->Release(); -} - - - -CValue* SCA_ExpressionController::GetReplica() -{ - SCA_ExpressionController* replica = new SCA_ExpressionController(*this); - replica->m_exprText = m_exprText; - replica->m_exprCache = NULL; - // this will copy properties and so on... - replica->ProcessReplica(); - - return replica; -} - - -// Forced deletion of precalculated expression to break reference loop -// Use this function when you know that you won't use the sensor anymore -void SCA_ExpressionController::Delete() -{ - if (m_exprCache) - { - m_exprCache->Release(); - m_exprCache = NULL; - } - Release(); -} - - -void SCA_ExpressionController::Trigger(SCA_LogicManager* logicmgr) -{ - - bool expressionresult = false; - if (!m_exprCache) - { - CParser parser; - parser.SetContext(this->AddRef()); - m_exprCache = parser.ProcessText(m_exprText); - } - if (m_exprCache) - { - CValue* value = m_exprCache->Calculate(); - if (value) - { - if (value->IsError()) - { - printf("%s\n", value->GetText().ReadPtr()); - } else - { - float num = (float)value->GetNumber(); - expressionresult = !MT_fuzzyZero(num); - } - value->Release(); - - } - } - - for (vector::const_iterator i=m_linkedactuators.begin(); - !(i==m_linkedactuators.end());i++) - { - SCA_IActuator* actua = *i; - logicmgr->AddActiveActuator(actua,expressionresult); - } -} - - - -CValue* SCA_ExpressionController::FindIdentifier(const STR_String& identifiername) -{ - - CValue* identifierval = NULL; - - for (vector::const_iterator is=m_linkedsensors.begin(); - !(is==m_linkedsensors.end());is++) - { - SCA_ISensor* sensor = *is; - if (sensor->GetName() == identifiername) - { - identifierval = new CBoolValue(sensor->GetState()); - //identifierval = sensor->AddRef(); - break; - } - - //if (!sensor->IsPositiveTrigger()) - //{ - // sensorresult = false; - // break; - //} - } - - if (identifierval) - return identifierval; - - return GetParent()->FindIdentifier(identifiername); - -} diff --git a/source/gameengine/GameLogic/SCA_ExpressionController.h b/source/gameengine/GameLogic/SCA_ExpressionController.h deleted file mode 100644 index c16944ccde1..00000000000 --- a/source/gameengine/GameLogic/SCA_ExpressionController.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - * KX_EXPRESSIONController.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 SCA_ExpressionController.h - * \ingroup gamelogic - */ - -#ifndef __SCA_EXPRESSIONCONTROLLER_H__ -#define __SCA_EXPRESSIONCONTROLLER_H__ - -#include "SCA_IController.h" - -class SCA_ExpressionController : public SCA_IController -{ -// Py_Header - STR_String m_exprText; - CExpression* m_exprCache; - -public: - SCA_ExpressionController(SCA_IObject* gameobj, - const STR_String& exprtext); - - virtual ~SCA_ExpressionController(); - virtual CValue* GetReplica(); - virtual void Trigger(SCA_LogicManager* logicmgr); - virtual CValue* FindIdentifier(const STR_String& identifiername); - /** - * used to release the expression cache - * so that self references are removed before the controller itself is released - */ - virtual void Delete(); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_ExpressionController") -#endif -}; - -#endif /* __SCA_EXPRESSIONCONTROLLER_H__ */ diff --git a/source/gameengine/GameLogic/SCA_IActuator.cpp b/source/gameengine/GameLogic/SCA_IActuator.cpp deleted file mode 100644 index 9a355fdf3c9..00000000000 --- a/source/gameengine/GameLogic/SCA_IActuator.cpp +++ /dev/null @@ -1,140 +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/GameLogic/SCA_IActuator.cpp - * \ingroup gamelogic - */ - - -#include "SCA_IActuator.h" -#include - -using namespace std; - -SCA_IActuator::SCA_IActuator(SCA_IObject* gameobj, KX_ACTUATOR_TYPE type) : - SCA_ILogicBrick(gameobj), - m_type(type), - m_links(0), - m_posevent(false), - m_negevent(false) -{ - // nothing to do -} - -bool SCA_IActuator::Update(double curtime, bool frame) -{ - if (frame) - return Update(); - - return true; -} - -bool SCA_IActuator::Update() -{ - assert(false && "Actuators should override an Update method."); - return false; -} - -void SCA_IActuator::Activate(SG_DList& head) -{ - if (QEmpty()) - { - InsertActiveQList(m_gameobj->m_activeActuators); - head.AddBack(&m_gameobj->m_activeActuators); - } -} - -// this function is only used to deactivate actuators outside the logic loop -// e.g. when an object is deleted. -void SCA_IActuator::Deactivate() -{ - if (QDelink()) - { - // the actuator was in the active list - if (m_gameobj->m_activeActuators.QEmpty()) - // the owner object has no more active actuators, remove it from the global list - m_gameobj->m_activeActuators.Delink(); - } -} - - -void SCA_IActuator::ProcessReplica() -{ - SCA_ILogicBrick::ProcessReplica(); - RemoveAllEvents(); - m_linkedcontrollers.clear(); -} - - - -SCA_IActuator::~SCA_IActuator() -{ - RemoveAllEvents(); -} - -void SCA_IActuator::DecLink() -{ - m_links--; - if (m_links < 0) - { - printf("Warning: actuator %s has negative m_links: %d\n", m_name.Ptr(), m_links); - m_links = 0; - } -} - -void SCA_IActuator::LinkToController(SCA_IController* controller) -{ - m_linkedcontrollers.push_back(controller); -} - -void SCA_IActuator::UnlinkController(SCA_IController* controller) -{ - std::vector::iterator contit; - for (contit = m_linkedcontrollers.begin();!(contit==m_linkedcontrollers.end());++contit) - { - if ((*contit) == controller) - { - *contit = m_linkedcontrollers.back(); - m_linkedcontrollers.pop_back(); - return; - } - } - printf("Missing link from actuator %s:%s to controller %s:%s\n", - m_gameobj->GetName().ReadPtr(), GetName().ReadPtr(), - controller->GetParent()->GetName().ReadPtr(), controller->GetName().ReadPtr()); -} - -void SCA_IActuator::UnlinkAllControllers() -{ - std::vector::iterator contit; - for (contit = m_linkedcontrollers.begin();!(contit==m_linkedcontrollers.end());++contit) - { - (*contit)->UnlinkActuator(this); - } - m_linkedcontrollers.clear(); -} - diff --git a/source/gameengine/GameLogic/SCA_IActuator.h b/source/gameengine/GameLogic/SCA_IActuator.h deleted file mode 100644 index b63cb633b4e..00000000000 --- a/source/gameengine/GameLogic/SCA_IActuator.h +++ /dev/null @@ -1,168 +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 SCA_IActuator.h - * \ingroup gamelogic - */ - -#ifndef __SCA_IACTUATOR_H__ -#define __SCA_IACTUATOR_H__ - -#include "SCA_IController.h" -#include - -/** - * Use of SG_DList : None - * Use of SG_QList : element of activated actuator list of their owner - * Head: SCA_IObject::m_activeActuators - */ -class SCA_IActuator : public SCA_ILogicBrick -{ - friend class SCA_LogicManager; -protected: - int m_type; - int m_links; // number of active links to controllers - // when 0, the actuator is automatically stopped - //std::vector m_events; - bool m_posevent; - bool m_negevent; - - std::vector m_linkedcontrollers; - - void RemoveAllEvents() - { - m_posevent = false; - m_negevent = false; - } - - -public: - /** - * This class also inherits the default copy constructors - */ - enum KX_ACTUATOR_TYPE { - KX_ACT_OBJECT, - KX_ACT_IPO, - KX_ACT_CAMERA, - KX_ACT_SOUND, - KX_ACT_PROPERTY, - KX_ACT_ADD_OBJECT, - KX_ACT_END_OBJECT, - KX_ACT_DYNAMIC, - KX_ACT_REPLACE_MESH, - KX_ACT_TRACKTO, - KX_ACT_CONSTRAINT, - KX_ACT_SCENE, - KX_ACT_RANDOM, - KX_ACT_MESSAGE, - KX_ACT_ACTION, - KX_ACT_CD, - KX_ACT_GAME, - KX_ACT_VISIBILITY, - KX_ACT_2DFILTER, - KX_ACT_PARENT, - KX_ACT_SHAPEACTION, - KX_ACT_STATE, - KX_ACT_ARMATURE, - KX_ACT_STEERING, - KX_ACT_MOUSE, - }; - - SCA_IActuator(SCA_IObject* gameobj, KX_ACTUATOR_TYPE type); - - /** - * UnlinkObject(...) - * Certain actuator use gameobject pointers (like TractTo actuator) - * This function can be called when an object is removed to make - * sure that the actuator will not use it anymore. - */ - - virtual bool UnlinkObject(SCA_IObject* clientobj) { return false; } - - /** - * Update(...) - * Update the actuator based upon the events received since - * the last call to Update, the current time and deltatime the - * time elapsed in this frame ? - * It is the responsibility of concrete Actuators to clear - * their event's. This is usually done in the Update() method via - * a call to RemoveAllEvents() - */ - - - virtual bool Update(double curtime, bool frame); - virtual bool Update(); - - /** - * Add an event to an actuator. - */ - //void AddEvent(CValue* event) - void AddEvent(bool event) - { - if (event) - m_posevent = true; - else - m_negevent = true; - } - - virtual void ProcessReplica(); - - /** - * Return true if all the current events - * are negative. The definition of negative event is - * not immediately clear. But usually refers to key-up events - * or events where no action is required. - */ - bool IsNegativeEvent() const - { - return !m_posevent && m_negevent; - } - - virtual ~SCA_IActuator(); - - /** - * remove this actuator from the list of active actuators - */ - virtual void Deactivate(); - virtual void Activate(SG_DList& head); - - void LinkToController(SCA_IController* controller); - void UnlinkController(class SCA_IController* cont); - void UnlinkAllControllers(); - - void ClrLink() { m_links=0; } - void IncLink() { m_links++; } - virtual void DecLink(); - bool IsNoLink() const { return !m_links; } - bool IsType(KX_ACTUATOR_TYPE type) { return m_type == type; } - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_IActuator") -#endif -}; - -#endif /* __SCA_IACTUATOR_H__ */ diff --git a/source/gameengine/GameLogic/SCA_IController.cpp b/source/gameengine/GameLogic/SCA_IController.cpp deleted file mode 100644 index c4176d66688..00000000000 --- a/source/gameengine/GameLogic/SCA_IController.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/GameLogic/SCA_IController.cpp - * \ingroup gamelogic - */ - - -#include - -#include "SCA_IController.h" -#include "SCA_LogicManager.h" -#include "SCA_IActuator.h" -#include "SCA_ISensor.h" -#include "EXP_PyObjectPlus.h" -#include "EXP_ListWrapper.h" - -#include - -SCA_IController::SCA_IController(SCA_IObject* gameobj) - : - SCA_ILogicBrick(gameobj), - m_statemask(0), - m_justActivated(false) -{ -} - - - -SCA_IController::~SCA_IController() -{ - //UnlinkAllActuators(); -} - - - -std::vector& SCA_IController::GetLinkedSensors() -{ - return m_linkedsensors; -} - - - -std::vector& SCA_IController::GetLinkedActuators() -{ - return m_linkedactuators; -} - - - -void SCA_IController::UnlinkAllSensors() -{ - std::vector::iterator sensit; - for (sensit = m_linkedsensors.begin();!(sensit==m_linkedsensors.end());++sensit) - { - if (IsActive()) - { - (*sensit)->DecLink(); - } - (*sensit)->UnlinkController(this); - } - m_linkedsensors.clear(); -} - - - -void SCA_IController::UnlinkAllActuators() -{ - std::vector::iterator actit; - for (actit = m_linkedactuators.begin();!(actit==m_linkedactuators.end());++actit) - { - if (IsActive()) - { - (*actit)->DecLink(); - } - (*actit)->UnlinkController(this); - } - m_linkedactuators.clear(); -} - -void SCA_IController::LinkToActuator(SCA_IActuator* actua) -{ - m_linkedactuators.push_back(actua); - if (IsActive()) - { - actua->IncLink(); - } -} - -void SCA_IController::UnlinkActuator(class SCA_IActuator* actua) -{ - std::vector::iterator actit; - for (actit = m_linkedactuators.begin();!(actit==m_linkedactuators.end());++actit) - { - if ((*actit) == actua) - { - if (IsActive()) - { - (*actit)->DecLink(); - } - *actit = m_linkedactuators.back(); - m_linkedactuators.pop_back(); - return; - } - } - printf("Missing link from controller %s:%s to actuator %s:%s\n", - m_gameobj->GetName().ReadPtr(), GetName().ReadPtr(), - actua->GetParent()->GetName().ReadPtr(), actua->GetName().ReadPtr()); -} - -void SCA_IController::LinkToSensor(SCA_ISensor* sensor) -{ - m_linkedsensors.push_back(sensor); - if (IsActive()) - { - sensor->IncLink(); - } -} - -void SCA_IController::UnlinkSensor(class SCA_ISensor* sensor) -{ - std::vector::iterator sensit; - for (sensit = m_linkedsensors.begin();!(sensit==m_linkedsensors.end());++sensit) - { - if ((*sensit) == sensor) - { - if (IsActive()) - { - sensor->DecLink(); - } - *sensit = m_linkedsensors.back(); - m_linkedsensors.pop_back(); - return; - } - } - printf("Missing link from controller %s:%s to sensor %s:%s\n", - m_gameobj->GetName().ReadPtr(), GetName().ReadPtr(), - sensor->GetParent()->GetName().ReadPtr(), sensor->GetName().ReadPtr()); -} - - -void SCA_IController::ApplyState(unsigned int state) -{ - std::vector::iterator actit; - std::vector::iterator sensit; - - if (m_statemask & state) - { - if (!IsActive()) - { - // reactive the controller, all the links to actuator are valid again - for (actit = m_linkedactuators.begin();!(actit==m_linkedactuators.end());++actit) - { - (*actit)->IncLink(); - } - - for (sensit = m_linkedsensors.begin();!(sensit==m_linkedsensors.end());++sensit) - { - (*sensit)->IncLink(); - } - SetActive(true); - m_justActivated = true; - } - } else if (IsActive()) - { - for (actit = m_linkedactuators.begin();!(actit==m_linkedactuators.end());++actit) - { - (*actit)->DecLink(); - } - for (sensit = m_linkedsensors.begin();!(sensit==m_linkedsensors.end());++sensit) - { - (*sensit)->DecLink(); - } - SetActive(false); - m_justActivated = false; - } -} - -#ifdef WITH_PYTHON - -/* Python api */ - -PyTypeObject SCA_IController::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "SCA_IController", - 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_ILogicBrick::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef SCA_IController::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef SCA_IController::Attributes[] = { - KX_PYATTRIBUTE_RO_FUNCTION("state", SCA_IController, pyattr_get_state), - KX_PYATTRIBUTE_RO_FUNCTION("sensors", SCA_IController, pyattr_get_sensors), - KX_PYATTRIBUTE_RO_FUNCTION("actuators", SCA_IController, pyattr_get_actuators), - KX_PYATTRIBUTE_BOOL_RW("useHighPriority",SCA_IController,m_bookmark), - { NULL } //Sentinel -}; - -PyObject *SCA_IController::pyattr_get_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_IController* self = static_cast(self_v); - return PyLong_FromLong(self->m_statemask); -} - -static int sca_icontroller_get_sensors_size_cb(void *self_v) -{ - return ((SCA_IController *)self_v)->GetLinkedSensors().size(); -} - -static PyObject *sca_icontroller_get_sensors_item_cb(void *self_v, int index) -{ - return ((SCA_IController *)self_v)->GetLinkedSensors()[index]->GetProxy(); -} - -static const char *sca_icontroller_get_sensors_item_name_cb(void *self_v, int index) -{ - return ((SCA_IController *)self_v)->GetLinkedSensors()[index]->GetName().ReadPtr(); -} - -PyObject *SCA_IController::pyattr_get_sensors(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - return (new CListWrapper(self_v, - ((SCA_IController *)self_v)->GetProxy(), - NULL, - sca_icontroller_get_sensors_size_cb, - sca_icontroller_get_sensors_item_cb, - sca_icontroller_get_sensors_item_name_cb, - NULL))->NewProxy(true); -} - -static int sca_icontroller_get_actuators_size_cb(void *self_v) -{ - return ((SCA_IController *)self_v)->GetLinkedActuators().size(); -} - -static PyObject *sca_icontroller_get_actuators_item_cb(void *self_v, int index) -{ - return ((SCA_IController *)self_v)->GetLinkedActuators()[index]->GetProxy(); -} - -static const char *sca_icontroller_get_actuators_item_name_cb(void *self_v, int index) -{ - return ((SCA_IController *)self_v)->GetLinkedActuators()[index]->GetName().ReadPtr(); -} - -PyObject *SCA_IController::pyattr_get_actuators(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - return (new CListWrapper(self_v, - ((SCA_IController *)self_v)->GetProxy(), - NULL, - sca_icontroller_get_actuators_size_cb, - sca_icontroller_get_actuators_item_cb, - sca_icontroller_get_actuators_item_name_cb, - NULL))->NewProxy(true); -} -#endif // WITH_PYTHON diff --git a/source/gameengine/GameLogic/SCA_IController.h b/source/gameengine/GameLogic/SCA_IController.h deleted file mode 100644 index 4ec872c2316..00000000000 --- a/source/gameengine/GameLogic/SCA_IController.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 SCA_IController.h - * \ingroup gamelogic - */ - -#ifndef __SCA_ICONTROLLER_H__ -#define __SCA_ICONTROLLER_H__ - -#include "SCA_ILogicBrick.h" -#include "EXP_PyObjectPlus.h" - -/** - * Use of SG_DList element: none - * Use of SG_QList element: build ordered list of activated controller on the owner object - * Head: SCA_IObject::m_activeControllers - */ -class SCA_IController : public SCA_ILogicBrick -{ - Py_Header -protected: - std::vector m_linkedsensors; - std::vector m_linkedactuators; - unsigned int m_statemask; - bool m_justActivated; - bool m_bookmark; -public: - SCA_IController(SCA_IObject* gameobj); - virtual ~SCA_IController(); - virtual void Trigger(class SCA_LogicManager* logicmgr)=0; - void LinkToSensor(SCA_ISensor* sensor); - void LinkToActuator(SCA_IActuator*); - std::vector& GetLinkedSensors(); - std::vector& GetLinkedActuators(); - void ReserveActuator(int num) - { - m_linkedactuators.reserve(num); - } - void UnlinkAllSensors(); - void UnlinkAllActuators(); - void UnlinkActuator(class SCA_IActuator* actua); - void UnlinkSensor(class SCA_ISensor* sensor); - void SetState(unsigned int state) { m_statemask = state; } - void ApplyState(unsigned int state); - void Deactivate() - { - // the controller can only be part of a sensor m_newControllers list - Delink(); - } - bool IsJustActivated() - { - return m_justActivated; - } - void ClrJustActivated() - { - m_justActivated = false; - } - void SetBookmark(bool bookmark) - { - m_bookmark = bookmark; - } - void Activate(SG_DList& head) - { - if (QEmpty()) - { - if (m_bookmark) - { - m_gameobj->m_activeBookmarkedControllers.QAddBack(this); - head.AddFront(&m_gameobj->m_activeBookmarkedControllers); - } - else - { - InsertActiveQList(m_gameobj->m_activeControllers); - head.AddBack(&m_gameobj->m_activeControllers); - } - } - } - - -#ifdef WITH_PYTHON - static PyObject* pyattr_get_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_sensors(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_actuators(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); -#endif /* WITH_PYTHON */ -}; - -#endif /* __SCA_ICONTROLLER_H__ */ diff --git a/source/gameengine/GameLogic/SCA_IInputDevice.cpp b/source/gameengine/GameLogic/SCA_IInputDevice.cpp deleted file mode 100644 index f4fce034c87..00000000000 --- a/source/gameengine/GameLogic/SCA_IInputDevice.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 ***** - */ - -/** \file gameengine/GameLogic/SCA_IInputDevice.cpp - * \ingroup gamelogic - */ - - -#include -#include "SCA_IInputDevice.h" - -SCA_IInputDevice::SCA_IInputDevice() - : - m_currentTable(0) -{ - ClearStatusTable(0); - ClearStatusTable(1); -} - - - -SCA_IInputDevice::~SCA_IInputDevice() -{ -} - -void SCA_IInputDevice::HookEscape() -{ - assert(false && "This device does not support hooking escape."); -} - -void SCA_IInputDevice::ClearStatusTable(int tableid) -{ - for (int i=0;i KX_NO_INPUTSTATUS - * KX_JUSTACTIVATED -> KX_ACTIVE - * KX_ACTIVE -> KX_ACTIVE - * KX_JUSTRELEASED -> KX_NO_INPUTSTATUS - * - * Getting new events provides the - * KX_NO_INPUTSTATUS->KX_JUSTACTIVATED and - * KX_ACTIVE->KX_JUSTRELEASED transitions. - */ - virtual void NextFrame(); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_InputEvent") -#endif -}; - -#endif /* __SCA_IINPUTDEVICE_H__ */ - diff --git a/source/gameengine/GameLogic/SCA_ILogicBrick.cpp b/source/gameengine/GameLogic/SCA_ILogicBrick.cpp deleted file mode 100644 index d0a6e4540c9..00000000000 --- a/source/gameengine/GameLogic/SCA_ILogicBrick.cpp +++ /dev/null @@ -1,271 +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/GameLogic/SCA_ILogicBrick.cpp - * \ingroup gamelogic - */ - - -#include - -#include "SCA_ILogicBrick.h" -#include "EXP_PyObjectPlus.h" - -SCA_ILogicBrick::SCA_ILogicBrick(SCA_IObject* gameobj) - : - CValue(), - m_gameobj(gameobj), - m_logicManager(NULL), - m_Execute_Priority(0), - m_Execute_Ueber_Priority(0), - m_bActive(false), - m_eventval(0) -{ - m_text = "KX_LogicBrick"; -} - - - -SCA_ILogicBrick::~SCA_ILogicBrick() -{ - RemoveEvent(); -} - - - -void SCA_ILogicBrick::SetExecutePriority(int execute_Priority) -{ - m_Execute_Priority = execute_Priority; -} - - - -void SCA_ILogicBrick::SetUeberExecutePriority(int execute_Priority) -{ - m_Execute_Ueber_Priority = execute_Priority; -} - - - -void SCA_ILogicBrick::ReParent(SCA_IObject* parent) -{ - m_gameobj = parent; -} - -void SCA_ILogicBrick::Relink(CTR_Map *obj_map) -{ - // nothing to do -} - -CValue* SCA_ILogicBrick::Calc(VALUE_OPERATOR op, CValue *val) -{ - CValue* temp = new CBoolValue(false,""); - CValue* result = temp->Calc(op,val); - temp->Release(); - - return result; -} - - - -CValue* SCA_ILogicBrick::CalcFinal(VALUE_DATA_TYPE dtype, - VALUE_OPERATOR op, - CValue *val) -{ - // same as bool implementation, so... - CValue* temp = new CBoolValue(false,""); - CValue* result = temp->CalcFinal(dtype,op,val); - temp->Release(); - - return result; -} - - - -const STR_String& SCA_ILogicBrick::GetText() -{ - if (m_name.Length()) - return m_name; - - return m_text; -} - - - -double SCA_ILogicBrick::GetNumber() -{ - return -1; -} - - - -STR_String& SCA_ILogicBrick::GetName() -{ - return m_name; -} - - - -void SCA_ILogicBrick::SetName(const char *name) -{ - m_name = name; -} - -bool SCA_ILogicBrick::LessComparedTo(SCA_ILogicBrick* other) -{ - return (this->m_Execute_Ueber_Priority < other->m_Execute_Ueber_Priority) - || ((this->m_Execute_Ueber_Priority == other->m_Execute_Ueber_Priority) && - (this->m_Execute_Priority < other->m_Execute_Priority)); -} - -void SCA_ILogicBrick::SetLogicManager(SCA_LogicManager *logicmgr) -{ - m_logicManager = logicmgr; -} - -SCA_LogicManager *SCA_ILogicBrick::GetLogicManager() -{ - return m_logicManager; -} - -void SCA_ILogicBrick::RegisterEvent(CValue* eventval) -{ - if (m_eventval) - m_eventval->Release(); - - m_eventval = eventval->AddRef(); -} - - -void SCA_ILogicBrick::RemoveEvent() -{ - if (m_eventval) - { - m_eventval->Release(); - m_eventval = NULL; - } -} - - - -CValue* SCA_ILogicBrick::GetEvent() -{ - if (m_eventval) - { - return m_eventval->AddRef(); - } - - return NULL; -} - - - -#ifdef WITH_PYTHON - -/* python stuff */ - -PyTypeObject SCA_ILogicBrick::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "SCA_ILogicBrick", - 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 SCA_ILogicBrick::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef SCA_ILogicBrick::Attributes[] = { - KX_PYATTRIBUTE_RO_FUNCTION("owner", SCA_ILogicBrick, pyattr_get_owner), - KX_PYATTRIBUTE_INT_RW("executePriority",0,100000,false,SCA_ILogicBrick,m_Execute_Priority), - KX_PYATTRIBUTE_STRING_RO("name", SCA_ILogicBrick, m_name), - {NULL} //Sentinel -}; - -int SCA_ILogicBrick::CheckProperty(void *self, const PyAttributeDef *attrdef) -{ - if (attrdef->m_type != KX_PYATTRIBUTE_TYPE_STRING || attrdef->m_length != 1) { - PyErr_SetString(PyExc_AttributeError, "inconsistent check function for attribute type, report to blender.org"); - return 1; - } - SCA_ILogicBrick* brick = reinterpret_cast(self); - STR_String* var = reinterpret_cast((char*)self+attrdef->m_offset); - CValue* prop = brick->GetParent()->FindIdentifier(*var); - bool error = prop->IsError(); - prop->Release(); - if (error) { - PyErr_SetString(PyExc_ValueError, "string does not correspond to a property"); - return 1; - } - return 0; -} - -/*Attribute functions */ -PyObject *SCA_ILogicBrick::pyattr_get_owner(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_ILogicBrick* self = static_cast(self_v); - CValue* parent = self->GetParent(); - - if (parent) - return parent->GetProxy(); - - Py_RETURN_NONE; -} - - - -/* Conversions for making life better. */ -bool SCA_ILogicBrick::PyArgToBool(int boolArg) -{ - if (boolArg) { - return true; - } else { - return false; - } -} - -PyObject *SCA_ILogicBrick::BoolToPyArg(bool boolarg) -{ - return PyLong_FromLong(boolarg ? KX_TRUE: KX_FALSE); -} - -#endif // WITH_PYTHON diff --git a/source/gameengine/GameLogic/SCA_ILogicBrick.h b/source/gameengine/GameLogic/SCA_ILogicBrick.h deleted file mode 100644 index f9ef18cc348..00000000000 --- a/source/gameengine/GameLogic/SCA_ILogicBrick.h +++ /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. - * - * 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 SCA_ILogicBrick.h - * \ingroup gamelogic - */ - -#ifndef __SCA_ILOGICBRICK_H__ -#define __SCA_ILOGICBRICK_H__ - -#include "EXP_Value.h" -#include "SCA_IObject.h" -#include "EXP_BoolValue.h" -#include "CTR_Map.h" -#include "CTR_HashedPtr.h" - -class NG_NetworkScene; -class SCA_IScene; -class SCA_LogicManager; - -class SCA_ILogicBrick : public CValue -{ - Py_Header -protected: - SCA_IObject* m_gameobj; - SCA_LogicManager *m_logicManager; - int m_Execute_Priority; - int m_Execute_Ueber_Priority; - - bool m_bActive; - CValue* m_eventval; - STR_String m_text; - STR_String m_name; - //unsigned long m_drawcolor; - void RegisterEvent(CValue* eventval); - void RemoveEvent(); - CValue* GetEvent(); - -public: - SCA_ILogicBrick(SCA_IObject* gameobj); - virtual ~SCA_ILogicBrick(); - - void SetExecutePriority(int execute_Priority); - void SetUeberExecutePriority(int execute_Priority); - - SCA_IObject* GetParent() { return m_gameobj; } - - virtual void ReParent(SCA_IObject* parent); - virtual void Relink(CTR_Map *obj_map); - virtual void Delete() { Release(); } - - // act as a BoolValue (with value IsPositiveTrigger) - 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 STR_String& GetName(); - virtual void SetName(const char *); - - bool IsActive() - { - return m_bActive; - } - - void SetActive(bool active) - { - m_bActive=active; - } - - // insert in a QList at position corresponding to m_Execute_Priority - void InsertActiveQList(SG_QList& head) - { - SG_QList::iterator it(head); - for (it.begin(); !it.end() && m_Execute_Priority > (*it)->m_Execute_Priority; ++it); - it.add_back(this); - } - - // insert in a QList at position corresponding to m_Execute_Priority - // inside a longer list that contains elements of other objects. - // Sorting is done only between the elements of the same object. - // head is the head of the combined list - // current points to the first element of the object in the list, NULL if none yet - void InsertSelfActiveQList(SG_QList& head, SG_QList** current) - { - if (!*current) - { - // first element can be put anywhere - head.QAddBack(this); - *current = this; - return; - } - // note: we assume current points actually to one o our element, skip the tests - SG_QList::iterator it(head,*current); - if (m_Execute_Priority <= (*it)->m_Execute_Priority) - { - // this element comes before the first - *current = this; - } - else { - for (++it; !it.end() && (*it)->m_gameobj == m_gameobj && m_Execute_Priority > (*it)->m_Execute_Priority; ++it); - } - it.add_back(this); - } - - virtual bool LessComparedTo(SCA_ILogicBrick* other); - - virtual void SetLogicManager(SCA_LogicManager *logicmgr); - SCA_LogicManager *GetLogicManager(); - - /* for moving logic bricks between scenes */ - virtual void Replace_IScene(SCA_IScene *val) {} - virtual void Replace_NetworkScene(NG_NetworkScene *val) {} - -#ifdef WITH_PYTHON - // python methods - - static PyObject* pyattr_get_owner(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - - // check that attribute is a property - static int CheckProperty(void *self, const PyAttributeDef *attrdef); - - enum KX_BOOL_TYPE { - KX_BOOL_NODEF = 0, - KX_TRUE, - KX_FALSE, - KX_BOOL_MAX - }; - - -protected: - /* Some conversions to go with the bool type. */ - /** Convert a KX_TRUE, KX_FALSE in Python to a c++ value. */ - bool PyArgToBool(int boolArg); - - /** Convert a a c++ value to KX_TRUE, KX_FALSE in Python. */ - PyObject *BoolToPyArg(bool); - -#endif /* WITH_PYTHON */ - -}; - -#endif /* __SCA_ILOGICBRICK_H__ */ diff --git a/source/gameengine/GameLogic/SCA_IObject.cpp b/source/gameengine/GameLogic/SCA_IObject.cpp deleted file mode 100644 index 526e695e792..00000000000 --- a/source/gameengine/GameLogic/SCA_IObject.cpp +++ /dev/null @@ -1,349 +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/GameLogic/SCA_IObject.cpp - * \ingroup gamelogic - */ - -#include -#include - -#include "SCA_IObject.h" -#include "SCA_ISensor.h" -#include "SCA_IController.h" -#include "SCA_IActuator.h" -#include "MT_Point3.h" -#include "EXP_ListValue.h" - -MT_Point3 SCA_IObject::m_sDummy=MT_Point3(0,0,0); -SG_QList SCA_IObject::m_activeBookmarkedControllers; - -SCA_IObject::SCA_IObject(): - CValue(), - m_initState(0), - m_state(0), - m_firstState(NULL) -{ - m_suspended = false; -} - -SCA_IObject::~SCA_IObject() -{ - SCA_SensorList::iterator its; - for (its = m_sensors.begin(); !(its == m_sensors.end()); ++its) - { - //Use Delete for sensor to ensure proper cleaning - (*its)->Delete(); - //((CValue*)(*its))->Release(); - } - SCA_ControllerList::iterator itc; - for (itc = m_controllers.begin(); !(itc == m_controllers.end()); ++itc) - { - //Use Delete for controller to ensure proper cleaning (expression controller) - (*itc)->Delete(); - //((CValue*)(*itc))->Release(); - } - SCA_ActuatorList::iterator ita; - for (ita = m_registeredActuators.begin(); !(ita==m_registeredActuators.end()); ++ita) - { - (*ita)->UnlinkObject(this); - } - for (ita = m_actuators.begin(); !(ita==m_actuators.end()); ++ita) - { - (*ita)->Delete(); - } - - SCA_ObjectList::iterator ito; - for (ito = m_registeredObjects.begin(); !(ito==m_registeredObjects.end()); ++ito) - { - (*ito)->UnlinkObject(this); - } - - //T_InterpolatorList::iterator i; - //for (i = m_interpolators.begin(); !(i == m_interpolators.end()); ++i) { - // delete *i; - //} -} - -void SCA_IObject::AddSensor(SCA_ISensor* act) -{ - act->AddRef(); - m_sensors.push_back(act); -} - - - -void SCA_IObject::AddController(SCA_IController* act) -{ - act->AddRef(); - m_controllers.push_back(act); -} - - - -void SCA_IObject::AddActuator(SCA_IActuator* act) -{ - act->AddRef(); - m_actuators.push_back(act); -} - -void SCA_IObject::RegisterActuator(SCA_IActuator* act) -{ - // don't increase ref count, it would create dead lock - m_registeredActuators.push_back(act); -} - -void SCA_IObject::UnregisterActuator(SCA_IActuator* act) -{ - SCA_ActuatorList::iterator ita; - for (ita = m_registeredActuators.begin(); ita != m_registeredActuators.end(); ++ita) - { - if ((*ita) == act) { - (*ita) = m_registeredActuators.back(); - m_registeredActuators.pop_back(); - break; - } - } -} - -void SCA_IObject::RegisterObject(SCA_IObject* obj) -{ - // one object may be registered multiple times via constraint target - // store multiple reference, this will serve as registration counter - m_registeredObjects.push_back(obj); -} - -void SCA_IObject::UnregisterObject(SCA_IObject* obj) -{ - SCA_ObjectList::iterator ito; - for (ito = m_registeredObjects.begin(); ito != m_registeredObjects.end(); ++ito) - { - if ((*ito) == obj) { - (*ito) = m_registeredObjects.back(); - m_registeredObjects.pop_back(); - break; - } - } -} - -void SCA_IObject::ReParentLogic() -{ - SCA_ActuatorList& oldactuators = GetActuators(); - int act = 0; - SCA_ActuatorList::iterator ita; - for (ita = oldactuators.begin(); !(ita==oldactuators.end()); ++ita) - { - SCA_IActuator* newactuator = (SCA_IActuator*) (*ita)->GetReplica(); - newactuator->ReParent(this); - // actuators are initially not connected to any controller - newactuator->SetActive(false); - newactuator->ClrLink(); - oldactuators[act++] = newactuator; - } - - SCA_ControllerList& oldcontrollers = GetControllers(); - int con = 0; - SCA_ControllerList::iterator itc; - for (itc = oldcontrollers.begin(); !(itc==oldcontrollers.end()); ++itc) - { - SCA_IController* newcontroller = (SCA_IController*)(*itc)->GetReplica(); - newcontroller->ReParent(this); - newcontroller->SetActive(false); - oldcontrollers[con++]=newcontroller; - - } - // convert sensors last so that actuators are already available for Actuator sensor - SCA_SensorList& oldsensors = GetSensors(); - int sen = 0; - SCA_SensorList::iterator its; - for (its = oldsensors.begin(); !(its==oldsensors.end()); ++its) - { - SCA_ISensor* newsensor = (SCA_ISensor*)(*its)->GetReplica(); - newsensor->ReParent(this); - newsensor->SetActive(false); - // sensors are initially not connected to any controller - newsensor->ClrLink(); - oldsensors[sen++] = newsensor; - } - - // a new object cannot be client of any actuator - m_registeredActuators.clear(); - m_registeredObjects.clear(); -} - - - -SCA_ISensor* SCA_IObject::FindSensor(const STR_String& sensorname) -{ - SCA_ISensor* foundsensor = NULL; - - for (SCA_SensorList::iterator its = m_sensors.begin();!(its==m_sensors.end());++its) - { - if ((*its)->GetName() == sensorname) - { - foundsensor = (*its); - break; - } - } - return foundsensor; -} - - - -SCA_IController* SCA_IObject::FindController(const STR_String& controllername) -{ - SCA_IController* foundcontroller = NULL; - - for (SCA_ControllerList::iterator itc = m_controllers.begin();!(itc==m_controllers.end());++itc) - { - if ((*itc)->GetName() == controllername) - { - foundcontroller = (*itc); - break; - } - } - return foundcontroller; -} - - - -SCA_IActuator* SCA_IObject::FindActuator(const STR_String& actuatorname) -{ - SCA_IActuator* foundactuator = NULL; - - for (SCA_ActuatorList::iterator ita = m_actuators.begin();!(ita==m_actuators.end());++ita) - { - if ((*ita)->GetName() == actuatorname) - { - foundactuator = (*ita); - break; - } - } - - return foundactuator; -} - - -void SCA_IObject::Suspend() -{ - if ((!m_ignore_activity_culling) - && (!m_suspended)) { - m_suspended = true; - /* flag suspend for all sensors */ - SCA_SensorList::iterator i = m_sensors.begin(); - while (i != m_sensors.end()) { - (*i)->Suspend(); - ++i; - } - } -} - - - -void SCA_IObject::Resume(void) -{ - if (m_suspended) { - m_suspended = false; - /* unflag suspend for all sensors */ - SCA_SensorList::iterator i = m_sensors.begin(); - while (i != m_sensors.end()) { - (*i)->Resume(); - ++i; - } - } -} - -void SCA_IObject::SetState(unsigned int state) -{ - unsigned int tmpstate; - SCA_ControllerList::iterator contit; - - // we will update the state in two steps: - // 1) set the new state bits that are 1 - // 2) clr the new state bits that are 0 - // This to ensure continuity if a sensor is attached to two states - // that are switching state: no need to deactive and reactive the sensor - - tmpstate = m_state | state; - if (tmpstate != m_state) - { - // update the status of the controllers - for (contit = m_controllers.begin(); contit != m_controllers.end(); ++contit) - { - (*contit)->ApplyState(tmpstate); - } - } - m_state = state; - if (m_state != tmpstate) - { - for (contit = m_controllers.begin(); contit != m_controllers.end(); ++contit) - { - (*contit)->ApplyState(m_state); - } - } -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject SCA_IObject::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "SCA_IObject", - 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 SCA_IObject::Methods[] = { - //{"setOrientation", (PyCFunction) SCA_IObject::sPySetOrientation, METH_VARARGS}, - //{"getOrientation", (PyCFunction) SCA_IObject::sPyGetOrientation, METH_VARARGS}, - {NULL,NULL} //Sentinel -}; - -PyAttributeDef SCA_IObject::Attributes[] = { - { NULL } //Sentinel -}; - -#endif // WITH_PYTHON diff --git a/source/gameengine/GameLogic/SCA_IObject.h b/source/gameengine/GameLogic/SCA_IObject.h deleted file mode 100644 index 29a21fd8708..00000000000 --- a/source/gameengine/GameLogic/SCA_IObject.h +++ /dev/null @@ -1,229 +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 SCA_IObject.h - * \ingroup gamelogic - * \brief An abstract object that has some logic, python scripting and - * reference counting Note: transformation stuff has been moved to - * SceneGraph - */ - -#ifndef __SCA_IOBJECT_H__ -#define __SCA_IOBJECT_H__ - -#include "EXP_Value.h" -#include - -class SCA_IObject; -class SCA_ISensor; -class SCA_IController; -class SCA_IActuator; - -#ifdef WITH_PYTHON -template T PyVecTo(PyObject *); -#endif - -typedef std::vector SCA_SensorList; -typedef std::vector SCA_ControllerList; -typedef std::vector SCA_ActuatorList; -typedef std::vector SCA_ObjectList; - -class SCA_IObject : public CValue -{ - - Py_Header - -protected: - friend class KX_StateActuator; - friend class SCA_IActuator; - friend class SCA_IController; - SCA_SensorList m_sensors; - SCA_ControllerList m_controllers; - SCA_ActuatorList m_actuators; - SCA_ActuatorList m_registeredActuators; // actuators that use a pointer to this object - SCA_ObjectList m_registeredObjects; // objects that hold reference to this object - - // SG_Dlist: element of objects with active actuators - // Head: SCA_LogicManager::m_activeActuators - // SG_QList: Head of active actuators list on this object - // Elements: SCA_IActuator - SG_QList m_activeActuators; - // SG_Dlist: element of list os lists with active controllers - // Head: SCA_LogicManager::m_activeControllers - // SG_QList: Head of active controller list on this object - // Elements: SCA_IController - SG_QList m_activeControllers; - // SG_Dlist: element of list of lists of active controllers - // Head: SCA_LogicManager::m_activeControllers - // SG_QList: Head of active bookmarked controller list globally - // Elements: SCA_IController with bookmark option - static SG_QList m_activeBookmarkedControllers; - - static class MT_Point3 m_sDummy; - - /** - * Ignore activity culling requests? - */ - bool m_ignore_activity_culling; - - /** - * Ignore updates? - */ - bool m_suspended; - - /** - * init state of object (used when object is created) - */ - unsigned int m_initState; - - /** - * current state = bit mask of state that are active - */ - unsigned int m_state; - - /** - * pointer inside state actuator list for sorting - */ - SG_QList* m_firstState; - -public: - - SCA_IObject(); - virtual ~SCA_IObject(); - - SCA_ControllerList& GetControllers() - { - return m_controllers; - } - SCA_SensorList& GetSensors() - { - return m_sensors; - } - SCA_ActuatorList& GetActuators() - { - return m_actuators; - } - SG_QList& GetActiveActuators() - { - return m_activeActuators; - } - - void AddSensor(SCA_ISensor* act); - void ReserveSensor(int num) - { - m_sensors.reserve(num); - } - void AddController(SCA_IController* act); - void ReserveController(int num) - { - m_controllers.reserve(num); - } - void AddActuator(SCA_IActuator* act); - void ReserveActuator(int num) - { - m_actuators.reserve(num); - } - void RegisterActuator(SCA_IActuator* act); - void UnregisterActuator(SCA_IActuator* act); - - void RegisterObject(SCA_IObject* objs); - void UnregisterObject(SCA_IObject* objs); - /** - * UnlinkObject(...) - * this object is informed that one of the object to which it holds a reference is deleted - * returns true if there was indeed a reference. - */ - virtual bool UnlinkObject(SCA_IObject* clientobj) { return false; } - - SCA_ISensor* FindSensor(const STR_String& sensorname); - SCA_IActuator* FindActuator(const STR_String& actuatorname); - SCA_IController* FindController(const STR_String& controllername); - - void SetCurrentTime(float currentTime) {} - - virtual void ReParentLogic(); - - /** - * Set whether or not to ignore activity culling requests - */ - void SetIgnoreActivityCulling(bool b) - { - m_ignore_activity_culling = b; - } - - /** - * Set whether or not this object wants to ignore activity culling - * requests - */ - bool GetIgnoreActivityCulling() - { - return m_ignore_activity_culling; - } - - /** - * Suspend all progress. - */ - void Suspend(void); - - /** - * Resume progress - */ - void Resume(void); - - /** - * Set init state - */ - void SetInitState(unsigned int initState) { m_initState = initState; } - - /** - * initialize the state when object is created - */ - void ResetState(void) { SetState(m_initState); } - - /** - * Set the object state - */ - void SetState(unsigned int state); - - /** - * Get the object state - */ - unsigned int GetState(void) { return m_state; } - -// const class MT_Point3& ConvertPythonPylist(PyObject *pylist); - - virtual int GetGameObjectType() {return -1;} - - typedef enum ObjectTypes { - OBJ_ARMATURE=0, - OBJ_CAMERA=1, - OBJ_LIGHT=2, - OBJ_TEXT=3 - } ObjectTypes; - -}; - -#endif /* __SCA_IOBJECT_H__ */ diff --git a/source/gameengine/GameLogic/SCA_IScene.cpp b/source/gameengine/GameLogic/SCA_IScene.cpp deleted file mode 100644 index a4c905096d7..00000000000 --- a/source/gameengine/GameLogic/SCA_IScene.cpp +++ /dev/null @@ -1,145 +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/GameLogic/SCA_IScene.cpp - * \ingroup gamelogic - */ - - -#include "SCA_IScene.h" -#include "EXP_Value.h" - -SCA_DebugProp::SCA_DebugProp(): m_obj(NULL) -{ -} - -SCA_DebugProp::~SCA_DebugProp() -{ - if (m_obj) - m_obj->Release(); -} - -SCA_IScene::SCA_IScene() -{ -} - -void SCA_IScene::RemoveAllDebugProperties() -{ - for (std::vector::iterator it = m_debugList.begin(); - !(it==m_debugList.end());++it) - { - delete (*it); - } - m_debugList.clear(); -} - - -SCA_IScene::~SCA_IScene() -{ - RemoveAllDebugProperties(); -} - - -std::vector& SCA_IScene::GetDebugProperties() -{ - return m_debugList; -} - - -bool SCA_IScene::PropertyInDebugList( class CValue *gameobj, const STR_String &name ) -{ - for (std::vector::iterator it = m_debugList.begin(); - !(it==m_debugList.end());++it) { - STR_String debugname = (*it)->m_name; - CValue *debugobj = (*it)->m_obj; - - if (debugobj == gameobj && debugname == name) - return true; - } - return false; -} - - -bool SCA_IScene::ObjectInDebugList( class CValue *gameobj ) -{ - for (std::vector::iterator it = m_debugList.begin(); - !(it==m_debugList.end());++it) { - CValue* debugobj = (*it)->m_obj; - - if (debugobj == gameobj) - return true; - } - return false; -} - - -void SCA_IScene::AddDebugProperty(class CValue* debugprop, - const STR_String &name) -{ - if (m_debugList.size() < DEBUG_MAX_DISPLAY) { - SCA_DebugProp* dprop = new SCA_DebugProp(); - dprop->m_obj = debugprop; - debugprop->AddRef(); - dprop->m_name = name; - m_debugList.push_back(dprop); - } -} - - -void SCA_IScene::RemoveDebugProperty(class CValue *gameobj, - const STR_String &name) -{ - vector::iterator it = m_debugList.begin(); - while (it != m_debugList.end()) { - STR_String debugname = (*it)->m_name; - CValue *debugobj = (*it)->m_obj; - - if (debugobj == gameobj && debugname == name) { - delete (*it); - m_debugList.erase(it); - break; - } - ++it; - } -} - - -void SCA_IScene::RemoveObjectDebugProperties(class CValue* gameobj) -{ - vector::iterator it = m_debugList.begin(); - while (it != m_debugList.end()) { - CValue* debugobj = (*it)->m_obj; - - if (debugobj == gameobj) { - delete (*it); - m_debugList.erase(it); - continue; - } - ++it; - } -} - diff --git a/source/gameengine/GameLogic/SCA_IScene.h b/source/gameengine/GameLogic/SCA_IScene.h deleted file mode 100644 index b76b5636b13..00000000000 --- a/source/gameengine/GameLogic/SCA_IScene.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 SCA_IScene.h - * \ingroup gamelogic - */ - -#ifndef __SCA_ISCENE_H__ -#define __SCA_ISCENE_H__ - -#include - -#include "STR_String.h" -#include "RAS_2DFilterManager.h" - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -#define DEBUG_MAX_DISPLAY 100 - -struct SCA_DebugProp -{ - class CValue* m_obj; - STR_String m_name; - SCA_DebugProp(); - ~SCA_DebugProp(); -}; - -class SCA_IScene -{ - std::vector m_debugList; -public: - SCA_IScene(); - virtual ~SCA_IScene(); - virtual class SCA_IObject* AddReplicaObject(class CValue* gameobj, - class CValue* locationobj, - int lifespan=0)=0; - virtual void RemoveObject(class CValue* gameobj)=0; - virtual void DelayedRemoveObject(class CValue* gameobj)=0; - //virtual void DelayedReleaseObject(class CValue* gameobj)=0; - - virtual void ReplaceMesh(class CValue* gameobj, - void* meshobj, bool use_gfx, bool use_phys)=0; - std::vector& GetDebugProperties(); - bool PropertyInDebugList(class CValue *gameobj, const STR_String &name); - bool ObjectInDebugList(class CValue *gameobj); - void RemoveAllDebugProperties(); - void AddDebugProperty(class CValue* debugprop, const STR_String &name); - void RemoveDebugProperty(class CValue *gameobj, const STR_String &name); - void RemoveObjectDebugProperties(class CValue* gameobj); - - virtual void Update2DFilter(std::vector& propNames, void* gameObj, - RAS_2DFilterManager::RAS_2DFILTER_MODE filtermode, - int pass, STR_String& text) {} - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_IScene") -#endif -}; - -#endif /* __SCA_ISCENE_H__ */ diff --git a/source/gameengine/GameLogic/SCA_ISensor.cpp b/source/gameengine/GameLogic/SCA_ISensor.cpp deleted file mode 100644 index 66dd69f93c4..00000000000 --- a/source/gameengine/GameLogic/SCA_ISensor.cpp +++ /dev/null @@ -1,471 +0,0 @@ -/* - * Abstract class for sensor logic bricks - * - * - * ***** 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/GameLogic/SCA_ISensor.cpp - * \ingroup gamelogic - */ - - -#include - -#include "SCA_ISensor.h" -#include "SCA_EventManager.h" -#include "SCA_LogicManager.h" -// needed for IsTriggered() -#include "SCA_PythonController.h" - -#include - -/* Native functions */ -void SCA_ISensor::ReParent(SCA_IObject* parent) -{ - SCA_ILogicBrick::ReParent(parent); - // will be done when the sensor is activated - //m_eventmgr->RegisterSensor(this); - //this->SetActive(false); -} - - -SCA_ISensor::SCA_ISensor(SCA_IObject* gameobj, - class SCA_EventManager* eventmgr) : - SCA_ILogicBrick(gameobj) -{ - m_links = 0; - m_suspended = false; - m_invert = false; - m_level = false; - m_tap = false; - m_reset = false; - m_pos_ticks = 0; - m_neg_ticks = 0; - m_pos_pulsemode = false; - m_neg_pulsemode = false; - m_skipped_ticks = 0; - m_state = false; - m_prev_state = false; - - m_eventmgr = eventmgr; -} - - -SCA_ISensor::~SCA_ISensor() -{ - // intentionally empty -} - -void SCA_ISensor::ProcessReplica() -{ - SCA_ILogicBrick::ProcessReplica(); - m_linkedcontrollers.clear(); -} - -bool SCA_ISensor::IsPositiveTrigger() -{ - bool result = false; - - if (m_eventval) { - result = (m_eventval->GetNumber() != 0.0); - } - if (m_invert) { - result = !result; - } - - return result; -} - -void SCA_ISensor::SetPulseMode(bool posmode, - bool negmode, - int skippedticks) -{ - m_pos_pulsemode = posmode; - m_neg_pulsemode = negmode; - m_skipped_ticks = skippedticks; -} - -void SCA_ISensor::SetInvert(bool inv) -{ - m_invert = inv; -} - -void SCA_ISensor::SetLevel(bool lvl) -{ - m_level = lvl; -} - -void SCA_ISensor::SetTap(bool tap) -{ - m_tap = tap; -} - - -double SCA_ISensor::GetNumber() -{ - return GetState(); -} - -void SCA_ISensor::Suspend() -{ - m_suspended = true; -} - -bool SCA_ISensor::IsSuspended() -{ - return m_suspended; -} - -void SCA_ISensor::Resume() -{ - m_suspended = false; -} - -void SCA_ISensor::Init() -{ - printf("Sensor %s has no init function, please report this bug to Blender.org\n", m_name.Ptr()); -} - -void SCA_ISensor::DecLink() -{ - m_links--; - if (m_links < 0) - { - printf("Warning: sensor %s has negative m_links: %d\n", m_name.Ptr(), m_links); - m_links = 0; - } - if (!m_links) - { - // sensor is detached from all controllers, remove it from manager - UnregisterToManager(); - } -} - -void SCA_ISensor::RegisterToManager() -{ - // sensor is just activated, initialize it - Init(); - m_state = false; - m_eventmgr->RegisterSensor(this); -} - -void SCA_ISensor::Replace_EventManager(class SCA_LogicManager* logicmgr) -{ - if (m_links) { /* true if we're used currently */ - - m_eventmgr->RemoveSensor(this); - m_eventmgr= logicmgr->FindEventManager(m_eventmgr->GetType()); - m_eventmgr->RegisterSensor(this); - } - else { - m_eventmgr= logicmgr->FindEventManager(m_eventmgr->GetType()); - } -} - -void SCA_ISensor::LinkToController(SCA_IController* controller) -{ - m_linkedcontrollers.push_back(controller); -} - -void SCA_ISensor::UnlinkController(SCA_IController* controller) -{ - std::vector::iterator contit; - for (contit = m_linkedcontrollers.begin();!(contit==m_linkedcontrollers.end());++contit) - { - if ((*contit) == controller) - { - *contit = m_linkedcontrollers.back(); - m_linkedcontrollers.pop_back(); - return; - } - } - printf("Missing link from sensor %s:%s to controller %s:%s\n", - m_gameobj->GetName().ReadPtr(), GetName().ReadPtr(), - controller->GetParent()->GetName().ReadPtr(), controller->GetName().ReadPtr()); -} - -void SCA_ISensor::UnlinkAllControllers() -{ - std::vector::iterator contit; - for (contit = m_linkedcontrollers.begin();!(contit==m_linkedcontrollers.end());++contit) - { - (*contit)->UnlinkSensor(this); - } - m_linkedcontrollers.clear(); -} - -void SCA_ISensor::UnregisterToManager() -{ - m_eventmgr->RemoveSensor(this); - m_links = 0; -} - -void SCA_ISensor::ActivateControllers(class SCA_LogicManager* logicmgr) -{ - for (vector::const_iterator c= m_linkedcontrollers.begin(); - c!=m_linkedcontrollers.end();++c) - { - SCA_IController* contr = *c; - if (contr->IsActive()) - logicmgr->AddTriggeredController(contr, this); - } -} - -void SCA_ISensor::Activate(class SCA_LogicManager* logicmgr) -{ - - // calculate if a __triggering__ is wanted - // don't evaluate a sensor that is not connected to any controller - if (m_links && !m_suspended) { - bool result = this->Evaluate(); - // store the state for the rest of the logic system - m_prev_state = m_state; - m_state = this->IsPositiveTrigger(); - if (result) { - // the sensor triggered this frame - if (m_state || !m_tap) { - ActivateControllers(logicmgr); - // reset these counters so that pulse are synchronized with transition - m_pos_ticks = 0; - m_neg_ticks = 0; - } else - { - result = false; - } - } else - { - /* First, the pulsing behavior, if pulse mode is - * active. It seems something goes wrong if pulse mode is - * not set :( */ - if (m_pos_pulsemode) { - m_pos_ticks++; - if (m_pos_ticks > m_skipped_ticks) { - if ( m_state ) - { - ActivateControllers(logicmgr); - result = true; - } - m_pos_ticks = 0; - } - } - // negative pulse doesn't make sense in tap mode, skip - if (m_neg_pulsemode && !m_tap) - { - m_neg_ticks++; - if (m_neg_ticks > m_skipped_ticks) { - if (!m_state ) - { - ActivateControllers(logicmgr); - result = true; - } - m_neg_ticks = 0; - } - } - } - if (m_tap) - { - // in tap mode: we send always a negative pulse immediately after a positive pulse - if (!result) - { - // the sensor did not trigger on this frame - if (m_prev_state) - { - // but it triggered on previous frame => send a negative pulse - ActivateControllers(logicmgr); - result = true; - } - // in any case, absence of trigger means sensor off - m_state = false; - } - } - if (!result && m_level) - { - // This level sensor is connected to at least one controller that was just made - // active but it did not generate an event yet, do it now to those controllers only - for (vector::const_iterator c= m_linkedcontrollers.begin(); - c!=m_linkedcontrollers.end();++c) - { - SCA_IController* contr = *c; - if (contr->IsJustActivated()) - logicmgr->AddTriggeredController(contr, this); - } - } - } -} - -#ifdef WITH_PYTHON - -/* ----------------------------------------------- */ -/* Python Functions */ -/* ----------------------------------------------- */ - -KX_PYMETHODDEF_DOC_NOARGS(SCA_ISensor, reset, -"reset()\n" -"\tReset sensor internal state, effect depends on the type of sensor and settings.\n" -"\tThe sensor is put in its initial state as if it was just activated.\n") -{ - Init(); - m_prev_state = false; - Py_RETURN_NONE; -} - -/* ----------------------------------------------- */ -/* Python Integration Hooks */ -/* ----------------------------------------------- */ - -PyTypeObject SCA_ISensor::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "SCA_ISensor", - 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_ILogicBrick::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef SCA_ISensor::Methods[] = { - KX_PYMETHODTABLE_NOARGS(SCA_ISensor, reset), - {NULL,NULL} //Sentinel -}; - -PyAttributeDef SCA_ISensor::Attributes[] = { - KX_PYATTRIBUTE_BOOL_RW("usePosPulseMode",SCA_ISensor,m_pos_pulsemode), - KX_PYATTRIBUTE_BOOL_RW("useNegPulseMode",SCA_ISensor,m_neg_pulsemode), - KX_PYATTRIBUTE_INT_RW("skippedTicks",0,100000,true,SCA_ISensor,m_skipped_ticks), - KX_PYATTRIBUTE_BOOL_RW("invert",SCA_ISensor,m_invert), - KX_PYATTRIBUTE_BOOL_RW_CHECK("level",SCA_ISensor,m_level,pyattr_check_level), - KX_PYATTRIBUTE_BOOL_RW_CHECK("tap",SCA_ISensor,m_tap,pyattr_check_tap), - KX_PYATTRIBUTE_RO_FUNCTION("triggered", SCA_ISensor, pyattr_get_triggered), - KX_PYATTRIBUTE_RO_FUNCTION("positive", SCA_ISensor, pyattr_get_positive), - KX_PYATTRIBUTE_RO_FUNCTION("status", SCA_ISensor, pyattr_get_status), - KX_PYATTRIBUTE_RO_FUNCTION("pos_ticks", SCA_ISensor, pyattr_get_posTicks), - KX_PYATTRIBUTE_RO_FUNCTION("neg_ticks", SCA_ISensor, pyattr_get_negTicks), - KX_PYATTRIBUTE_RW_FUNCTION("frequency", SCA_ISensor, pyattr_get_frequency, pyattr_set_frequency), - { NULL } //Sentinel -}; - - -PyObject *SCA_ISensor::pyattr_get_triggered(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_ISensor* self = static_cast(self_v); - bool retval = false; - if (SCA_PythonController::m_sCurrentController) - retval = SCA_PythonController::m_sCurrentController->IsTriggered(self); - return PyBool_FromLong(retval); -} - -PyObject *SCA_ISensor::pyattr_get_positive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_ISensor* self = static_cast(self_v); - return PyBool_FromLong(self->GetState()); -} - -PyObject *SCA_ISensor::pyattr_get_status(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_ISensor* self = static_cast(self_v); - int status = 0; - if (self->GetState()) - { - if (self->GetState() == self->GetPrevState()) - { - status = 2; - } - else - { - status = 1; - } - } - else if (self->GetState() != self->GetPrevState()) - { - status = 3; - } - return PyLong_FromLong(status); -} - -PyObject *SCA_ISensor::pyattr_get_posTicks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_ISensor* self = static_cast(self_v); - return PyLong_FromLong(self->GetPosTicks()); -} - -PyObject *SCA_ISensor::pyattr_get_negTicks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_ISensor* self = static_cast(self_v); - return PyLong_FromLong(self->GetNegTicks()); -} - -int SCA_ISensor::pyattr_check_level(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_ISensor* self = static_cast(self_v); - if (self->m_level) - self->m_tap = false; - return 0; -} - -int SCA_ISensor::pyattr_check_tap(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_ISensor* self = static_cast(self_v); - if (self->m_tap) - self->m_level = false; - return 0; -} - -PyObject *SCA_ISensor::pyattr_get_frequency(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_ISensor *self = static_cast(self_v); - ShowDeprecationWarning("SCA_ISensor.frequency", "SCA_ISensor.skippedTicks"); - return PyLong_FromLong(self->m_skipped_ticks); -} - -int SCA_ISensor::pyattr_set_frequency(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - SCA_ISensor *self = static_cast(self_v); - ShowDeprecationWarning("SCA_ISensor.frequency", "SCA_ISensor.skippedTicks"); - if (PyLong_Check(value)) { - self->m_skipped_ticks = PyLong_AsLong(value); - return PY_SET_ATTR_SUCCESS; - } - else { - PyErr_SetString(PyExc_TypeError, "sensor.frequency = int: Sensor, expected an integer"); - return PY_SET_ATTR_FAIL; - } -} -#endif // WITH_PYTHON - -/* eof */ diff --git a/source/gameengine/GameLogic/SCA_ISensor.h b/source/gameengine/GameLogic/SCA_ISensor.h deleted file mode 100644 index 1e82f3ab11f..00000000000 --- a/source/gameengine/GameLogic/SCA_ISensor.h +++ /dev/null @@ -1,220 +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 SCA_ISensor.h - * \ingroup gamelogic - * \brief Interface Class for all logic Sensors. Implements - * pulsemode and pulsefrequency, and event suppression. - */ - -#ifndef __SCA_ISENSOR_H__ -#define __SCA_ISENSOR_H__ - -#include "SCA_IController.h" - -#include - -/** - * Interface Class for all logic Sensors. Implements - * pulsemode,pulsefrequency - * Use of SG_DList element: link sensors to their respective event manager - * Head: SCA_EventManager::m_sensors - * Use of SG_QList element: not used - */ -class SCA_ISensor : public SCA_ILogicBrick -{ - Py_Header -protected: - class SCA_EventManager* m_eventmgr; - - /** Pulse positive pulses? */ - bool m_pos_pulsemode; - - /** Pulse negative pulses? */ - bool m_neg_pulsemode; - - /** Number of skipped ticks between two active pulses. */ - int m_skipped_ticks; - - /** Number of ticks since the last positive pulse. */ - int m_pos_ticks; - - /** Number of ticks since the last negative pulse. */ - int m_neg_ticks; - - /** invert the output signal*/ - bool m_invert; - - /** detect level instead of edge*/ - bool m_level; - - /** tap mode */ - bool m_tap; - - /** sensor has been reset */ - bool m_reset; - - /** Sensor must ignore updates? */ - bool m_suspended; - - /** number of connections to controller */ - int m_links; - - /** current sensor state */ - bool m_state; - - /** previous state (for tap option) */ - bool m_prev_state; - - std::vector m_linkedcontrollers; - -public: - - enum sensortype { - ST_NONE = 0, - ST_TOUCH, - ST_NEAR, - ST_RADAR, - // to be updated as needed - }; - - SCA_ISensor(SCA_IObject* gameobj, - class SCA_EventManager* eventmgr); - ~SCA_ISensor(); - virtual void ReParent(SCA_IObject* parent); - - /** Because we want sensors to share some behavior, the Activate has */ - /* an implementation on this level. It requires an evaluate on the lower */ - /* level of individual sensors. Mapping the old activate()s is easy. */ - /* The IsPosTrig() also has to change, to keep things consistent. */ - void Activate(class SCA_LogicManager* logicmgr); - virtual bool Evaluate() = 0; - virtual bool IsPositiveTrigger(); - virtual void Init(); - - virtual CValue* GetReplica()=0; - - /** Set parameters for the pulsing behavior. - * \param posmode Trigger positive pulses? - * \param negmode Trigger negative pulses? - * \param freq Frequency to use when doing pulsing. - */ - void SetPulseMode(bool posmode, - bool negmode, - int skippedticks); - - /** Set inversion of pulses on or off. */ - void SetInvert(bool inv); - /** set the level detection on or off */ - void SetLevel(bool lvl); - void SetTap(bool tap); - - virtual void RegisterToManager(); - virtual void UnregisterToManager(); - void Replace_EventManager(class SCA_LogicManager* logicmgr); - void ReserveController(int num) - { - m_linkedcontrollers.reserve(num); - } - void LinkToController(SCA_IController* controller); - void UnlinkController(SCA_IController* controller); - void UnlinkAllControllers(); - void ActivateControllers(class SCA_LogicManager* logicmgr); - - virtual void ProcessReplica(); - - virtual double GetNumber(); - - virtual sensortype GetSensorType() { return ST_NONE; } - - /** Stop sensing for a while. */ - void Suspend(); - - /** Is this sensor switched off? */ - bool IsSuspended(); - - /** get the state of the sensor: positive or negative */ - bool GetState() - { - return m_state; - } - - /** get the previous state of the sensor: positive or negative */ - bool GetPrevState() - { - return m_prev_state; - } - - /** get the number of ticks since the last positive pulse */ - int GetPosTicks() - { - return m_pos_ticks; - } - - /** get the number of ticks since the last negative pulse */ - int GetNegTicks() - { - return m_neg_ticks; - } - - /** Resume sensing. */ - void Resume(); - - void ClrLink() - { m_links = 0; } - void IncLink() - { if (!m_links++) RegisterToManager(); } - void DecLink(); - bool IsNoLink() const - { return !m_links; } - -#ifdef WITH_PYTHON - /* Python functions: */ - KX_PYMETHOD_DOC_NOARGS(SCA_ISensor,reset); - - static PyObject* pyattr_get_triggered(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_positive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_status(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_posTicks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_negTicks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_frequency(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_frequency(void *self_v, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - - static int pyattr_check_level(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_check_tap(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - - enum SensorStatus { - KX_SENSOR_INACTIVE = 0, - KX_SENSOR_JUST_ACTIVATED, - KX_SENSOR_ACTIVE, - KX_SENSOR_JUST_DEACTIVATED - - }; -#endif /* WITH_PYTHON */ -}; - -#endif /* __SCA_ISENSOR_H__ */ diff --git a/source/gameengine/GameLogic/SCA_JoystickManager.cpp b/source/gameengine/GameLogic/SCA_JoystickManager.cpp deleted file mode 100644 index 780e4e9ce88..00000000000 --- a/source/gameengine/GameLogic/SCA_JoystickManager.cpp +++ /dev/null @@ -1,92 +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/GameLogic/SCA_JoystickManager.cpp - * \ingroup gamelogic - */ - -#include "SCA_JoystickSensor.h" -#include "SCA_JoystickManager.h" -#include "SCA_LogicManager.h" -//#include -#include "SCA_ISensor.h" - -//using namespace std; - - -SCA_JoystickManager::SCA_JoystickManager(class SCA_LogicManager* logicmgr) - : SCA_EventManager(logicmgr, JOY_EVENTMGR) -{ - int i; - for (i=0; iReleaseInstance(); - } -} - - -void SCA_JoystickManager::NextFrame(double curtime,double deltatime) -{ - // We should always handle events in case we want to grab them with Python -#ifdef WITH_SDL - SCA_Joystick::HandleEvents(); /* Handle all SDL Joystick events */ -#endif - - if (m_sensors.Empty()) { - return; - } - else { - ; - SG_DList::iterator it(m_sensors); - for (it.begin();!it.end();++it) - { - SCA_JoystickSensor* joysensor = *it; - if (!joysensor->IsSuspended()) - { - joysensor->Activate(m_logicmgr); - } - } - } -} - - -SCA_Joystick *SCA_JoystickManager::GetJoystickDevice( short int joyindex) -{ - /* - *Return the instance of SCA_Joystick for use - */ - return m_joystick[joyindex]; -} diff --git a/source/gameengine/GameLogic/SCA_JoystickManager.h b/source/gameengine/GameLogic/SCA_JoystickManager.h deleted file mode 100644 index 60dcaea4ef2..00000000000 --- a/source/gameengine/GameLogic/SCA_JoystickManager.h +++ /dev/null @@ -1,59 +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 SCA_JoystickManager.h - * \ingroup gamelogic - */ - -#ifndef __SCA_JOYSTICKMANAGER_H__ -#define __SCA_JOYSTICKMANAGER_H__ - -#include "SCA_EventManager.h" -#include "Joystick/SCA_Joystick.h" -#include - -using namespace std; -class SCA_JoystickManager : public SCA_EventManager -{ - /** - * SDL Joystick Class Instance - */ - SCA_Joystick *m_joystick[JOYINDEX_MAX]; -public: - SCA_JoystickManager(class SCA_LogicManager* logicmgr); - virtual ~SCA_JoystickManager(); - virtual void NextFrame(double curtime,double deltatime); - SCA_Joystick* GetJoystickDevice(short int joyindex); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_JoystickManager") -#endif -}; - -#endif - diff --git a/source/gameengine/GameLogic/SCA_JoystickSensor.cpp b/source/gameengine/GameLogic/SCA_JoystickSensor.cpp deleted file mode 100644 index 56df9692e72..00000000000 --- a/source/gameengine/GameLogic/SCA_JoystickSensor.cpp +++ /dev/null @@ -1,428 +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/GameLogic/SCA_JoystickSensor.cpp - * \ingroup gamelogic - */ - -#include "SCA_JoystickManager.h" -#include "SCA_JoystickSensor.h" - -#include "SCA_EventManager.h" -#include "SCA_LogicManager.h" - -#include "EXP_PyObjectPlus.h" - -#include -#include -#include - - - -SCA_JoystickSensor::SCA_JoystickSensor(class SCA_JoystickManager* eventmgr, - SCA_IObject* gameobj, - short int joyindex, - short int joymode, - int axis, int axisf,int prec, - int button, - int hat, int hatf, bool allevents) - :SCA_ISensor(gameobj,eventmgr), - m_axis(axis), - m_axisf(axisf), - m_button(button), - m_hat(hat), - m_hatf(hatf), - m_precision(prec), - m_joymode(joymode), - m_joyindex(joyindex), - m_bAllEvents(allevents) -{ -/* -std::cout << " axis " << m_axis << std::endl; -std::cout << " axis flag " << m_axisf << std::endl; -std::cout << " precision " << m_precision << std::endl; -std::cout << " button " << m_button << std::endl; -std::cout << " hat " << m_hat << std::endl; -std::cout << " hat flag " << m_hatf << std::endl; -*/ - Init(); -} - -void SCA_JoystickSensor::Init() -{ - m_istrig=(m_invert)?1:0; - m_istrig_prev=0; - m_reset = true; -} - -SCA_JoystickSensor::~SCA_JoystickSensor() -{ -} - - -CValue* SCA_JoystickSensor::GetReplica() -{ - SCA_JoystickSensor* replica = new SCA_JoystickSensor(*this); - // this will copy properties and so on... - replica->ProcessReplica(); - replica->Init(); - return replica; -} - - -bool SCA_JoystickSensor::IsPositiveTrigger() -{ - bool result = m_istrig; - if (m_invert) - result = !result; - return result; -} - - -bool SCA_JoystickSensor::Evaluate() -{ - SCA_Joystick *js = ((SCA_JoystickManager *)m_eventmgr)->GetJoystickDevice(m_joyindex); - bool result = false; - bool reset = m_reset && m_level; - - if (js==NULL) /* no joystick - don't do anything */ - return false; - - m_reset = false; - - switch (m_joymode) { - case KX_JOYSENSORMODE_AXIS: - { - /* what is what! - * m_axisf == JOYAXIS_RIGHT, JOYAXIS_UP, JOYAXIS_DOWN, JOYAXIS_LEFT - * m_axisf == 1 == up - * m_axisf == 2 == left - * m_axisf == 3 == down - * - * numberof== m_axis (1-4), range is half of JOYAXIS_MAX since - * it assumes the axis joysticks are axis parirs (0,1), (2,3), etc - * also note that this starts at 1 where functions its used - * with expect a zero index. - */ - - if (!js->IsTrigAxis() && !reset) /* No events from SDL? - don't bother */ - return false; - - js->cSetPrecision(m_precision); - if (m_bAllEvents) { - if (js->aAxisPairIsPositive(m_axis-1)) { /* use zero based axis index internally */ - m_istrig = 1; - result = true; - } - else { - if (m_istrig) { - m_istrig = 0; - result = true; - } - } - } - else { - if (js->aAxisPairDirectionIsPositive(m_axis-1, m_axisf)) { /* use zero based axis index internally */ - m_istrig = 1; - result = true; - } - else { - if (m_istrig) { - m_istrig = 0; - result = true; - } - } - } - break; - } - case KX_JOYSENSORMODE_AXIS_SINGLE: - { - /* Like KX_JOYSENSORMODE_AXIS but don't pair up axis */ - if (!js->IsTrigAxis() && !reset) /* No events from SDL? - don't bother */ - return false; - - /* No need for 'm_bAllEvents' check here since were only checking 1 axis */ - js->cSetPrecision(m_precision); - if (js->aAxisIsPositive(m_axis-1)) { /* use zero based axis index internally */ - m_istrig = 1; - result = true; - } - else { - if (m_istrig) { - m_istrig = 0; - result = true; - } - } - break; - } - - case KX_JOYSENSORMODE_BUTTON: - { - /* what is what! - * m_button = the actual button in question - */ - if (!js->IsTrigButton() && !reset) /* No events from SDL? - don't bother */ - return false; - - if (( m_bAllEvents && js->aAnyButtonPressIsPositive()) || (!m_bAllEvents && js->aButtonPressIsPositive(m_button))) { - m_istrig = 1; - result = true; - } - else { - if (m_istrig) { - m_istrig = 0; - result = true; - } - } - break; - } - case KX_JOYSENSORMODE_HAT: - { - /* what is what! - * numberof = m_hat -- max 4 - * direction= m_hatf -- max 12 - */ - - if (!js->IsTrigHat() && !reset) /* No events from SDL? - don't bother */ - return false; - - if ((m_bAllEvents && js->GetHat(m_hat-1)) || js->aHatIsPositive(m_hat-1, m_hatf)) { - m_istrig = 1; - result = true; - } - else { - if (m_istrig) { - m_istrig = 0; - result = true; - } - } - break; - } - /* test for ball anyone ?*/ - default: - printf("Error invalid switch statement\n"); - break; - } - - /* if not all events are enabled, only send a positive pulse when - * the button state changes */ - if (!m_bAllEvents) { - if (m_istrig_prev == m_istrig) { - result = false; - } - else { - m_istrig_prev = m_istrig; - } - } - - if (reset) - result = true; - - return result; -} - - -bool SCA_JoystickSensor::isValid(SCA_JoystickSensor::KX_JOYSENSORMODE m) -{ - bool res = false; - res = ((m > KX_JOYSENSORMODE_NODEF) && (m < KX_JOYSENSORMODE_MAX)); - return res; -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject SCA_JoystickSensor::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "SCA_JoystickSensor", - 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 SCA_JoystickSensor::Methods[] = { - {"getButtonActiveList",(PyCFunction) SCA_JoystickSensor::sPyGetButtonActiveList, METH_NOARGS,(const char *)GetButtonActiveList_doc}, - {"getButtonStatus",(PyCFunction) SCA_JoystickSensor::sPyGetButtonStatus, METH_VARARGS,(const char *)GetButtonStatus_doc}, - {NULL,NULL} //Sentinel -}; - -PyAttributeDef SCA_JoystickSensor::Attributes[] = { - KX_PYATTRIBUTE_SHORT_RW("index",0,JOYINDEX_MAX-1,true,SCA_JoystickSensor,m_joyindex), - KX_PYATTRIBUTE_INT_RW("threshold",0,32768,true,SCA_JoystickSensor,m_precision), - KX_PYATTRIBUTE_INT_RW("button",0,100,false,SCA_JoystickSensor,m_button), - KX_PYATTRIBUTE_INT_LIST_RW_CHECK("axis",0,3,true,SCA_JoystickSensor,m_axis,2,CheckAxis), - KX_PYATTRIBUTE_INT_LIST_RW_CHECK("hat",0,12,true,SCA_JoystickSensor,m_hat,2,CheckHat), - KX_PYATTRIBUTE_RO_FUNCTION("axisValues", SCA_JoystickSensor, pyattr_get_axis_values), - KX_PYATTRIBUTE_RO_FUNCTION("axisSingle", SCA_JoystickSensor, pyattr_get_axis_single), - KX_PYATTRIBUTE_RO_FUNCTION("hatValues", SCA_JoystickSensor, pyattr_get_hat_values), - KX_PYATTRIBUTE_RO_FUNCTION("hatSingle", SCA_JoystickSensor, pyattr_get_hat_single), - KX_PYATTRIBUTE_RO_FUNCTION("numAxis", SCA_JoystickSensor, pyattr_get_num_axis), - KX_PYATTRIBUTE_RO_FUNCTION("numButtons", SCA_JoystickSensor, pyattr_get_num_buttons), - KX_PYATTRIBUTE_RO_FUNCTION("numHats", SCA_JoystickSensor, pyattr_get_num_hats), - KX_PYATTRIBUTE_RO_FUNCTION("connected", SCA_JoystickSensor, pyattr_get_connected), - { NULL } //Sentinel -}; - -/* get button active list -------------------------------------------------- */ -const char SCA_JoystickSensor::GetButtonActiveList_doc[] = -"getButtonActiveList\n" -"\tReturns a list containing the indices of the button currently pressed.\n"; -PyObject *SCA_JoystickSensor::PyGetButtonActiveList( ) -{ - SCA_Joystick *joy = ((SCA_JoystickManager *)m_eventmgr)->GetJoystickDevice(m_joyindex); - PyObject *ls = PyList_New(0); - PyObject *value; - int i; - - if (joy) { - for (i=0; i < joy->GetNumberOfButtons(); i++) { - if (joy->aButtonPressIsPositive(i)) { - value = PyLong_FromLong(i); - PyList_Append(ls, value); - Py_DECREF(value); - } - } - } - return ls; -} - -/* get button status -------------------------------------------------- */ -const char SCA_JoystickSensor::GetButtonStatus_doc[] = -"getButtonStatus(buttonIndex)\n" -"\tReturns a bool of the current pressed state of the specified button.\n"; -PyObject *SCA_JoystickSensor::PyGetButtonStatus( PyObject *args ) -{ - SCA_Joystick *joy = ((SCA_JoystickManager *)m_eventmgr)->GetJoystickDevice(m_joyindex); - int index; - - if (!PyArg_ParseTuple(args, "i:getButtonStatus", &index)) { - return NULL; - } - if (joy && index >= 0 && index < joy->GetNumberOfButtons()) { - return PyBool_FromLong(joy->aButtonPressIsPositive(index) ? 1 : 0); - } - return PyBool_FromLong(0); -} - -PyObject *SCA_JoystickSensor::pyattr_get_axis_values(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_JoystickSensor* self = static_cast(self_v); - SCA_Joystick *joy = ((SCA_JoystickManager *)self->m_eventmgr)->GetJoystickDevice(self->m_joyindex); - - int axis_index = (joy ? joy->GetNumberOfAxes() : 0); - PyObject *list = PyList_New(axis_index); - - while (axis_index--) { - PyList_SET_ITEM(list, axis_index, PyLong_FromLong(joy->GetAxisPosition(axis_index))); - } - - return list; -} - -PyObject *SCA_JoystickSensor::pyattr_get_axis_single(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_JoystickSensor* self = static_cast(self_v); - SCA_Joystick *joy = ((SCA_JoystickManager *)self->m_eventmgr)->GetJoystickDevice(self->m_joyindex); - - if (self->m_joymode != KX_JOYSENSORMODE_AXIS_SINGLE) { - PyErr_SetString(PyExc_AttributeError, "val = sensor.axisSingle: Joystick Sensor, not 'Single Axis' type"); - return NULL; - } - - return PyLong_FromLong(joy ? joy->GetAxisPosition(self->m_axis - 1) : 0); -} - -PyObject *SCA_JoystickSensor::pyattr_get_hat_values(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_JoystickSensor* self = static_cast(self_v); - SCA_Joystick *joy = ((SCA_JoystickManager *)self->m_eventmgr)->GetJoystickDevice(self->m_joyindex); - - int hat_index = (joy ? joy->GetNumberOfHats() : 0); - PyObject *list = PyList_New(hat_index); - - while (hat_index--) { - PyList_SET_ITEM(list, hat_index, PyLong_FromLong(joy->GetHat(hat_index))); - } - - return list; -} - -PyObject *SCA_JoystickSensor::pyattr_get_hat_single(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_JoystickSensor* self = static_cast(self_v); - SCA_Joystick *joy = ((SCA_JoystickManager *)self->m_eventmgr)->GetJoystickDevice(self->m_joyindex); - - return PyLong_FromLong(joy ? joy->GetHat(self->m_hat - 1) : 0); -} - -PyObject *SCA_JoystickSensor::pyattr_get_num_axis(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_JoystickSensor* self = static_cast(self_v); - SCA_Joystick *joy = ((SCA_JoystickManager *)self->m_eventmgr)->GetJoystickDevice(self->m_joyindex); - return PyLong_FromLong( joy ? joy->GetNumberOfAxes() : 0 ); -} - -PyObject *SCA_JoystickSensor::pyattr_get_num_buttons(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_JoystickSensor* self = static_cast(self_v); - SCA_Joystick *joy = ((SCA_JoystickManager *)self->m_eventmgr)->GetJoystickDevice(self->m_joyindex); - return PyLong_FromLong( joy ? joy->GetNumberOfButtons() : 0 ); -} - -PyObject *SCA_JoystickSensor::pyattr_get_num_hats(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_JoystickSensor* self = static_cast(self_v); - SCA_Joystick *joy = ((SCA_JoystickManager *)self->m_eventmgr)->GetJoystickDevice(self->m_joyindex); - return PyLong_FromLong( joy ? joy->GetNumberOfHats() : 0 ); -} - -PyObject *SCA_JoystickSensor::pyattr_get_connected(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_JoystickSensor* self = static_cast(self_v); - SCA_Joystick *joy = ((SCA_JoystickManager *)self->m_eventmgr)->GetJoystickDevice(self->m_joyindex); - return PyBool_FromLong( joy ? joy->Connected() : 0 ); -} - -#endif diff --git a/source/gameengine/GameLogic/SCA_JoystickSensor.h b/source/gameengine/GameLogic/SCA_JoystickSensor.h deleted file mode 100644 index 6c6dc019a5e..00000000000 --- a/source/gameengine/GameLogic/SCA_JoystickSensor.h +++ /dev/null @@ -1,168 +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 SCA_JoystickSensor.h - * \ingroup gamelogic - */ - - -#ifndef __JOYSENSOR_H__ -#define __JOYSENSOR_H__ - -#include "SCA_ISensor.h" -#include "Joystick/SCA_JoystickDefines.h" - -class SCA_JoystickSensor :public SCA_ISensor -{ - Py_Header - - /** - * Axis 1-JOYAXIS_MAX, MUST be followed by m_axisf - */ - int m_axis; - /** - * Axis flag to find direction, MUST be an int - */ - int m_axisf; - /** - * The actual button - */ - int m_button; - /** - * Flag for a pressed or released button - */ - int m_buttonf; - /** - * The actual hat 1-JOYHAT_MAX. MUST be followed by m_hatf - */ - int m_hat; - /** - * Flag to find direction 1-12, MUST be an int - */ - int m_hatf; - /** - * The threshold value the axis acts upon - */ - int m_precision; - /** - * Is an event triggered ? - */ - bool m_istrig; - /** - * Last trigger state for this sensors joystick, - * Otherwise it will trigger all the time - * this is used to see if the trigger state changes. - */ - bool m_istrig_prev; - /** - * The mode to determine axis,button or hat - */ - short int m_joymode; - /** - * Select which joystick to use - */ - short int m_joyindex; - - /** - * Detect all events for the currently selected type - */ - bool m_bAllEvents; - - enum KX_JOYSENSORMODE { - KX_JOYSENSORMODE_NODEF = 0, - KX_JOYSENSORMODE_AXIS, - KX_JOYSENSORMODE_BUTTON, - KX_JOYSENSORMODE_HAT, - KX_JOYSENSORMODE_AXIS_SINGLE, - KX_JOYSENSORMODE_MAX - }; - bool isValid(KX_JOYSENSORMODE); - -public: - SCA_JoystickSensor(class SCA_JoystickManager* eventmgr, - SCA_IObject* gameobj, - short int joyindex, - short int joymode, - int axis, int axisf,int prec, - int button, - int hat, int hatf, bool allevents); - virtual ~SCA_JoystickSensor(); - virtual CValue* GetReplica(); - - virtual bool Evaluate(); - virtual bool IsPositiveTrigger(); - virtual void Init(); - - short int GetJoyIndex(void) { - return m_joyindex; - } - -#ifdef WITH_PYTHON - - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - - /* Joystick Index */ - KX_PYMETHOD_DOC_NOARGS(SCA_JoystickSensor,GetButtonActiveList) - KX_PYMETHOD_DOC_VARARGS(SCA_JoystickSensor,GetButtonStatus) - - static PyObject* pyattr_get_axis_values(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_axis_single(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_hat_values(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_hat_single(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_num_axis(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_num_buttons(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_num_hats(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_connected(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - - - /* attribute check */ - static int CheckAxis(void *self, const PyAttributeDef*) - { - SCA_JoystickSensor* sensor = reinterpret_cast(self); - if (sensor->m_axis < 1) - sensor->m_axis = 1; - else if (sensor->m_axis > JOYAXIS_MAX) - sensor->m_axis = JOYAXIS_MAX; - return 0; - } - static int CheckHat(void *self, const PyAttributeDef*) - { - SCA_JoystickSensor* sensor = reinterpret_cast(self); - if (sensor->m_hat < 1) - sensor->m_hat = 1; - else if (sensor->m_hat > JOYHAT_MAX) - sensor->m_hat = JOYHAT_MAX; - return 0; - } - -#endif /* WITH_PYTHON */ - -}; - -#endif /* __JOYSENSOR_H__ */ diff --git a/source/gameengine/GameLogic/SCA_KeyboardManager.cpp b/source/gameengine/GameLogic/SCA_KeyboardManager.cpp deleted file mode 100644 index 778ba9e9a2c..00000000000 --- a/source/gameengine/GameLogic/SCA_KeyboardManager.cpp +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Manager for keyboard 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/GameLogic/SCA_KeyboardManager.cpp - * \ingroup gamelogic - */ - - -#include "EXP_BoolValue.h" -#include "SCA_KeyboardManager.h" -#include "SCA_KeyboardSensor.h" -#include "EXP_IntValue.h" -#include - -SCA_KeyboardManager::SCA_KeyboardManager(SCA_LogicManager* logicmgr, - SCA_IInputDevice* inputdev) - : SCA_EventManager(logicmgr, KEYBOARD_EVENTMGR), - m_inputDevice(inputdev) -{ -} - - - -SCA_KeyboardManager::~SCA_KeyboardManager() -{ -} - - - -SCA_IInputDevice* SCA_KeyboardManager::GetInputDevice() -{ - return m_inputDevice; -} - - - -void SCA_KeyboardManager::NextFrame() -{ - //const SCA_InputEvent& event = GetEventValue(SCA_IInputDevice::KX_EnumInputs inputcode)=0; -// cerr << "SCA_KeyboardManager::NextFrame"<< endl; - SG_DList::iterator it(m_sensors); - for (it.begin();!it.end();++it) - { - (*it)->Activate(m_logicmgr); - } -} - -bool SCA_KeyboardManager::IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode) -{ - return false; - //return m_kxsystem->IsPressed(inputcode); -} - diff --git a/source/gameengine/GameLogic/SCA_KeyboardManager.h b/source/gameengine/GameLogic/SCA_KeyboardManager.h deleted file mode 100644 index cd1cbf4adee..00000000000 --- a/source/gameengine/GameLogic/SCA_KeyboardManager.h +++ /dev/null @@ -1,66 +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 SCA_KeyboardManager.h - * \ingroup gamelogic - * \brief Manager for keyboard events - * - */ - -#ifndef __SCA_KEYBOARDMANAGER_H__ -#define __SCA_KEYBOARDMANAGER_H__ - - -#include "SCA_EventManager.h" - -#include - -using namespace std; - -#include "SCA_IInputDevice.h" - - -class SCA_KeyboardManager : public SCA_EventManager -{ - class SCA_IInputDevice* m_inputDevice; - -public: - SCA_KeyboardManager(class SCA_LogicManager* logicmgr,class SCA_IInputDevice* inputdev); - virtual ~SCA_KeyboardManager(); - - bool IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode); - - virtual void NextFrame(); - SCA_IInputDevice* GetInputDevice(); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_KeyboardManager") -#endif -}; - -#endif /* __SCA_KEYBOARDMANAGER_H__ */ diff --git a/source/gameengine/GameLogic/SCA_KeyboardSensor.cpp b/source/gameengine/GameLogic/SCA_KeyboardSensor.cpp deleted file mode 100644 index 414a685d358..00000000000 --- a/source/gameengine/GameLogic/SCA_KeyboardSensor.cpp +++ /dev/null @@ -1,668 +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 ***** - * Sensor for keyboard input - */ - -/** \file gameengine/GameLogic/SCA_KeyboardSensor.cpp - * \ingroup gamelogic - */ - - -#include - -#include "SCA_KeyboardSensor.h" -#include "SCA_KeyboardManager.h" -#include "SCA_LogicManager.h" -#include "EXP_StringValue.h" -#include "SCA_IInputDevice.h" - -extern "C" { - #include "BLI_string_utf8.h" - #include "BLI_string_cursor_utf8.h" -} - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -SCA_KeyboardSensor::SCA_KeyboardSensor(SCA_KeyboardManager* keybdmgr, - short int hotkey, - short int qual, - short int qual2, - bool bAllKeys, - const STR_String& targetProp, - const STR_String& toggleProp, - SCA_IObject* gameobj, - short int exitKey) - :SCA_ISensor(gameobj,keybdmgr), - m_hotkey(hotkey), - m_qual(qual), - m_qual2(qual2), - m_bAllKeys(bAllKeys), - m_targetprop(targetProp), - m_toggleprop(toggleProp) -{ - if (hotkey == exitKey) - keybdmgr->GetInputDevice()->HookEscape(); -// SetDrawColor(0xff0000ff); - Init(); -} - - - -SCA_KeyboardSensor::~SCA_KeyboardSensor() -{ -} - -void SCA_KeyboardSensor::Init() -{ - // this function is used when the sensor is disconnected from all controllers - // by the state engine. It reinitializes the sensor as if it was just created. - // However, if the target key is pressed when the sensor is reactivated, it - // will not generated an event (see remark in Evaluate()). - m_val = (m_invert)?1:0; - m_reset = true; -} - -CValue* SCA_KeyboardSensor::GetReplica() -{ - SCA_KeyboardSensor* replica = new SCA_KeyboardSensor(*this); - // this will copy properties and so on... - replica->ProcessReplica(); - replica->Init(); - return replica; -} - - - -short int SCA_KeyboardSensor::GetHotkey() -{ - return m_hotkey; -} - - - -bool SCA_KeyboardSensor::IsPositiveTrigger() -{ - bool result = (m_val != 0); - - if (m_invert) - result = !result; - - return result; -} - - - -bool SCA_KeyboardSensor::TriggerOnAllKeys() -{ - return m_bAllKeys; -} - - - -bool SCA_KeyboardSensor::Evaluate() -{ - bool result = false; - bool reset = m_reset && m_level; - bool qual = true; - bool qual_change = false; - short int m_val_orig = m_val; - - SCA_IInputDevice* inputdev = ((SCA_KeyboardManager *)m_eventmgr)->GetInputDevice(); - // cerr << "SCA_KeyboardSensor::Eval event, sensing for "<< m_hotkey << " at device " << inputdev << "\n"; - - /* See if we need to do logging: togPropState exists and is - * different from 0 */ - CValue* myparent = GetParent(); - CValue* togPropState = myparent->GetProperty(m_toggleprop); - if (togPropState && - (((int)togPropState->GetNumber()) != 0) ) - { - LogKeystrokes(); - } - - m_reset = false; - - /* Now see whether events must be bounced. */ - if (m_bAllKeys) - { - bool justactivated = false; - bool justreleased = false; - bool active = false; - - for (int i=SCA_IInputDevice::KX_BEGINKEY ; i<= SCA_IInputDevice::KX_ENDKEY;i++) - { - const SCA_InputEvent & inevent = inputdev->GetEventValue((SCA_IInputDevice::KX_EnumInputs) i); - switch (inevent.m_status) - { - case SCA_InputEvent::KX_JUSTACTIVATED: - justactivated = true; - break; - case SCA_InputEvent::KX_JUSTRELEASED: - justreleased = true; - break; - case SCA_InputEvent::KX_ACTIVE: - active = true; - break; - case SCA_InputEvent::KX_NO_INPUTSTATUS: - /* do nothing */ - break; - } - } - - if (justactivated) - { - m_val=1; - result = true; - } else - { - if (justreleased) - { - m_val=(active)?1:0; - result = true; - } else - { - if (active) - { - if (m_val == 0) - { - m_val = 1; - if (m_level) { - result = true; - } - } - } else - { - if (m_val == 1) - { - m_val = 0; - result = true; - } - } - } - if (m_tap) - // special case for tap mode: only generate event for new activation - result = false; - } - - - } else - { - - // cerr << "======= SCA_KeyboardSensor::Evaluate:: peeking at key status" << endl; - const SCA_InputEvent & inevent = inputdev->GetEventValue( - (SCA_IInputDevice::KX_EnumInputs) m_hotkey); - - // cerr << "======= SCA_KeyboardSensor::Evaluate:: status: " << inevent.m_status << endl; - - - /* Check qualifier keys - * - see if the qualifiers we request are pressed - 'qual' true/false - * - see if the qualifiers we request changed their state - 'qual_change' true/false - */ - if (m_qual > 0) { - const SCA_InputEvent & qualevent = inputdev->GetEventValue((SCA_IInputDevice::KX_EnumInputs) m_qual); - switch (qualevent.m_status) { - case SCA_InputEvent::KX_NO_INPUTSTATUS: - qual = false; - break; - case SCA_InputEvent::KX_JUSTRELEASED: - qual_change = true; - qual = false; - break; - case SCA_InputEvent::KX_JUSTACTIVATED: - qual_change = true; - case SCA_InputEvent::KX_ACTIVE: - /* do nothing */ - break; - } - } - if (m_qual2 > 0 && qual==true) { - const SCA_InputEvent & qualevent = inputdev->GetEventValue((SCA_IInputDevice::KX_EnumInputs) m_qual2); - /* copy of above */ - switch (qualevent.m_status) { - case SCA_InputEvent::KX_NO_INPUTSTATUS: - qual = false; - break; - case SCA_InputEvent::KX_JUSTRELEASED: - qual_change = true; - qual = false; - break; - case SCA_InputEvent::KX_JUSTACTIVATED: - qual_change = true; - case SCA_InputEvent::KX_ACTIVE: - /* do nothing */ - break; - } - } - /* done reading qualifiers */ - - if (inevent.m_status == SCA_InputEvent::KX_NO_INPUTSTATUS) - { - if (m_val == 1) - { - // this situation may occur after a scene suspend: the keyboard release - // event was not captured, produce now the event off - m_val = 0; - result = true; - } - } else - { - if (inevent.m_status == SCA_InputEvent::KX_JUSTACTIVATED) - { - m_val=1; - result = true; - } else - { - if (inevent.m_status == SCA_InputEvent::KX_JUSTRELEASED) - { - m_val = 0; - result = true; - } else - { - if (inevent.m_status == SCA_InputEvent::KX_ACTIVE) - { - if (m_val == 0) - { - m_val = 1; - if (m_level) - { - result = true; - } - } - } - } - } - } - - /* Modify the key state based on qual(s) - * Tested carefully. don't touch unless your really sure. - * note, this will only change the results if key modifiers are set. - * - * When all modifiers and keys are positive - * - pulse true - * - * When ANY of the modifiers or main key become inactive, - * - pulse false - */ - if (qual==false) { /* one of the qualifiers are not pressed */ - if (m_val_orig && qual_change) { /* we were originally enabled, but a qualifier changed */ - result = true; - } else { - result = false; - } - m_val = 0; /* since one of the qualifiers is not on, set the state to false */ - } else { /* we done have any qualifiers or they are all pressed */ - if (m_val && qual_change) { /* the main key state is true and our qualifier just changed */ - result = true; - } - } - /* done with key quals */ - - } - - if (reset) - // force an event - result = true; - return result; - -} - -void SCA_KeyboardSensor::AddToTargetProp(int keyIndex, int unicode) -{ - if (IsPrintable(keyIndex)) { - CValue* tprop = GetParent()->GetProperty(m_targetprop); - - if (IsDelete(keyIndex)) { - /* Make a new property. Deletes can be ignored. */ - if (tprop) { - /* overwrite the old property */ - /* strip one char, if possible */ - STR_String newprop = tprop->GetText(); - int oldlength = newprop.Length(); - if (oldlength >= 1 ) { - int newlength=oldlength; - - BLI_str_cursor_step_prev_utf8(newprop, newprop.Length(), &newlength); - newprop.SetLength(newlength); - - CStringValue * newstringprop = new CStringValue(newprop, m_targetprop); - GetParent()->SetProperty(m_targetprop, newstringprop); - newstringprop->Release(); - } - } - } - else { - char utf8_buf[7]; - size_t utf8_len; - - utf8_len = BLI_str_utf8_from_unicode(unicode, utf8_buf); - utf8_buf[utf8_len] = '\0'; - - STR_String newprop = tprop ? (tprop->GetText() + utf8_buf) : utf8_buf; - - CStringValue * newstringprop = new CStringValue(newprop, m_targetprop); - GetParent()->SetProperty(m_targetprop, newstringprop); - newstringprop->Release(); - } - } -} - -/** - * Tests whether shift is pressed - */ -bool SCA_KeyboardSensor::IsShifted(void) -{ - SCA_IInputDevice* inputdev = ((SCA_KeyboardManager *)m_eventmgr)->GetInputDevice(); - - if ( (inputdev->GetEventValue(SCA_IInputDevice::KX_RIGHTSHIFTKEY).m_status - == SCA_InputEvent::KX_ACTIVE) - || (inputdev->GetEventValue(SCA_IInputDevice::KX_RIGHTSHIFTKEY).m_status - == SCA_InputEvent::KX_JUSTACTIVATED) - || (inputdev->GetEventValue(SCA_IInputDevice::KX_LEFTSHIFTKEY).m_status - == SCA_InputEvent::KX_ACTIVE) - || (inputdev->GetEventValue(SCA_IInputDevice::KX_LEFTSHIFTKEY).m_status - == SCA_InputEvent::KX_JUSTACTIVATED) - ) { - return true; - } - else { - return false; - } -} - -void SCA_KeyboardSensor::LogKeystrokes(void) -{ - SCA_IInputDevice* inputdev = ((SCA_KeyboardManager *)m_eventmgr)->GetInputDevice(); - int num = inputdev->GetNumActiveEvents(); - - /* weird loop, this one... */ - if (num > 0) - { - - int index = 0; - /* Check on all keys whether they were pushed. This does not - * untangle the ordering, so don't type too fast :) */ - for (int i=SCA_IInputDevice::KX_BEGINKEY ; i<= SCA_IInputDevice::KX_ENDKEY;i++) - { - const SCA_InputEvent & inevent = inputdev->GetEventValue((SCA_IInputDevice::KX_EnumInputs) i); - if (inevent.m_status == SCA_InputEvent::KX_JUSTACTIVATED) //NO_INPUTSTATUS) - { - if (index < num) - { - AddToTargetProp(i, inevent.m_unicode); - index++; - } - } - } - } -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python Functions */ -/* ------------------------------------------------------------------------- */ - -KX_PYMETHODDEF_DOC_O(SCA_KeyboardSensor, getKeyStatus, -"getKeyStatus(keycode)\n" -"\tGet the given key's status (KX_NO_INPUTSTATUS, KX_JUSTACTIVATED, KX_ACTIVE or KX_JUSTRELEASED).\n") -{ - if (!PyLong_Check(value)) { - PyErr_SetString(PyExc_ValueError, "sensor.getKeyStatus(int): Keyboard Sensor, expected an int"); - return NULL; - } - - SCA_IInputDevice::KX_EnumInputs keycode = (SCA_IInputDevice::KX_EnumInputs)PyLong_AsLong(value); - - if ((keycode < SCA_IInputDevice::KX_BEGINKEY) || - (keycode > SCA_IInputDevice::KX_ENDKEY)) - { - PyErr_SetString(PyExc_AttributeError, "sensor.getKeyStatus(int): Keyboard Sensor, invalid keycode specified!"); - return NULL; - } - - SCA_IInputDevice* inputdev = ((SCA_KeyboardManager *)m_eventmgr)->GetInputDevice(); - const SCA_InputEvent & inevent = inputdev->GetEventValue(keycode); - return PyLong_FromLong(inevent.m_status); -} - -/* ------------------------------------------------------------------------- */ -/* Python Integration Hooks */ -/* ------------------------------------------------------------------------- */ - -PyTypeObject SCA_KeyboardSensor::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "SCA_KeyboardSensor", - 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 SCA_KeyboardSensor::Methods[] = { - KX_PYMETHODTABLE_O(SCA_KeyboardSensor, getKeyStatus), - {NULL,NULL} //Sentinel -}; - -PyAttributeDef SCA_KeyboardSensor::Attributes[] = { - KX_PYATTRIBUTE_RO_FUNCTION("events", SCA_KeyboardSensor, pyattr_get_events), - KX_PYATTRIBUTE_BOOL_RW("useAllKeys",SCA_KeyboardSensor,m_bAllKeys), - KX_PYATTRIBUTE_INT_RW("key",0,SCA_IInputDevice::KX_ENDKEY,true,SCA_KeyboardSensor,m_hotkey), - KX_PYATTRIBUTE_SHORT_RW("hold1",0,SCA_IInputDevice::KX_ENDKEY,true,SCA_KeyboardSensor,m_qual), - KX_PYATTRIBUTE_SHORT_RW("hold2",0,SCA_IInputDevice::KX_ENDKEY,true,SCA_KeyboardSensor,m_qual2), - KX_PYATTRIBUTE_STRING_RW("toggleProperty",0,MAX_PROP_NAME,false,SCA_KeyboardSensor,m_toggleprop), - KX_PYATTRIBUTE_STRING_RW("targetProperty",0,MAX_PROP_NAME,false,SCA_KeyboardSensor,m_targetprop), - { NULL } //Sentinel -}; - - -PyObject *SCA_KeyboardSensor::pyattr_get_events(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_KeyboardSensor* self = static_cast(self_v); - - SCA_IInputDevice* inputdev = ((SCA_KeyboardManager *)self->m_eventmgr)->GetInputDevice(); - - PyObject *resultlist = PyList_New(0); - - for (int i=SCA_IInputDevice::KX_BEGINKEY ; i<= SCA_IInputDevice::KX_ENDKEY;i++) - { - const SCA_InputEvent & inevent = inputdev->GetEventValue((SCA_IInputDevice::KX_EnumInputs) i); - if (inevent.m_status != SCA_InputEvent::KX_NO_INPUTSTATUS) - { - PyObject *keypair = PyList_New(2); - PyList_SET_ITEM(keypair,0,PyLong_FromLong(i)); - PyList_SET_ITEM(keypair,1,PyLong_FromLong(inevent.m_status)); - PyList_Append(resultlist,keypair); - Py_DECREF(keypair); - } - } - return resultlist; -} - -#endif // WITH_PYTHON - -/* Accessed from python */ - -// this code looks ugly, please use an ordinary hashtable - -char ToCharacter(int keyIndex, bool shifted) -{ - /* numerals */ - if ( (keyIndex >= SCA_IInputDevice::KX_ZEROKEY) - && (keyIndex <= SCA_IInputDevice::KX_NINEKEY) ) { - if (shifted) { - char numshift[] = ")!@#$%^&*("; - return numshift[keyIndex - '0']; - } else { - return keyIndex - SCA_IInputDevice::KX_ZEROKEY + '0'; - } - } - - /* letters... always lowercase... is that desirable? */ - if ( (keyIndex >= SCA_IInputDevice::KX_AKEY) - && (keyIndex <= SCA_IInputDevice::KX_ZKEY) ) { - if (shifted) { - return keyIndex - SCA_IInputDevice::KX_AKEY + 'A'; - } else { - return keyIndex - SCA_IInputDevice::KX_AKEY + 'a'; - } - } - - if (keyIndex == SCA_IInputDevice::KX_SPACEKEY) { - return ' '; - } - if (keyIndex == SCA_IInputDevice::KX_RETKEY || keyIndex == SCA_IInputDevice::KX_PADENTER) { - return '\n'; - } - - - if (keyIndex == SCA_IInputDevice::KX_PADASTERKEY) { - return '*'; - } - - if (keyIndex == SCA_IInputDevice::KX_TABKEY) { - return '\t'; - } - - /* comma to period */ - char commatoperiod[] = ",-."; - char commatoperiodshifted[] = "<_>"; - if (keyIndex == SCA_IInputDevice::KX_COMMAKEY) { - if (shifted) { - return commatoperiodshifted[0]; - } else { - return commatoperiod[0]; - } - } - if (keyIndex == SCA_IInputDevice::KX_MINUSKEY) { - if (shifted) { - return commatoperiodshifted[1]; - } else { - return commatoperiod[1]; - } - } - if (keyIndex == SCA_IInputDevice::KX_PERIODKEY) { - if (shifted) { - return commatoperiodshifted[2]; - } else { - return commatoperiod[2]; - } - } - - /* semicolon to rightbracket */ - char semicolontorightbracket[] = ";\'`/\\=[]"; - char semicolontorightbracketshifted[] = ":\"~\?|+{}"; - if ((keyIndex >= SCA_IInputDevice::KX_SEMICOLONKEY) - && (keyIndex <= SCA_IInputDevice::KX_RIGHTBRACKETKEY)) { - if (shifted) { - return semicolontorightbracketshifted[keyIndex - SCA_IInputDevice::KX_SEMICOLONKEY]; - } else { - return semicolontorightbracket[keyIndex - SCA_IInputDevice::KX_SEMICOLONKEY]; - } - } - - /* keypad2 to padplus */ - char pad2topadplus[] = "246813579. 0- +"; - if ((keyIndex >= SCA_IInputDevice::KX_PAD2) - && (keyIndex <= SCA_IInputDevice::KX_PADPLUSKEY)) { - return pad2topadplus[keyIndex - SCA_IInputDevice::KX_PAD2]; - } - - return '!'; -} - - - -/** - * Determine whether this character can be printed. We cannot use - * the library functions here, because we need to test our own - * keycodes. */ -bool IsPrintable(int keyIndex) -{ - /* only print - * - numerals: KX_ZEROKEY to KX_NINEKEY - * - alphas: KX_AKEY to KX_ZKEY. - * - specials: KX_RETKEY, KX_PADASTERKEY, KX_PADCOMMAKEY to KX_PERIODKEY, - * KX_TABKEY, KX_SEMICOLONKEY to KX_RIGHTBRACKETKEY, - * KX_PAD2 to KX_PADPLUSKEY - * - delete and backspace: also printable in the sense that they modify - * the string - * - retkey: should this be printable? - * - virgule: prints a space... don't know which key that's supposed - * to be... - */ - if ( ((keyIndex >= SCA_IInputDevice::KX_ZEROKEY) - && (keyIndex <= SCA_IInputDevice::KX_NINEKEY)) - || ((keyIndex >= SCA_IInputDevice::KX_AKEY) - && (keyIndex <= SCA_IInputDevice::KX_ZKEY)) - || (keyIndex == SCA_IInputDevice::KX_SPACEKEY) - || (keyIndex == SCA_IInputDevice::KX_RETKEY) - || (keyIndex == SCA_IInputDevice::KX_PADENTER) - || (keyIndex == SCA_IInputDevice::KX_PADASTERKEY) - || (keyIndex == SCA_IInputDevice::KX_TABKEY) - || ((keyIndex >= SCA_IInputDevice::KX_COMMAKEY) - && (keyIndex <= SCA_IInputDevice::KX_PERIODKEY)) - || ((keyIndex >= SCA_IInputDevice::KX_SEMICOLONKEY) - && (keyIndex <= SCA_IInputDevice::KX_RIGHTBRACKETKEY)) - || ((keyIndex >= SCA_IInputDevice::KX_PAD2) - && (keyIndex <= SCA_IInputDevice::KX_PADPLUSKEY)) - || (keyIndex == SCA_IInputDevice::KX_DELKEY) - || (keyIndex == SCA_IInputDevice::KX_BACKSPACEKEY) - ) - { - return true; - } else { - return false; - } -} - -/** - * Tests whether this is a delete key. - */ -bool IsDelete(int keyIndex) -{ - if ( (keyIndex == SCA_IInputDevice::KX_DELKEY) - || (keyIndex == SCA_IInputDevice::KX_BACKSPACEKEY) ) { - return true; - } else { - return false; - } -} diff --git a/source/gameengine/GameLogic/SCA_KeyboardSensor.h b/source/gameengine/GameLogic/SCA_KeyboardSensor.h deleted file mode 100644 index 51d7756bd1f..00000000000 --- a/source/gameengine/GameLogic/SCA_KeyboardSensor.h +++ /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 SCA_KeyboardSensor.h - * \ingroup gamelogic - * \brief Sensor for keyboard input - */ - -#ifndef __SCA_KEYBOARDSENSOR_H__ -#define __SCA_KEYBOARDSENSOR_H__ - -#include "SCA_ISensor.h" -#include "EXP_BoolValue.h" -#include - -/** - * The keyboard sensor listens to the keyboard, and passes on events - * on selected keystrokes. It has an alternate mode in which it logs - * keypresses to a property. Note that these modes are not mutually - * exclusive. */ -class SCA_KeyboardSensor : public SCA_ISensor -{ - Py_Header - - /** - * the key this sensor is sensing for - */ - int m_hotkey; - short int m_qual,m_qual2; - short int m_val; - /** - * If this toggle is true, all incoming key events generate a - * response. - */ - bool m_bAllKeys; - - /** - * The name of the property to which logged text is appended. If - * this property is not defined, no logging takes place. - */ - STR_String m_targetprop; - /** - * The property that indicates whether or not to log text when in - * logging mode. If the property equals 0, no logging is done. For - * all other values, logging is active. Logging can only become - * active if there is a property to log to. Logging is independent - * from hotkey settings. */ - STR_String m_toggleprop; - - /** - * Log the keystrokes from the current input buffer. - */ - void LogKeystrokes(void); - - /** - * Adds this key-code to the target prop. - */ - void AddToTargetProp(int keyIndex, int unicode); - - /** - * Tests whether shift is pressed. - */ - bool IsShifted(void); - -public: - SCA_KeyboardSensor(class SCA_KeyboardManager* keybdmgr, - short int hotkey, - short int qual, - short int qual2, - bool bAllKeys, - const STR_String& targetProp, - const STR_String& toggleProp, - SCA_IObject* gameobj, - short int exitKey); - virtual ~SCA_KeyboardSensor(); - virtual CValue* GetReplica(); - virtual void Init(); - - - short int GetHotkey(); - virtual bool Evaluate(); - virtual bool IsPositiveTrigger(); - bool TriggerOnAllKeys(); - -#ifdef WITH_PYTHON - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - - // KeyEvents: - KX_PYMETHOD_DOC_NOARGS(SCA_KeyboardSensor,getEventList); - // KeyStatus: - KX_PYMETHOD_DOC_O(SCA_KeyboardSensor,getKeyStatus); - - static PyObject* pyattr_get_events(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); -#endif -}; - - -/** - * Transform keycodes to something printable. - */ -char ToCharacter(int keyIndex, bool shifted); - -/** - * Determine whether this character can be printed. We cannot use - * the library functions here, because we need to test our own - * keycodes. */ -bool IsPrintable(int keyIndex); - -/** - * Tests whether this is a delete key. - */ -bool IsDelete(int keyIndex); - - -#endif /* __SCA_KEYBOARDSENSOR_H__ */ diff --git a/source/gameengine/GameLogic/SCA_LogicManager.cpp b/source/gameengine/GameLogic/SCA_LogicManager.cpp deleted file mode 100644 index 978f6d6b836..00000000000 --- a/source/gameengine/GameLogic/SCA_LogicManager.cpp +++ /dev/null @@ -1,342 +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 ***** - * Regulates the top-level logic behavior for one scene. - */ - -/** \file gameengine/GameLogic/SCA_LogicManager.cpp - * \ingroup gamelogic - */ - -#include "EXP_Value.h" -#include "SCA_LogicManager.h" -#include "SCA_ISensor.h" -#include "SCA_IController.h" -#include "SCA_IActuator.h" -#include "SCA_EventManager.h" -#include "SCA_PythonController.h" -#include - - -SCA_LogicManager::SCA_LogicManager() -{ -} - - - -SCA_LogicManager::~SCA_LogicManager() -{ - for (vector::iterator it = m_eventmanagers.begin();!(it==m_eventmanagers.end());++it) - { - delete (*it); - } - m_eventmanagers.clear(); - assert(m_activeActuators.Empty()); -} - -#if 0 -// this kind of fixes bug 398 but breakes games, so better leave it out for now. -// a removed object's gameobject (and logicbricks and stuff) didn't get released -// because it was still in the m_mapStringToGameObjects map. -void SCA_LogicManager::RemoveGameObject(const STR_String& gameobjname) -{ - int numgameobj = m_mapStringToGameObjects.size(); - for (int i = 0; i < numgameobj; i++) - { - CValue** gameobjptr = m_mapStringToGameObjects.at(i); - assert(gameobjptr); - - if (gameobjptr) - { - if ((*gameobjptr)->GetName() == gameobjname) - (*gameobjptr)->Release(); - } - } - - m_mapStringToGameObjects.remove(gameobjname); -} -#endif - - -void SCA_LogicManager::RegisterEventManager(SCA_EventManager* eventmgr) -{ - m_eventmanagers.push_back(eventmgr); -} - - - -void SCA_LogicManager::RegisterGameObjectName(const STR_String& gameobjname, - CValue* gameobj) -{ - STR_HashedString mn = gameobjname; - m_mapStringToGameObjects.insert(mn,gameobj); -} - - - -void SCA_LogicManager::RegisterGameMeshName(const STR_String& gamemeshname, void* blendobj) -{ - STR_HashedString mn = gamemeshname; - m_map_gamemeshname_to_blendobj.insert(mn, blendobj); -} - - - -void SCA_LogicManager::RegisterGameObj(void* blendobj, CValue* gameobj) -{ - m_map_blendobj_to_gameobj.insert(CHashedPtr(blendobj), gameobj); -} - -void SCA_LogicManager::UnregisterGameObj(void* blendobj, CValue* gameobj) -{ - void **obp = m_map_blendobj_to_gameobj[CHashedPtr(blendobj)]; - if (obp && (CValue*)(*obp) == gameobj) - m_map_blendobj_to_gameobj.remove(CHashedPtr(blendobj)); -} - -CValue* SCA_LogicManager::GetGameObjectByName(const STR_String& gameobjname) -{ - STR_HashedString mn = gameobjname; - CValue** gameptr = m_mapStringToGameObjects[mn]; - - if (gameptr) - return *gameptr; - - return NULL; -} - - -CValue* SCA_LogicManager::FindGameObjByBlendObj(void* blendobj) -{ - void **obp= m_map_blendobj_to_gameobj[CHashedPtr(blendobj)]; - return obp?(CValue*)(*obp):NULL; -} - - - -void* SCA_LogicManager::FindBlendObjByGameMeshName(const STR_String& gamemeshname) -{ - STR_HashedString mn = gamemeshname; - void **obp= m_map_gamemeshname_to_blendobj[mn]; - return obp?*obp:NULL; -} - - - -void SCA_LogicManager::RemoveSensor(SCA_ISensor* sensor) -{ - sensor->UnlinkAllControllers(); - sensor->UnregisterToManager(); -} - -void SCA_LogicManager::RemoveController(SCA_IController* controller) -{ - controller->UnlinkAllSensors(); - controller->UnlinkAllActuators(); - controller->Deactivate(); -} - - -void SCA_LogicManager::RemoveActuator(SCA_IActuator* actuator) -{ - actuator->UnlinkAllControllers(); - actuator->Deactivate(); - actuator->SetActive(false); -} - - - -void SCA_LogicManager::RegisterToSensor(SCA_IController* controller,SCA_ISensor* sensor) -{ - sensor->LinkToController(controller); - controller->LinkToSensor(sensor); -} - - - -void SCA_LogicManager::RegisterToActuator(SCA_IController* controller,SCA_IActuator* actua) -{ - actua->LinkToController(controller); - controller->LinkToActuator(actua); -} - - - -void SCA_LogicManager::BeginFrame(double curtime, double fixedtime) -{ - for (vector::const_iterator ie=m_eventmanagers.begin(); !(ie==m_eventmanagers.end()); ie++) - (*ie)->NextFrame(curtime, fixedtime); - - for (SG_QList* obj = (SG_QList*)m_triggeredControllerSet.Remove(); - obj != NULL; - obj = (SG_QList*)m_triggeredControllerSet.Remove()) - { - for (SCA_IController* contr = (SCA_IController*)obj->QRemove(); - contr != NULL; - contr = (SCA_IController*)obj->QRemove()) - { - contr->Trigger(this); - contr->ClrJustActivated(); - } - } -} - - - -void SCA_LogicManager::UpdateFrame(double curtime, bool frame) -{ - for (vector::const_iterator ie=m_eventmanagers.begin(); !(ie==m_eventmanagers.end()); ie++) - (*ie)->UpdateFrame(); - - SG_DList::iterator io(m_activeActuators); - for (io.begin(); !io.end(); ) - { - SG_QList* ahead = *io; - // increment now so that we can remove the current element - ++io; - SG_QList::iterator ia(*ahead); - for (ia.begin(); !ia.end(); ) - { - SCA_IActuator* actua = *ia; - // increment first to allow removal of inactive actuators. - ++ia; - if (!actua->Update(curtime, frame)) - { - // this actuator is not active anymore, remove - actua->QDelink(); - actua->SetActive(false); - } else if (actua->IsNoLink()) - { - // This actuator has no more links but it still active - // make sure it will get a negative event on next frame to stop it - // Do this check after Update() rather than before to make sure - // that all the actuators that are activated at same time than a state - // actuator have a chance to execute. - bool event = false; - actua->RemoveAllEvents(); - actua->AddEvent(event); - } - } - if (ahead->QEmpty()) - { - // no more active controller, remove from main list - ahead->Delink(); - } - } -} - - - -void *SCA_LogicManager::GetActionByName(const STR_String& actname) -{ - STR_HashedString an = actname; - void** actptr = m_mapStringToActions[an]; - - if (actptr) - return *actptr; - - return NULL; -} - - - -void* SCA_LogicManager::GetMeshByName(const STR_String& meshname) -{ - STR_HashedString mn = meshname; - void** meshptr = m_mapStringToMeshes[mn]; - - if (meshptr) - return *meshptr; - - return NULL; -} - - - -void SCA_LogicManager::RegisterMeshName(const STR_String& meshname,void* mesh) -{ - STR_HashedString mn = meshname; - m_mapStringToMeshes.insert(mn,mesh); -} - -void SCA_LogicManager::UnregisterMeshName(const STR_String& meshname,void* mesh) -{ - STR_HashedString mn = meshname; - m_mapStringToMeshes.remove(mn); -} - - -void SCA_LogicManager::RegisterActionName(const STR_String& actname,void* action) -{ - STR_HashedString an = actname; - m_mapStringToActions.insert(an, action); -} - - - -void SCA_LogicManager::EndFrame() -{ - for (vector::const_iterator ie=m_eventmanagers.begin(); - !(ie==m_eventmanagers.end());ie++) - { - (*ie)->EndFrame(); - } -} - - -void SCA_LogicManager::AddTriggeredController(SCA_IController* controller, SCA_ISensor* sensor) -{ - controller->Activate(m_triggeredControllerSet); - -#ifdef WITH_PYTHON - - // so that the controller knows which sensor has activited it - // only needed for python controller - // Note that this is safe even if the controller is subclassed. - if (controller->GetType() == &SCA_PythonController::Type) - { - SCA_PythonController* pythonController = (SCA_PythonController*)controller; - pythonController->AddTriggeredSensor(sensor); - } -#endif -} - -SCA_EventManager* SCA_LogicManager::FindEventManager(int eventmgrtype) -{ - // find an eventmanager of a certain type - SCA_EventManager* eventmgr = NULL; - - for (vector::const_iterator i= - m_eventmanagers.begin();!(i==m_eventmanagers.end());i++) - { - SCA_EventManager* emgr = *i; - if (emgr->GetType() == eventmgrtype) - { - eventmgr = emgr; - break; - } - } - return eventmgr; -} diff --git a/source/gameengine/GameLogic/SCA_LogicManager.h b/source/gameengine/GameLogic/SCA_LogicManager.h deleted file mode 100644 index 7319bb537dd..00000000000 --- a/source/gameengine/GameLogic/SCA_LogicManager.h +++ /dev/null @@ -1,154 +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 SCA_LogicManager.h - * \ingroup gamelogic - * \brief Regulates the top-level logic behavior for one scene. - */ -#ifndef __SCA_LOGICMANAGER_H__ -#define __SCA_LOGICMANAGER_H__ - -#ifdef _MSC_VER -# pragma warning (disable:4786) -#endif - -#include -//#include "CTR_Map.h" -#include -#include -#include - -#include "CTR_Map.h" -#include "STR_HashedString.h" -#include "EXP_Value.h" -#include "SG_QList.h" - -#include "EXP_HashedPtr.h" - -using namespace std; -typedef std::list controllerlist; -typedef std::map sensormap_t; - -/** - * This manager handles sensor, controllers and actuators. - * logic executes each frame the following way: - * find triggering sensors - * build list of controllers that are triggered by these triggering sensors - * process all triggered controllers - * during this phase actuators can be added to the active actuator list - * process all active actuators - * clear triggering sensors - * clear triggered controllers - * (actuators may be active during a longer timeframe) - */ - -#include "SCA_ILogicBrick.h" -#include "SCA_IActuator.h" -#include "SCA_EventManager.h" - - -class SCA_LogicManager -{ - vector m_eventmanagers; - - // SG_DList: Head of objects having activated actuators - // element: SCA_IObject::m_activeActuators - SG_DList m_activeActuators; - // SG_DList: Head of objects having activated controllers - // element: SCA_IObject::m_activeControllers - SG_DList m_triggeredControllerSet; - - // need to find better way for this - // also known as FactoryManager... - CTR_Map m_mapStringToGameObjects; - CTR_Map m_mapStringToMeshes; - CTR_Map m_mapStringToActions; - - CTR_Map m_map_gamemeshname_to_blendobj; - CTR_Map m_map_blendobj_to_gameobj; -public: - SCA_LogicManager(); - virtual ~SCA_LogicManager(); - - //void SetKeyboardManager(SCA_KeyboardManager* keyboardmgr) { m_keyboardmgr=keyboardmgr;} - void RegisterEventManager(SCA_EventManager* eventmgr); - void RegisterToSensor(SCA_IController* controller, - class SCA_ISensor* sensor); - void RegisterToActuator(SCA_IController* controller, - class SCA_IActuator* actuator); - - void BeginFrame(double curtime, double fixedtime); - void UpdateFrame(double curtime, bool frame); - void EndFrame(); - void AddActiveActuator(SCA_IActuator* actua,bool event) - { - actua->SetActive(true); - actua->Activate(m_activeActuators); - actua->AddEvent(event); - } - - void AddTriggeredController(SCA_IController* controller, SCA_ISensor* sensor); - SCA_EventManager* FindEventManager(int eventmgrtype); - vector GetEventManagers() { return m_eventmanagers; } - - void RemoveGameObject(const STR_String& gameobjname); - - /** - * remove Logic Bricks from the running logicmanager - */ - void RemoveSensor(SCA_ISensor* sensor); - void RemoveController(SCA_IController* controller); - void RemoveActuator(SCA_IActuator* actuator); - - - // for the scripting... needs a FactoryManager later (if we would have time... ;) - void RegisterMeshName(const STR_String& meshname,void* mesh); - void UnregisterMeshName(const STR_String& meshname,void* mesh); - CTR_Map& GetMeshMap() { return m_mapStringToMeshes; } - CTR_Map& GetActionMap() { return m_mapStringToActions; } - - void RegisterActionName(const STR_String& actname,void* action); - - void* GetActionByName (const STR_String& actname); - void* GetMeshByName(const STR_String& meshname); - - void RegisterGameObjectName(const STR_String& gameobjname,CValue* gameobj); - class CValue* GetGameObjectByName(const STR_String& gameobjname); - - void RegisterGameMeshName(const STR_String& gamemeshname, void* blendobj); - void* FindBlendObjByGameMeshName(const STR_String& gamemeshname); - - void RegisterGameObj(void* blendobj, CValue* gameobj); - void UnregisterGameObj(void* blendobj, CValue* gameobj); - CValue* FindGameObjByBlendObj(void* blendobj); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_LogicManager") -#endif -}; - -#endif /* __SCA_LOGICMANAGER_H__ */ diff --git a/source/gameengine/GameLogic/SCA_MouseManager.cpp b/source/gameengine/GameLogic/SCA_MouseManager.cpp deleted file mode 100644 index 51c03d1e350..00000000000 --- a/source/gameengine/GameLogic/SCA_MouseManager.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Manager for mouse 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/GameLogic/SCA_MouseManager.cpp - * \ingroup gamelogic - */ - - -#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 "EXP_BoolValue.h" -#include "SCA_MouseManager.h" -#include "SCA_MouseSensor.h" -#include "EXP_IntValue.h" -#include "RAS_ICanvas.h" - - -SCA_MouseManager::SCA_MouseManager(SCA_LogicManager* logicmgr, - SCA_IInputDevice* mousedev, - RAS_ICanvas* canvas) - : SCA_EventManager(logicmgr, MOUSE_EVENTMGR), - m_mousedevice (mousedev), - m_canvas(canvas) -{ - m_xpos = 0; - m_ypos = 0; -} - - - -SCA_MouseManager::~SCA_MouseManager() -{ -} - - - -SCA_IInputDevice* SCA_MouseManager::GetInputDevice() -{ - return m_mousedevice; -} - - - -void SCA_MouseManager::NextFrame() -{ - if (m_mousedevice) - { - SG_DList::iterator it(m_sensors); - for (it.begin();!it.end();++it) - { - SCA_MouseSensor* mousesensor = (SCA_MouseSensor*)(*it); - // (0,0) is the Upper Left corner in our local window - // coordinates - if (!mousesensor->IsSuspended()) - { - const SCA_InputEvent& event1 = - m_mousedevice->GetEventValue(SCA_IInputDevice::KX_MOUSEX); - const SCA_InputEvent& event2 = - m_mousedevice->GetEventValue(SCA_IInputDevice::KX_MOUSEY); - - int mx = this->m_canvas->GetMouseX(event1.m_eventval); - int my = this->m_canvas->GetMouseY(event2.m_eventval); - - mousesensor->setX(mx); - mousesensor->setY(my); - - mousesensor->Activate(m_logicmgr); - } - } - } -} - -bool SCA_MouseManager::IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode) -{ - /* We should guard for non-mouse events maybe? A rather silly side */ - /* effect here is that position-change events are considered presses as */ - /* well. */ - - return m_mousedevice->IsPressed(inputcode); -} diff --git a/source/gameengine/GameLogic/SCA_MouseManager.h b/source/gameengine/GameLogic/SCA_MouseManager.h deleted file mode 100644 index a57e52070a7..00000000000 --- a/source/gameengine/GameLogic/SCA_MouseManager.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 SCA_MouseManager.h - * \ingroup gamelogic - * \brief Manager for mouse events. - * - */ - - -#ifndef __SCA_MOUSEMANAGER_H__ -#define __SCA_MOUSEMANAGER_H__ - - -#include "SCA_EventManager.h" - -#include - -using namespace std; - -#include "SCA_IInputDevice.h" - - -class SCA_MouseManager : public SCA_EventManager -{ - - class SCA_IInputDevice* m_mousedevice; - class RAS_ICanvas* m_canvas; - - unsigned short m_xpos; // Cached location of the mouse pointer - unsigned short m_ypos; - -public: - SCA_MouseManager(class SCA_LogicManager* logicmgr,class SCA_IInputDevice* mousedev, class RAS_ICanvas* canvas); - virtual ~SCA_MouseManager(); - - /** - * Checks whether a mouse button is depressed. Ignores requests on non- - * mouse related events. Can also flag mouse movement. - */ - bool IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode); - virtual void NextFrame(); - SCA_IInputDevice* GetInputDevice(); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_MouseManager") -#endif -}; - -#endif /* __SCA_MOUSEMANAGER_H__ */ diff --git a/source/gameengine/GameLogic/SCA_MouseSensor.cpp b/source/gameengine/GameLogic/SCA_MouseSensor.cpp deleted file mode 100644 index 2479e859dea..00000000000 --- a/source/gameengine/GameLogic/SCA_MouseSensor.cpp +++ /dev/null @@ -1,317 +0,0 @@ -/* - * Sensor for mouse input - * - * - * - * ***** 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): José I. Romero (cleanup and fixes) - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/GameLogic/SCA_MouseSensor.cpp - * \ingroup gamelogic - */ - - -#include - -#include "SCA_MouseSensor.h" -#include "SCA_EventManager.h" -#include "SCA_MouseManager.h" -#include "SCA_LogicManager.h" -#include "SCA_IInputDevice.h" -#include "EXP_ConstExpr.h" -#include - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -SCA_MouseSensor::SCA_MouseSensor(SCA_MouseManager* eventmgr, - int startx,int starty, - short int mousemode, - SCA_IObject* gameobj) - : SCA_ISensor(gameobj,eventmgr), - m_x(startx), - m_y(starty) -{ - m_mousemode = mousemode; - m_triggermode = true; - - UpdateHotkey(this); - Init(); -} - -void SCA_MouseSensor::Init() -{ - m_val = (m_invert)?1:0; /* stores the latest attribute */ - m_reset = true; -} - -SCA_MouseSensor::~SCA_MouseSensor() -{ - /* Nothing to be done here. */ -} - -void SCA_MouseSensor::UpdateHotkey(void *self) -{ - // gosh, this function is so damn stupid - // its here because of a design mistake in the mouse sensor, it should only - // have 3 trigger modes (button, wheel, move), and let the user set the - // hotkey separately, like the other sensors. but instead it has a mode for - // each friggin key and i have to update the hotkey based on it... genius! - SCA_MouseSensor* sensor = reinterpret_cast(self); - - switch (sensor->m_mousemode) { - case KX_MOUSESENSORMODE_LEFTBUTTON: - sensor->m_hotkey = SCA_IInputDevice::KX_LEFTMOUSE; - break; - case KX_MOUSESENSORMODE_MIDDLEBUTTON: - sensor->m_hotkey = SCA_IInputDevice::KX_MIDDLEMOUSE; - break; - case KX_MOUSESENSORMODE_RIGHTBUTTON: - sensor->m_hotkey = SCA_IInputDevice::KX_RIGHTMOUSE; - break; - case KX_MOUSESENSORMODE_WHEELUP: - sensor->m_hotkey = SCA_IInputDevice::KX_WHEELUPMOUSE; - break; - case KX_MOUSESENSORMODE_WHEELDOWN: - sensor->m_hotkey = SCA_IInputDevice::KX_WHEELDOWNMOUSE; - break; - default: - ; /* ignore, no hotkey */ - } -} - -CValue* SCA_MouseSensor::GetReplica() -{ - SCA_MouseSensor* replica = new SCA_MouseSensor(*this); - // this will copy properties and so on... - replica->ProcessReplica(); - replica->Init(); - - return replica; -} - - - -bool SCA_MouseSensor::IsPositiveTrigger() -{ - bool result = (m_val != 0); - if (m_invert) - result = !result; - - return result; -} - - - -short int SCA_MouseSensor::GetModeKey() -{ - return m_mousemode; -} - - - -SCA_IInputDevice::KX_EnumInputs SCA_MouseSensor::GetHotKey() -{ - return m_hotkey; -} - - - -bool SCA_MouseSensor::Evaluate() -{ - bool result = false; - bool reset = m_reset && m_level; - SCA_IInputDevice* mousedev = ((SCA_MouseManager *)m_eventmgr)->GetInputDevice(); - - m_reset = false; - switch (m_mousemode) { - case KX_MOUSESENSORMODE_LEFTBUTTON: - case KX_MOUSESENSORMODE_MIDDLEBUTTON: - case KX_MOUSESENSORMODE_RIGHTBUTTON: - case KX_MOUSESENSORMODE_WHEELUP: - case KX_MOUSESENSORMODE_WHEELDOWN: - { - const SCA_InputEvent& mevent = mousedev->GetEventValue(m_hotkey); - switch (mevent.m_status) { - case SCA_InputEvent::KX_JUSTACTIVATED: - m_val = 1; - result = true; - break; - case SCA_InputEvent::KX_JUSTRELEASED: - m_val = 0; - result = true; - break; - case SCA_InputEvent::KX_ACTIVE: - if (m_val == 0) - { - m_val = 1; - if (m_level) - result = true; - } - break; - default: - if (m_val == 1) - { - m_val = 0; - result = true; - } - break; - } - break; - } - case KX_MOUSESENSORMODE_MOVEMENT: - { - const SCA_InputEvent& eventX = mousedev->GetEventValue(SCA_IInputDevice::KX_MOUSEX); - const SCA_InputEvent& eventY = mousedev->GetEventValue(SCA_IInputDevice::KX_MOUSEY); - - if (eventX.m_status == SCA_InputEvent::KX_JUSTACTIVATED || - eventY.m_status == SCA_InputEvent::KX_JUSTACTIVATED || - eventX.m_status == SCA_InputEvent::KX_ACTIVE || - eventY.m_status == SCA_InputEvent::KX_ACTIVE) - { - m_val = 1; - result = true; - } - else if (eventX.m_status == SCA_InputEvent::KX_JUSTRELEASED || - eventY.m_status == SCA_InputEvent::KX_JUSTRELEASED ) - { - m_val = 0; - result = true; - } - else //KX_NO_IMPUTSTATUS - { - if (m_val == 1) - { - m_val = 0; - result = true; - } - } - - break; - } - default: - ; /* error */ - } - - if (reset) - // force an event - result = true; - return result; -} - -void SCA_MouseSensor::setX(short x) -{ - m_x = x; -} - -void SCA_MouseSensor::setY(short y) -{ - m_y = y; -} - -bool SCA_MouseSensor::isValid(SCA_MouseSensor::KX_MOUSESENSORMODE m) -{ - return ((m > KX_MOUSESENSORMODE_NODEF) && (m < KX_MOUSESENSORMODE_MAX)); -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -KX_PYMETHODDEF_DOC_O(SCA_MouseSensor, getButtonStatus, -"getButtonStatus(button)\n" -"\tGet the given button's status (KX_INPUT_NONE, KX_INPUT_NONE, KX_INPUT_JUST_ACTIVATED, KX_INPUT_ACTIVE, KX_INPUT_JUST_RELEASED).\n") -{ - if (PyLong_Check(value)) - { - SCA_IInputDevice::KX_EnumInputs button = (SCA_IInputDevice::KX_EnumInputs)PyLong_AsLong(value); - - if ((button < SCA_IInputDevice::KX_LEFTMOUSE) || - (button > SCA_IInputDevice::KX_RIGHTMOUSE)) - { - PyErr_SetString(PyExc_ValueError, "sensor.getButtonStatus(int): Mouse Sensor, invalid button specified!"); - return NULL; - } - - SCA_IInputDevice* mousedev = ((SCA_MouseManager *)m_eventmgr)->GetInputDevice(); - const SCA_InputEvent& event = mousedev->GetEventValue(button); - return PyLong_FromLong(event.m_status); - } - - Py_RETURN_NONE; -} - -/* ------------------------------------------------------------------------- */ -/* Python Integration Hooks */ -/* ------------------------------------------------------------------------- */ - -PyTypeObject SCA_MouseSensor::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "SCA_MouseSensor", - 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 SCA_MouseSensor::Methods[] = { - KX_PYMETHODTABLE_O(SCA_MouseSensor, getButtonStatus), - {NULL,NULL} //Sentinel -}; - -int SCA_MouseSensor::UpdateHotkeyPy(void *self, const PyAttributeDef*) -{ - UpdateHotkey(self); - // return value is used in py_setattro(), - // 0=attribute checked ok (see Attributes array definition) - return 0; -} - -PyAttributeDef SCA_MouseSensor::Attributes[] = { - KX_PYATTRIBUTE_SHORT_RW_CHECK("mode",KX_MOUSESENSORMODE_NODEF,KX_MOUSESENSORMODE_MAX-1,true,SCA_MouseSensor,m_mousemode,UpdateHotkeyPy), - KX_PYATTRIBUTE_SHORT_LIST_RO("position",SCA_MouseSensor,m_x,2), - { NULL } //Sentinel -}; - -#endif // WITH_PYTHON - -/* eof */ diff --git a/source/gameengine/GameLogic/SCA_MouseSensor.h b/source/gameengine/GameLogic/SCA_MouseSensor.h deleted file mode 100644 index 2660aaeacb5..00000000000 --- a/source/gameengine/GameLogic/SCA_MouseSensor.h +++ /dev/null @@ -1,120 +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): José I. Romero (cleanup and fixes) - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file SCA_MouseSensor.h - * \ingroup gamelogic - * \brief Senses mouse events - */ - -#ifndef __SCA_MOUSESENSOR_H__ -#define __SCA_MOUSESENSOR_H__ - -#include "SCA_ISensor.h" -#include "EXP_BoolValue.h" -#include "SCA_IInputDevice.h" - -class SCA_MouseSensor : public SCA_ISensor -{ - Py_Header - - /** - * Use SCA_IInputDevice values to encode the mouse mode for now. - */ - short int m_mousemode; - /** - * Triggermode true means all mouse events trigger. Useful mainly - * for button presses. - */ - bool m_triggermode; - /** - * Remember the last state update - */ - int m_val; - - SCA_IInputDevice::KX_EnumInputs m_hotkey; - - /** - * valid x coordinate, MUST be followed by y coordinate - */ - short m_x; - - /** - * valid y coordinate - */ - short m_y; - - public: - /** - * Allowable modes for the trigger status of the mouse sensor. - */ - enum KX_MOUSESENSORMODE { - KX_MOUSESENSORMODE_NODEF = 0, - KX_MOUSESENSORMODE_LEFTBUTTON, - KX_MOUSESENSORMODE_MIDDLEBUTTON, - KX_MOUSESENSORMODE_RIGHTBUTTON, - KX_MOUSESENSORMODE_WHEELUP, - KX_MOUSESENSORMODE_WHEELDOWN, - KX_MOUSESENSORMODE_POSITION, - KX_MOUSESENSORMODE_POSITIONX, - KX_MOUSESENSORMODE_POSITIONY, - KX_MOUSESENSORMODE_MOVEMENT, - KX_MOUSESENSORMODE_MAX - }; - - bool isValid(KX_MOUSESENSORMODE); - - SCA_MouseSensor(class SCA_MouseManager* keybdmgr, - int startx,int starty, - short int mousemode, - SCA_IObject* gameobj); - - virtual ~SCA_MouseSensor(); - virtual CValue* GetReplica(); - virtual bool Evaluate(); - virtual void Init(); - virtual bool IsPositiveTrigger(); - short int GetModeKey(); - SCA_IInputDevice::KX_EnumInputs GetHotKey(); - void setX(short x); - void setY(short y); - - static void UpdateHotkey(void *self); - - -#ifdef WITH_PYTHON - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - - static int UpdateHotkeyPy(void *self, const PyAttributeDef *); - - // get button status - KX_PYMETHOD_DOC_O(SCA_MouseSensor,getButtonStatus); -#endif -}; - -#endif /* __SCA_MOUSESENSOR_H__ */ diff --git a/source/gameengine/GameLogic/SCA_NANDController.cpp b/source/gameengine/GameLogic/SCA_NANDController.cpp deleted file mode 100644 index 6a00c110e2b..00000000000 --- a/source/gameengine/GameLogic/SCA_NANDController.cpp +++ /dev/null @@ -1,133 +0,0 @@ -/* - * 'Nand' together all inputs - * - * - * ***** 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/GameLogic/SCA_NANDController.cpp - * \ingroup gamelogic - */ - - -#include "SCA_NANDController.h" -#include "SCA_ISensor.h" -#include "SCA_LogicManager.h" -#include "EXP_BoolValue.h" - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -SCA_NANDController::SCA_NANDController(SCA_IObject* gameobj) - : - SCA_IController(gameobj) -{ -} - - - -SCA_NANDController::~SCA_NANDController() -{ -} - - - -void SCA_NANDController::Trigger(SCA_LogicManager* logicmgr) -{ - - bool sensorresult = false; - - for (vector::const_iterator is=m_linkedsensors.begin(); - !(is==m_linkedsensors.end());is++) - { - SCA_ISensor* sensor = *is; - if (!sensor->GetState()) - { - sensorresult = true; - break; - } - } - - for (vector::const_iterator i=m_linkedactuators.begin(); - !(i==m_linkedactuators.end());i++) - { - SCA_IActuator* actua = *i; - logicmgr->AddActiveActuator(actua,sensorresult); - } -} - - - -CValue* SCA_NANDController::GetReplica() -{ - CValue* replica = new SCA_NANDController(*this); - // this will copy properties and so on... - replica->ProcessReplica(); - - return replica; -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject SCA_NANDController::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "SCA_NANDController", - 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_IController::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef SCA_NANDController::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef SCA_NANDController::Attributes[] = { - { NULL } //Sentinel -}; - -#endif - -/* eof */ diff --git a/source/gameengine/GameLogic/SCA_NANDController.h b/source/gameengine/GameLogic/SCA_NANDController.h deleted file mode 100644 index a3f02908dd2..00000000000 --- a/source/gameengine/GameLogic/SCA_NANDController.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 SCA_NANDController.h - * \ingroup gamelogic - */ - -#ifndef __SCA_NANDCONTROLLER_H__ -#define __SCA_NANDCONTROLLER_H__ - -#include "SCA_IController.h" - -class SCA_NANDController : public SCA_IController -{ - Py_Header - //virtual void Trigger(class SCA_LogicManager* logicmgr); -public: - SCA_NANDController(SCA_IObject* gameobj); - virtual ~SCA_NANDController(); - virtual CValue* GetReplica(); - virtual void Trigger(SCA_LogicManager* logicmgr); - - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ -}; - -#endif /* __SCA_NANDCONTROLLER_H__ */ diff --git a/source/gameengine/GameLogic/SCA_NORController.cpp b/source/gameengine/GameLogic/SCA_NORController.cpp deleted file mode 100644 index fb09617e060..00000000000 --- a/source/gameengine/GameLogic/SCA_NORController.cpp +++ /dev/null @@ -1,133 +0,0 @@ -/* - * 'Nor' together all inputs - * - * - * ***** 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/GameLogic/SCA_NORController.cpp - * \ingroup gamelogic - */ - - -#include "SCA_NORController.h" -#include "SCA_ISensor.h" -#include "SCA_LogicManager.h" -#include "EXP_BoolValue.h" - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -SCA_NORController::SCA_NORController(SCA_IObject* gameobj) - : - SCA_IController(gameobj) -{ -} - - - -SCA_NORController::~SCA_NORController() -{ -} - - - -void SCA_NORController::Trigger(SCA_LogicManager* logicmgr) -{ - - bool sensorresult = true; - - for (vector::const_iterator is=m_linkedsensors.begin(); - !(is==m_linkedsensors.end());is++) - { - SCA_ISensor* sensor = *is; - if (sensor->GetState()) - { - sensorresult = false; - break; - } - } - - for (vector::const_iterator i=m_linkedactuators.begin(); - !(i==m_linkedactuators.end());i++) - { - SCA_IActuator* actua = *i; - logicmgr->AddActiveActuator(actua,sensorresult); - } -} - - - -CValue* SCA_NORController::GetReplica() -{ - CValue* replica = new SCA_NORController(*this); - // this will copy properties and so on... - replica->ProcessReplica(); - - return replica; -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject SCA_NORController::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "SCA_NORController", - 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_IController::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef SCA_NORController::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef SCA_NORController::Attributes[] = { - { NULL } //Sentinel -}; - -#endif // WITH_PYTHON - -/* eof */ diff --git a/source/gameengine/GameLogic/SCA_NORController.h b/source/gameengine/GameLogic/SCA_NORController.h deleted file mode 100644 index ec8159de8d1..00000000000 --- a/source/gameengine/GameLogic/SCA_NORController.h +++ /dev/null @@ -1,48 +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 SCA_NORController.h - * \ingroup gamelogic - */ - -#ifndef __SCA_NORCONTROLLER_H__ -#define __SCA_NORCONTROLLER_H__ - -#include "SCA_IController.h" - -class SCA_NORController : public SCA_IController -{ - Py_Header - //virtual void Trigger(class SCA_LogicManager* logicmgr); -public: - SCA_NORController(SCA_IObject* gameobj); - virtual ~SCA_NORController(); - virtual CValue* GetReplica(); - virtual void Trigger(SCA_LogicManager* logicmgr); -}; - -#endif /* __SCA_NORCONTROLLER_H__ */ diff --git a/source/gameengine/GameLogic/SCA_ORController.cpp b/source/gameengine/GameLogic/SCA_ORController.cpp deleted file mode 100644 index 8a59bdf1b89..00000000000 --- a/source/gameengine/GameLogic/SCA_ORController.cpp +++ /dev/null @@ -1,129 +0,0 @@ -/* - * 'Or' together all inputs - * - * - * ***** 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/GameLogic/SCA_ORController.cpp - * \ingroup gamelogic - */ - - -#include "SCA_ORController.h" -#include "SCA_ISensor.h" -#include "SCA_LogicManager.h" -#include "EXP_BoolValue.h" - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -SCA_ORController::SCA_ORController(SCA_IObject* gameobj) - :SCA_IController(gameobj) -{ -} - - - -SCA_ORController::~SCA_ORController() -{ -} - - - -CValue* SCA_ORController::GetReplica() -{ - CValue* replica = new SCA_ORController(*this); - // this will copy properties and so on... - replica->ProcessReplica(); - - return replica; -} - - -void SCA_ORController::Trigger(SCA_LogicManager* logicmgr) -{ - - bool sensorresult = false; - SCA_ISensor* sensor; - - vector::const_iterator is=m_linkedsensors.begin(); - while ( (!sensorresult) && (!(is==m_linkedsensors.end())) ) - { - sensor = *is; - if (sensor->GetState()) sensorresult = true; - is++; - } - - for (vector::const_iterator i=m_linkedactuators.begin(); - !(i==m_linkedactuators.end());i++) - { - SCA_IActuator* actua = *i; - logicmgr->AddActiveActuator(actua,sensorresult); - } -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject SCA_ORController::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "SCA_ORController", - 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_IController::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef SCA_ORController::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef SCA_ORController::Attributes[] = { - { NULL } //Sentinel -}; - -#endif // WITH_PYTHON - -/* eof */ diff --git a/source/gameengine/GameLogic/SCA_ORController.h b/source/gameengine/GameLogic/SCA_ORController.h deleted file mode 100644 index 9499c893c72..00000000000 --- a/source/gameengine/GameLogic/SCA_ORController.h +++ /dev/null @@ -1,49 +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 SCA_ORController.h - * \ingroup gamelogic - */ - -#ifndef __SCA_ORCONTROLLER_H__ -#define __SCA_ORCONTROLLER_H__ - -#include "SCA_IController.h" - -class SCA_ORController : public SCA_IController -{ - Py_Header - //virtual void Trigger(class SCA_LogicManager* logicmgr); -public: - SCA_ORController(SCA_IObject* gameobj); - - virtual ~SCA_ORController(); - virtual CValue* GetReplica(); - virtual void Trigger(SCA_LogicManager* logicmgr); -}; - -#endif /* __SCA_ORCONTROLLER_H__ */ diff --git a/source/gameengine/GameLogic/SCA_PropertyActuator.cpp b/source/gameengine/GameLogic/SCA_PropertyActuator.cpp deleted file mode 100644 index f2907ca6361..00000000000 --- a/source/gameengine/GameLogic/SCA_PropertyActuator.cpp +++ /dev/null @@ -1,293 +0,0 @@ -/* - * Assign, change, copy properties - * - * - * ***** 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/GameLogic/SCA_PropertyActuator.cpp - * \ingroup gamelogic - */ - - -#include - -#include "SCA_PropertyActuator.h" -#include "EXP_InputParser.h" -#include "EXP_Operator2Expr.h" -#include "EXP_ConstExpr.h" - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -SCA_PropertyActuator::SCA_PropertyActuator(SCA_IObject* gameobj,SCA_IObject* sourceObj,const STR_String& propname,const STR_String& expr,int acttype) - : SCA_IActuator(gameobj, KX_ACT_PROPERTY), - m_type(acttype), - m_propname(propname), - m_exprtxt(expr), - m_sourceObj(sourceObj) -{ - // protect ourselves against someone else deleting the source object - // don't protect against ourselves: it would create a dead lock - if (m_sourceObj) - m_sourceObj->RegisterActuator(this); -} - -SCA_PropertyActuator::~SCA_PropertyActuator() -{ - if (m_sourceObj) - m_sourceObj->UnregisterActuator(this); -} - -bool SCA_PropertyActuator::Update() -{ - bool result = false; - - bool bNegativeEvent = IsNegativeEvent(); - RemoveAllEvents(); - CValue* propowner = GetParent(); - - if (bNegativeEvent) - { - if (m_type==KX_ACT_PROP_LEVEL) - { - CValue* newval = new CBoolValue(false); - CValue* oldprop = propowner->GetProperty(m_propname); - if (oldprop) - { - oldprop->SetValue(newval); - } - newval->Release(); - } - return false; - } - - - CParser parser; - parser.SetContext( propowner->AddRef()); - - CExpression* userexpr= NULL; - - if (m_type==KX_ACT_PROP_TOGGLE) - { - /* don't use */ - CValue* newval; - CValue* oldprop = propowner->GetProperty(m_propname); - if (oldprop) - { - newval = new CBoolValue((oldprop->GetNumber()==0.0) ? true:false); - oldprop->SetValue(newval); - } else - { /* as not been assigned, evaluate as false, so assign true */ - newval = new CBoolValue(true); - propowner->SetProperty(m_propname,newval); - } - newval->Release(); - } - else if (m_type==KX_ACT_PROP_LEVEL) - { - CValue* newval = new CBoolValue(true); - CValue* oldprop = propowner->GetProperty(m_propname); - if (oldprop) - { - oldprop->SetValue(newval); - } else - { - propowner->SetProperty(m_propname,newval); - } - newval->Release(); - } - else if ((userexpr = parser.ProcessText(m_exprtxt))) { - switch (m_type) - { - - case KX_ACT_PROP_ASSIGN: - { - - CValue* newval = userexpr->Calculate(); - CValue* oldprop = propowner->GetProperty(m_propname); - if (oldprop) - { - oldprop->SetValue(newval); - } else - { - propowner->SetProperty(m_propname,newval); - } - newval->Release(); - break; - } - case KX_ACT_PROP_ADD: - { - CValue* oldprop = propowner->GetProperty(m_propname); - if (oldprop) - { - // int waarde = (int)oldprop->GetNumber(); /*unused*/ - CExpression* expr = new COperator2Expr(VALUE_ADD_OPERATOR,new CConstExpr(oldprop->AddRef()), - userexpr->AddRef()); - - CValue* newprop = expr->Calculate(); - oldprop->SetValue(newprop); - newprop->Release(); - expr->Release(); - - } - - break; - } - case KX_ACT_PROP_COPY: - { - if (m_sourceObj) - { - CValue* copyprop = m_sourceObj->GetProperty(m_exprtxt); - if (copyprop) - { - CValue *val = copyprop->GetReplica(); - GetParent()->SetProperty( - m_propname, - val); - val->Release(); - - } - } - break; - } - /* case KX_ACT_PROP_TOGGLE: */ /* accounted for above, no need for userexpr */ - default: - { - - } - } - - userexpr->Release(); - } - - return result; -} - - bool - -SCA_PropertyActuator:: - -isValid( - - SCA_PropertyActuator::KX_ACT_PROP_MODE mode - -) { - bool res = false; - res = ((mode > KX_ACT_PROP_NODEF) && (mode < KX_ACT_PROP_MAX)); - return res; -} - - - CValue* - -SCA_PropertyActuator:: - -GetReplica() -{ - - SCA_PropertyActuator* replica = new SCA_PropertyActuator(*this); - - replica->ProcessReplica(); - return replica; - -}; - -void SCA_PropertyActuator::ProcessReplica() -{ - // no need to check for self reference like in the constructor: - // the replica will always have a different parent - if (m_sourceObj) - m_sourceObj->RegisterActuator(this); - SCA_IActuator::ProcessReplica(); -} - -bool SCA_PropertyActuator::UnlinkObject(SCA_IObject* clientobj) -{ - if (clientobj == m_sourceObj) - { - // this object is being deleted, we cannot continue to track it. - m_sourceObj = NULL; - return true; - } - return false; -} - -void SCA_PropertyActuator::Relink(CTR_Map *obj_map) -{ - void **h_obj = (*obj_map)[m_sourceObj]; - if (h_obj) { - if (m_sourceObj) - m_sourceObj->UnregisterActuator(this); - m_sourceObj = (SCA_IObject*)(*h_obj); - m_sourceObj->RegisterActuator(this); - } -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject SCA_PropertyActuator::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "SCA_PropertyActuator", - 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 SCA_PropertyActuator::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef SCA_PropertyActuator::Attributes[] = { - KX_PYATTRIBUTE_STRING_RW_CHECK("propName",0,MAX_PROP_NAME,false,SCA_PropertyActuator,m_propname,CheckProperty), - KX_PYATTRIBUTE_STRING_RW("value",0,100,false,SCA_PropertyActuator,m_exprtxt), - KX_PYATTRIBUTE_INT_RW("mode", KX_ACT_PROP_NODEF+1, KX_ACT_PROP_MAX-1, false, SCA_PropertyActuator, m_type), /* ATTR_TODO add constents to game logic dict */ - { NULL } //Sentinel -}; - -#endif - -/* eof */ diff --git a/source/gameengine/GameLogic/SCA_PropertyActuator.h b/source/gameengine/GameLogic/SCA_PropertyActuator.h deleted file mode 100644 index 228ecf94bc4..00000000000 --- a/source/gameengine/GameLogic/SCA_PropertyActuator.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 SCA_PropertyActuator.h - * \ingroup gamelogic - */ - -#ifndef __SCA_PROPERTYACTUATOR_H__ -#define __SCA_PROPERTYACTUATOR_H__ - -#include "SCA_IActuator.h" - -class SCA_PropertyActuator : public SCA_IActuator -{ - Py_Header - - enum KX_ACT_PROP_MODE { - KX_ACT_PROP_NODEF = 0, - KX_ACT_PROP_ASSIGN, - KX_ACT_PROP_ADD, - KX_ACT_PROP_COPY, - KX_ACT_PROP_TOGGLE, - KX_ACT_PROP_LEVEL, - KX_ACT_PROP_MAX - }; - - /**check whether this value is valid */ - bool isValid(KX_ACT_PROP_MODE mode); - - int m_type; - STR_String m_propname; - STR_String m_exprtxt; - SCA_IObject* m_sourceObj; // for copy property actuator - -public: - - - - SCA_PropertyActuator( - SCA_IObject* gameobj, - SCA_IObject* sourceObj, - const STR_String& propname, - const STR_String& expr, - int acttype); - - - ~SCA_PropertyActuator(); - - CValue* - GetReplica( - ); - - virtual void ProcessReplica(); - virtual bool UnlinkObject(SCA_IObject* clientobj); - virtual void Relink(CTR_Map *obj_map); - - virtual bool - Update(); - - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - -}; - -#endif /* __KX_PROPERTYACTUATOR_DOC */ diff --git a/source/gameengine/GameLogic/SCA_PropertyEventManager.cpp b/source/gameengine/GameLogic/SCA_PropertyEventManager.cpp deleted file mode 100644 index 854069690da..00000000000 --- a/source/gameengine/GameLogic/SCA_PropertyEventManager.cpp +++ /dev/null @@ -1,57 +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/GameLogic/SCA_PropertyEventManager.cpp - * \ingroup gamelogic - */ - - -#include "SCA_ISensor.h" -#include "SCA_PropertyEventManager.h" - - -SCA_PropertyEventManager::SCA_PropertyEventManager(class SCA_LogicManager* logicmgr) - : SCA_EventManager(logicmgr, PROPERTY_EVENTMGR) -{ -} - - - -SCA_PropertyEventManager::~SCA_PropertyEventManager() -{ - -} - -void SCA_PropertyEventManager::NextFrame() -{ - // check for changed properties - SG_DList::iterator it(m_sensors); - for (it.begin();!it.end();++it) - { - (*it)->Activate(m_logicmgr); - } -} diff --git a/source/gameengine/GameLogic/SCA_PropertyEventManager.h b/source/gameengine/GameLogic/SCA_PropertyEventManager.h deleted file mode 100644 index 554fe686df2..00000000000 --- a/source/gameengine/GameLogic/SCA_PropertyEventManager.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 SCA_PropertyEventManager.h - * \ingroup gamelogic - */ - -#ifndef __SCA_PROPERTYEVENTMANAGER_H__ -#define __SCA_PROPERTYEVENTMANAGER_H__ - -#include "SCA_EventManager.h" - -#include - -using namespace std; - -class SCA_PropertyEventManager : public SCA_EventManager -{ -public: - SCA_PropertyEventManager(class SCA_LogicManager* logicmgr); - virtual ~SCA_PropertyEventManager(); - virtual void NextFrame(); - //SCA_LogicManager* GetLogicManager() { return m_logicmgr;} - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_PropertyEventManager") -#endif -}; - -#endif /* __SCA_PROPERTYEVENTMANAGER_H__ */ diff --git a/source/gameengine/GameLogic/SCA_PropertySensor.cpp b/source/gameengine/GameLogic/SCA_PropertySensor.cpp deleted file mode 100644 index e34a5296139..00000000000 --- a/source/gameengine/GameLogic/SCA_PropertySensor.cpp +++ /dev/null @@ -1,332 +0,0 @@ -/* - * Property 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/GameLogic/SCA_PropertySensor.cpp - * \ingroup gamelogic - */ - - -#include - -#include -#include "SCA_PropertySensor.h" -#include "EXP_Operator2Expr.h" -#include "EXP_ConstExpr.h" -#include "EXP_InputParser.h" -#include "EXP_StringValue.h" -#include "SCA_EventManager.h" -#include "SCA_LogicManager.h" -#include "EXP_BoolValue.h" -#include "EXP_FloatValue.h" -#include - -SCA_PropertySensor::SCA_PropertySensor(SCA_EventManager* eventmgr, - SCA_IObject* gameobj, - const STR_String& propname, - const STR_String& propval, - const STR_String& propmaxval, - KX_PROPSENSOR_TYPE checktype) - : SCA_ISensor(gameobj,eventmgr), - m_checktype(checktype), - m_checkpropval(propval), - m_checkpropmaxval(propmaxval), - m_checkpropname(propname) -{ - //CParser pars; - //pars.SetContext(this->AddRef()); - //CValue* resultval = m_rightexpr->Calculate(); - - CValue* orgprop = GetParent()->FindIdentifier(m_checkpropname); - if (!orgprop->IsError()) - { - m_previoustext = orgprop->GetText(); - } - orgprop->Release(); - - Init(); -} - -void SCA_PropertySensor::Init() -{ - m_recentresult = false; - m_lastresult = m_invert?true:false; - m_reset = true; -} - -CValue* SCA_PropertySensor::GetReplica() -{ - SCA_PropertySensor* replica = new SCA_PropertySensor(*this); - // m_range_expr must be recalculated on replica! - replica->ProcessReplica(); - replica->Init(); - - return replica; -} - - - -bool SCA_PropertySensor::IsPositiveTrigger() -{ - bool result = m_recentresult;//CheckPropertyCondition(); - if (m_invert) - result = !result; - - return result; -} - - - -SCA_PropertySensor::~SCA_PropertySensor() -{ -} - - - -bool SCA_PropertySensor::Evaluate() -{ - bool result = CheckPropertyCondition(); - bool reset = m_reset && m_level; - - m_reset = false; - if (m_lastresult!=result) - { - m_lastresult = result; - return true; - } - return (reset) ? true : false; -} - - -bool SCA_PropertySensor::CheckPropertyCondition() -{ - m_recentresult=false; - bool result=false; - bool reverse = false; - switch (m_checktype) - { - case KX_PROPSENSOR_NOTEQUAL: - reverse = true; - ATTR_FALLTHROUGH; - case KX_PROPSENSOR_EQUAL: - { - CValue* orgprop = GetParent()->FindIdentifier(m_checkpropname); - if (!orgprop->IsError()) - { - const STR_String& testprop = orgprop->GetText(); - // Force strings to upper case, to avoid confusion in - // bool tests. It's stupid the prop's identity is lost - // on the way here... - if ((&testprop == &CBoolValue::sTrueString) || (&testprop == &CBoolValue::sFalseString)) { - m_checkpropval.Upper(); - } - result = (testprop == m_checkpropval); - - /* Patch: floating point values cant use strings usefully since you can have "0.0" == "0.0000" - * this could be made into a generic Value class function for comparing values with a string. - */ - if (result==false && (orgprop->GetValueType() == VALUE_FLOAT_TYPE)) { - float f; - if (sscanf(m_checkpropval.ReadPtr(), "%f", &f) == 1) { - result = (f == ((CFloatValue *)orgprop)->GetFloat()); - } - else { - /* error */ - } - } - /* end patch */ - } - orgprop->Release(); - - if (reverse) - result = !result; - break; - - } - - case KX_PROPSENSOR_EXPRESSION: - { -#if 0 - if (m_rightexpr) - { - CValue* resultval = m_rightexpr->Calculate(); - if (resultval->IsError()) - { - int i=0; - STR_String errortest = resultval->GetText(); - printf(errortest); - - } else - { - result = resultval->GetNumber() != 0; - } - } -#endif - break; - } - case KX_PROPSENSOR_INTERVAL: - { - CValue* orgprop = GetParent()->FindIdentifier(m_checkpropname); - if (!orgprop->IsError()) - { - const float min = m_checkpropval.ToFloat(); - const float max = m_checkpropmaxval.ToFloat(); - float val; - - if (orgprop->GetValueType() == VALUE_STRING_TYPE) { - val = orgprop->GetText().ToFloat(); - } - else { - val = orgprop->GetNumber(); - } - - result = (min <= val) && (val <= max); - } - orgprop->Release(); - - break; - } - case KX_PROPSENSOR_CHANGED: - { - CValue* orgprop = GetParent()->FindIdentifier(m_checkpropname); - - if (!orgprop->IsError()) - { - if (m_previoustext != orgprop->GetText()) - { - m_previoustext = orgprop->GetText(); - result = true; - } - } - orgprop->Release(); - - //cout << " \nSens:Prop:changed!"; /* need implementation here!!! */ - break; - } - case KX_PROPSENSOR_LESSTHAN: - reverse = true; - ATTR_FALLTHROUGH; - case KX_PROPSENSOR_GREATERTHAN: - { - CValue* orgprop = GetParent()->FindIdentifier(m_checkpropname); - if (!orgprop->IsError()) - { - const float ref = m_checkpropval.ToFloat(); - float val; - - if (orgprop->GetValueType() == VALUE_STRING_TYPE) { - val = orgprop->GetText().ToFloat(); - } - else { - val = orgprop->GetNumber(); - } - - if (reverse) { - result = val < ref; - } - else { - result = val > ref; - } - - } - orgprop->Release(); - - break; - } - default: - ; /* error */ - } - - //the concept of Edge and Level triggering has unwanted effect for KX_PROPSENSOR_CHANGED - //see Game Engine bugtracker [ #3809 ] - m_recentresult = result; - - return result; -} - -CValue* SCA_PropertySensor::FindIdentifier(const STR_String& identifiername) -{ - return GetParent()->FindIdentifier(identifiername); -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -int SCA_PropertySensor::validValueForProperty(void *self, const PyAttributeDef*) -{ - /* If someone actually do type checking please make sure the 'max' and 'min' - * are checked as well (currently they are calling the PrecalculateRangeExpression - * function directly */ - - /* There is no type checking at this moment, unfortunately... */ - return 0; -} - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject SCA_PropertySensor::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "SCA_PropertySensor", - 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 SCA_PropertySensor::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef SCA_PropertySensor::Attributes[] = { - KX_PYATTRIBUTE_INT_RW("mode",KX_PROPSENSOR_NODEF,KX_PROPSENSOR_MAX-1,false,SCA_PropertySensor,m_checktype), - KX_PYATTRIBUTE_STRING_RW_CHECK("propName",0,MAX_PROP_NAME,false,SCA_PropertySensor,m_checkpropname,CheckProperty), - KX_PYATTRIBUTE_STRING_RW_CHECK("value",0,100,false,SCA_PropertySensor,m_checkpropval,validValueForProperty), - KX_PYATTRIBUTE_STRING_RW_CHECK("min",0,100,false,SCA_PropertySensor,m_checkpropval,validValueForProperty), - KX_PYATTRIBUTE_STRING_RW_CHECK("max",0,100,false,SCA_PropertySensor,m_checkpropmaxval,validValueForProperty), - { NULL } //Sentinel -}; - -#endif // WITH_PYTHON - -/* eof */ diff --git a/source/gameengine/GameLogic/SCA_PropertySensor.h b/source/gameengine/GameLogic/SCA_PropertySensor.h deleted file mode 100644 index f9cfb5fb1d2..00000000000 --- a/source/gameengine/GameLogic/SCA_PropertySensor.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 SCA_PropertySensor.h - * \ingroup gamelogic - * \brief Property sensor - */ - -#ifndef __SCA_PROPERTYSENSOR_H__ -#define __SCA_PROPERTYSENSOR_H__ - -#include "SCA_ISensor.h" - -class SCA_PropertySensor : public SCA_ISensor -{ - Py_Header - //class CExpression* m_rightexpr; - int m_checktype; - STR_String m_checkpropval; - STR_String m_checkpropmaxval; - STR_String m_checkpropname; - STR_String m_previoustext; - bool m_lastresult; - bool m_recentresult; - - protected: - -public: - enum KX_PROPSENSOR_TYPE { - KX_PROPSENSOR_NODEF = 0, - KX_PROPSENSOR_EQUAL, - KX_PROPSENSOR_NOTEQUAL, - KX_PROPSENSOR_INTERVAL, - KX_PROPSENSOR_CHANGED, - KX_PROPSENSOR_EXPRESSION, - KX_PROPSENSOR_LESSTHAN, - KX_PROPSENSOR_GREATERTHAN, - KX_PROPSENSOR_MAX - }; - - const STR_String S_KX_PROPSENSOR_EQ_STRING; - - SCA_PropertySensor(class SCA_EventManager* eventmgr, - SCA_IObject* gameobj, - const STR_String& propname, - const STR_String& propval, - const STR_String& propmaxval, - KX_PROPSENSOR_TYPE checktype); - - virtual ~SCA_PropertySensor(); - virtual CValue* GetReplica(); - virtual void Init(); - bool CheckPropertyCondition(); - - virtual bool Evaluate(); - virtual bool IsPositiveTrigger(); - virtual CValue* FindIdentifier(const STR_String& identifiername); - -#ifdef WITH_PYTHON - - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - - /** - * Test whether this is a sensible value (type check) - */ - static int validValueForProperty(void* self, const PyAttributeDef*); - -#endif -}; - -#endif - diff --git a/source/gameengine/GameLogic/SCA_PythonController.cpp b/source/gameengine/GameLogic/SCA_PythonController.cpp deleted file mode 100644 index fd2e723741c..00000000000 --- a/source/gameengine/GameLogic/SCA_PythonController.cpp +++ /dev/null @@ -1,539 +0,0 @@ -/* - * Execute Python scripts - * - * - * ***** 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/GameLogic/SCA_PythonController.cpp - * \ingroup gamelogic - */ - - -#include - -#include "SCA_PythonController.h" -#include "SCA_LogicManager.h" -#include "SCA_ISensor.h" -#include "SCA_IActuator.h" -#include "EXP_PyObjectPlus.h" - -#ifdef WITH_PYTHON -#include "compile.h" -#include "eval.h" -#endif // WITH_PYTHON - -#include - - -// initialize static member variables -SCA_PythonController* SCA_PythonController::m_sCurrentController = NULL; - - -SCA_PythonController::SCA_PythonController(SCA_IObject* gameobj, int mode) - : SCA_IController(gameobj), -#ifdef WITH_PYTHON - m_bytecode(NULL), - m_function(NULL), -#endif - m_function_argc(0), - m_bModified(true), - m_debug(false), - m_mode(mode) -#ifdef WITH_PYTHON - , m_pythondictionary(NULL) -#endif - -{ - -} - -#if 0 -//debugging -CValue *SCA_PythonController::AddRef() -{ - //printf("AddRef refcount = %i\n",GetRefCount()); - return CValue::AddRef(); -} -int SCA_PythonController::Release() -{ - //printf("Release refcount = %i\n",GetRefCount()); - return CValue::Release(); -} -#endif - -SCA_PythonController::~SCA_PythonController() -{ - -#ifdef WITH_PYTHON - //printf("released python byte script\n"); - - Py_XDECREF(m_bytecode); - Py_XDECREF(m_function); - - if (m_pythondictionary) { - // break any circular references in the dictionary - PyDict_Clear(m_pythondictionary); - Py_DECREF(m_pythondictionary); - } -#endif -} - - - -CValue* SCA_PythonController::GetReplica() -{ - SCA_PythonController* replica = new SCA_PythonController(*this); - -#ifdef WITH_PYTHON - /* why is this needed at all??? - m_bytecode is NULL'd below so this doesnt make sense - * but removing it crashes blender (with YoFrankie). so leave in for now - Campbell */ - Py_XINCREF(replica->m_bytecode); - - Py_XINCREF(replica->m_function); // this is ok since its not set to NULL - replica->m_bModified = replica->m_bytecode == NULL; - - // The replica->m_pythondictionary is stolen - replace with a copy. - if (m_pythondictionary) - replica->m_pythondictionary = PyDict_Copy(m_pythondictionary); - -#if 0 - // The other option is to incref the replica->m_pythondictionary - - // the replica objects can then share data. - if (m_pythondictionary) - Py_INCREF(replica->m_pythondictionary); -#endif - -#endif /* WITH_PYTHON */ - - // this will copy properties and so on... - replica->ProcessReplica(); - - return replica; -} - - - -void SCA_PythonController::SetScriptText(const STR_String& text) -{ - m_scriptText = text; - m_bModified = true; -} - - - -void SCA_PythonController::SetScriptName(const STR_String& name) -{ - m_scriptName = name; -} - - -#ifdef WITH_PYTHON -void SCA_PythonController::SetNamespace(PyObject* pythondictionary) -{ - if (m_pythondictionary) - { - PyDict_Clear(m_pythondictionary); - Py_DECREF(m_pythondictionary); - } - m_pythondictionary = PyDict_Copy(pythondictionary); /* new reference */ - - /* Without __file__ set the sys.argv[0] is used for the filename - * which ends up with lines from the blender binary being printed in the console */ - PyObject *value = PyUnicode_From_STR_String(m_scriptName); - PyDict_SetItemString(m_pythondictionary, "__file__", value); - Py_DECREF(value); - -} -#endif - -bool SCA_PythonController::IsTriggered(class SCA_ISensor* sensor) -{ - if (std::find(m_triggeredSensors.begin(), m_triggeredSensors.end(), sensor) != - m_triggeredSensors.end()) - { - return true; - } - else { - return false; - } -} - -#ifdef WITH_PYTHON - -/* warning, self is not the SCA_PythonController, its a PyObjectPlus_Proxy */ -PyObject *SCA_PythonController::sPyGetCurrentController(PyObject *self) -{ - if (m_sCurrentController==NULL) - { - PyErr_SetString(PyExc_SystemError, "bge.logic.getCurrentController(), this function is being run outside the python controllers context, or blenders internal state is corrupt."); - return NULL; - } - return m_sCurrentController->GetProxy(); -} - -SCA_IActuator* SCA_PythonController::LinkedActuatorFromPy(PyObject *value) -{ - // for safety, todo: only allow for registered actuators (pointertable) - // we don't want to crash gameengine/blender by python scripts - std::vector lacts = m_sCurrentController->GetLinkedActuators(); - std::vector::iterator it; - - if (PyUnicode_Check(value)) { - /* get the actuator from the name */ - const char *name= _PyUnicode_AsString(value); - for (it = lacts.begin(); it!= lacts.end(); ++it) { - if ( name == (*it)->GetName() ) { - return *it; - } - } - } - else if (PyObject_TypeCheck(value, &SCA_IActuator::Type)) { - PyObjectPlus *value_plus= BGE_PROXY_REF(value); - for (it = lacts.begin(); it!= lacts.end(); ++it) { - if (static_cast(value_plus) == (*it)) { - return *it; - } - } - } - - /* set the exception */ - PyErr_Format(PyExc_ValueError, - "%R not in this python controllers actuator list", value); - - return NULL; -} - -const char* SCA_PythonController::sPyGetCurrentController__doc__ = "getCurrentController()"; - -PyTypeObject SCA_PythonController::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "SCA_PythonController", - 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_IController::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef SCA_PythonController::Methods[] = { - {"activate", (PyCFunction) SCA_PythonController::sPyActivate, METH_O}, - {"deactivate", (PyCFunction) SCA_PythonController::sPyDeActivate, METH_O}, - {NULL,NULL} //Sentinel -}; - -PyAttributeDef SCA_PythonController::Attributes[] = { - KX_PYATTRIBUTE_RW_FUNCTION("script", SCA_PythonController, pyattr_get_script, pyattr_set_script), - KX_PYATTRIBUTE_INT_RO("mode", SCA_PythonController, m_mode), - { NULL } //Sentinel -}; - -void SCA_PythonController::ErrorPrint(const char *error_msg) -{ - // If GetParent() is NULL, then most likely the object this controller - // was attached to is gone (e.g., removed by LibFree()). Also, GetName() - // can be a bad pointer if GetParent() is NULL, so better be safe and - // flag it as unavailable as well - const char *obj_name, *ctr_name; - if (GetParent()) { - obj_name = GetParent()->GetName().ReadPtr(); - ctr_name = GetName().ReadPtr(); - } else { - obj_name = ctr_name = "Unavailable"; - } - printf("%s - object '%s', controller '%s':\n", error_msg, obj_name, ctr_name); - PyErr_Print(); - - /* Added in 2.48a, the last_traceback can reference Objects for example, increasing - * their user count. Not to mention holding references to wrapped data. - * This is especially bad when the PyObject for the wrapped data is freed, after blender - * has already dealocated the pointer */ - PySys_SetObject("last_traceback", NULL); - PyErr_Clear(); /* just to be sure */ -} - -bool SCA_PythonController::Compile() -{ - //printf("py script modified '%s'\n", m_scriptName.Ptr()); - m_bModified= false; - - // if a script already exists, decref it before replace the pointer to a new script - if (m_bytecode) { - Py_DECREF(m_bytecode); - m_bytecode=NULL; - } - - // recompile the scripttext into bytecode - m_bytecode = Py_CompileString(m_scriptText.Ptr(), m_scriptName.Ptr(), Py_file_input); - - if (m_bytecode) { - return true; - } else { - ErrorPrint("Python error compiling script"); - return false; - } -} - -bool SCA_PythonController::Import() -{ - //printf("py module modified '%s'\n", m_scriptName.Ptr()); - m_bModified= false; - - /* in case we re-import */ - Py_XDECREF(m_function); - m_function= NULL; - - STR_String mod_path_str= m_scriptText; /* just for storage, use C style string access */ - char *mod_path= mod_path_str.Ptr(); - char *function_string; - - function_string= strrchr(mod_path, '.'); - - if (function_string == NULL) { - printf("Python module name formatting error in object '%s', controller '%s':\n\texpected 'SomeModule.Func', got '%s'\n", GetParent()->GetName().Ptr(), GetName().Ptr(), m_scriptText.Ptr()); - return false; - } - - *function_string= '\0'; - function_string++; - - // Import the module and print an error if it's not found - PyObject *mod = PyImport_ImportModule(mod_path); - - if (mod == NULL) { - ErrorPrint("Python module can't be imported"); - return false; - } - - if (m_debug) - mod = PyImport_ReloadModule(mod); - - if (mod == NULL) { - ErrorPrint("Python module can't be reloaded"); - return false; - } - - // Get the function object - m_function = PyObject_GetAttrString(mod, function_string); - - // DECREF the module as we don't need it anymore - Py_DECREF(mod); - - if (m_function==NULL) { - if (PyErr_Occurred()) - ErrorPrint("Python controller found the module but could not access the function"); - else - printf("Python module error in object '%s', controller '%s':\n '%s' module found but function missing\n", GetParent()->GetName().Ptr(), GetName().Ptr(), m_scriptText.Ptr()); - return false; - } - - if (!PyCallable_Check(m_function)) { - Py_DECREF(m_function); - m_function = NULL; - printf("Python module function error in object '%s', controller '%s':\n '%s' not callable\n", GetParent()->GetName().Ptr(), GetName().Ptr(), m_scriptText.Ptr()); - return false; - } - - m_function_argc = 0; /* rare cases this could be a function that isn't defined in python, assume zero args */ - if (PyFunction_Check(m_function)) { - m_function_argc= ((PyCodeObject *)PyFunction_GET_CODE(m_function))->co_argcount; - } - - if (m_function_argc > 1) { - Py_DECREF(m_function); - m_function = NULL; - printf("Python module function in object '%s', controller '%s':\n '%s' takes %d args, should be zero or 1 controller arg\n", GetParent()->GetName().Ptr(), GetName().Ptr(), m_scriptText.Ptr(), m_function_argc); - return false; - } - - return true; -} - - -void SCA_PythonController::Trigger(SCA_LogicManager* logicmgr) -{ - m_sCurrentController = this; - - PyObject *excdict= NULL; - PyObject *resultobj= NULL; - - switch (m_mode) { - case SCA_PYEXEC_SCRIPT: - { - if (m_bModified) - if (Compile()==false) // sets m_bModified to false - return; - if (!m_bytecode) - return; - - /* - * This part here with excdict is a temporary patch - * to avoid python/gameengine crashes when python - * inadvertently holds references to game objects - * in global variables. - * - * The idea is always make a fresh dictionary, and - * destroy it right after it is used to make sure - * python won't hold any gameobject references. - * - * Note that the PyDict_Clear _is_ necessary before - * the Py_DECREF() because it is possible for the - * variables inside the dictionary to hold references - * to the dictionary (ie. generate a cycle), so we - * break it by hand, then DECREF (which in this case - * should always ensure excdict is cleared). - */ - - excdict= PyDict_Copy(m_pythondictionary); - - resultobj = PyEval_EvalCode((PyObject *)m_bytecode, excdict, excdict); - - /* PyRun_SimpleString(m_scriptText.Ptr()); */ - break; - } - case SCA_PYEXEC_MODULE: - { - if (m_bModified || m_debug) - if (Import()==false) // sets m_bModified to false - return; - if (!m_function) - return; - - PyObject *args= NULL; - - if (m_function_argc==1) { - args = PyTuple_New(1); - PyTuple_SET_ITEM(args, 0, GetProxy()); - } - - resultobj = PyObject_CallObject(m_function, args); - Py_XDECREF(args); - break; - } - - } /* end switch */ - - - /* Free the return value and print the error */ - if (resultobj) - Py_DECREF(resultobj); - else - ErrorPrint("Python script error"); - - if (excdict) /* Only for SCA_PYEXEC_SCRIPT types */ - { - /* clear after PyErrPrint - seems it can be using - * something in this dictionary and crash? */ - // This doesn't appear to be needed anymore - //PyDict_Clear(excdict); - Py_DECREF(excdict); - } - - m_triggeredSensors.clear(); - m_sCurrentController = NULL; -} - -PyObject *SCA_PythonController::PyActivate(PyObject *value) -{ - if (m_sCurrentController != this) { - PyErr_SetString(PyExc_SystemError, "Cannot activate an actuator from a non-active controller"); - return NULL; - } - - SCA_IActuator* actu = LinkedActuatorFromPy(value); - if (actu==NULL) - return NULL; - - m_logicManager->AddActiveActuator((SCA_IActuator*)actu, true); - Py_RETURN_NONE; -} - -PyObject *SCA_PythonController::PyDeActivate(PyObject *value) -{ - if (m_sCurrentController != this) { - PyErr_SetString(PyExc_SystemError, "Cannot deactivate an actuator from a non-active controller"); - return NULL; - } - - SCA_IActuator* actu = LinkedActuatorFromPy(value); - if (actu==NULL) - return NULL; - - m_logicManager->AddActiveActuator((SCA_IActuator*)actu, false); - Py_RETURN_NONE; -} - -PyObject *SCA_PythonController::pyattr_get_script(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - //SCA_PythonController* self = static_cast(static_cast(static_cast(static_cast(static_cast(self_v))))); - // static_cast(dynamic_cast(obj)) - static_cast(obj) - - SCA_PythonController* self = static_cast(self_v); - return PyUnicode_From_STR_String(self->m_scriptText); -} - - - -int SCA_PythonController::pyattr_set_script(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - SCA_PythonController* self = static_cast(self_v); - - const char *scriptArg = _PyUnicode_AsString(value); - - if (scriptArg==NULL) { - PyErr_SetString(PyExc_TypeError, "controller.script = string: Python Controller, expected a string script text"); - return PY_SET_ATTR_FAIL; - } - - /* set scripttext sets m_bModified to true, - * so next time the script is needed, a reparse into byte code is done */ - self->SetScriptText(scriptArg); - - return PY_SET_ATTR_SUCCESS; -} - -#else // WITH_PYTHON - -void SCA_PythonController::Trigger(SCA_LogicManager* logicmgr) -{ - /* intentionally blank */ -} - -#endif // WITH_PYTHON - -/* eof */ diff --git a/source/gameengine/GameLogic/SCA_PythonController.h b/source/gameengine/GameLogic/SCA_PythonController.h deleted file mode 100644 index 11241da9117..00000000000 --- a/source/gameengine/GameLogic/SCA_PythonController.h +++ /dev/null @@ -1,118 +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 SCA_PythonController.h - * \ingroup gamelogic - * \brief Execute Python scripts - */ - -#ifndef __SCA_PYTHONCONTROLLER_H__ -#define __SCA_PYTHONCONTROLLER_H__ - -#include "SCA_IController.h" -#include "SCA_LogicManager.h" -#include "EXP_BoolValue.h" - -#include - -class SCA_IObject; -class SCA_PythonController : public SCA_IController -{ - Py_Header -#ifdef WITH_PYTHON - struct _object * m_bytecode; /* SCA_PYEXEC_SCRIPT only */ - PyObject* m_function; /* SCA_PYEXEC_MODULE only */ -#endif - int m_function_argc; - bool m_bModified; - bool m_debug; /* use with SCA_PYEXEC_MODULE for reloading every logic run */ - int m_mode; - - - protected: - STR_String m_scriptText; - STR_String m_scriptName; -#ifdef WITH_PYTHON - PyObject* m_pythondictionary; /* for SCA_PYEXEC_SCRIPT only */ - PyObject* m_pythonfunction; /* for SCA_PYEXEC_MODULE only */ -#endif - std::vector m_triggeredSensors; - - public: - enum SCA_PyExecMode - { - SCA_PYEXEC_SCRIPT = 0, - SCA_PYEXEC_MODULE, - SCA_PYEXEC_MAX - }; - - static SCA_PythonController* m_sCurrentController; // protected !!! - - //for debugging - //virtual CValue* AddRef(); - //virtual int Release(); // Release a reference to this value (when reference count reaches 0, the value is removed from the heap) - - SCA_PythonController(SCA_IObject* gameobj, int mode); - virtual ~SCA_PythonController(); - - virtual CValue* GetReplica(); - virtual void Trigger(class SCA_LogicManager* logicmgr); - - void SetScriptText(const STR_String& text); - void SetScriptName(const STR_String& name); -#ifdef WITH_PYTHON - void SetNamespace(PyObject* pythondictionary); -#endif - void SetDebug(bool debug) { m_debug = debug; } - void AddTriggeredSensor(class SCA_ISensor* sensor) - { m_triggeredSensors.push_back(sensor); } - bool IsTriggered(class SCA_ISensor* sensor); - bool Compile(); - bool Import(); - void ErrorPrint(const char *error_msg); - -#ifdef WITH_PYTHON - static const char *sPyGetCurrentController__doc__; - static PyObject *sPyGetCurrentController(PyObject *self); - static const char *sPyAddActiveActuator__doc__; - static PyObject *sPyAddActiveActuator(PyObject *self, - PyObject *args); - static SCA_IActuator* LinkedActuatorFromPy(PyObject *value); - - - KX_PYMETHOD_O(SCA_PythonController,Activate); - KX_PYMETHOD_O(SCA_PythonController,DeActivate); - KX_PYMETHOD_O(SCA_PythonController,SetScript); - KX_PYMETHOD_NOARGS(SCA_PythonController,GetScript); - - - static PyObject* pyattr_get_script(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_script(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); -#endif -}; - -#endif /* __SCA_PYTHONCONTROLLER_H__ */ diff --git a/source/gameengine/GameLogic/SCA_PythonJoystick.cpp b/source/gameengine/GameLogic/SCA_PythonJoystick.cpp deleted file mode 100644 index 9b24ad7bcf2..00000000000 --- a/source/gameengine/GameLogic/SCA_PythonJoystick.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. - * - * Contributor(s): Mitchell Stokes. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file gameengine/GameLogic/SCA_PythonJoystick.cpp - * \ingroup gamelogic - */ - - -#include "SCA_PythonJoystick.h" -#include "./Joystick/SCA_Joystick.h" -#include "SCA_IInputDevice.h" - -//#include "GHOST_C-api.h" - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -SCA_PythonJoystick::SCA_PythonJoystick(SCA_Joystick* joystick) -: PyObjectPlus(), -m_joystick(joystick) -{ -#ifdef WITH_PYTHON - m_event_dict = PyDict_New(); -#endif -} - -SCA_PythonJoystick::~SCA_PythonJoystick() -{ - // The joystick reference we got in the constructor was a new instance, - // so we release it here - m_joystick->ReleaseInstance(); - -#ifdef WITH_PYTHON - PyDict_Clear(m_event_dict); - Py_DECREF(m_event_dict); -#endif -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ -PyObject* SCA_PythonJoystick::py_repr(void) -{ - return PyUnicode_FromString(m_joystick->GetName()); -} - - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject SCA_PythonJoystick::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "SCA_PythonJoystick", - 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 SCA_PythonJoystick::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef SCA_PythonJoystick::Attributes[] = { - KX_PYATTRIBUTE_RO_FUNCTION("numButtons", SCA_PythonJoystick, pyattr_get_num_x), - KX_PYATTRIBUTE_RO_FUNCTION("numHats", SCA_PythonJoystick, pyattr_get_num_x), - KX_PYATTRIBUTE_RO_FUNCTION("numAxis", SCA_PythonJoystick, pyattr_get_num_x), - KX_PYATTRIBUTE_RO_FUNCTION("activeButtons", SCA_PythonJoystick, pyattr_get_active_buttons), - KX_PYATTRIBUTE_RO_FUNCTION("hatValues", SCA_PythonJoystick, pyattr_get_hat_values), - KX_PYATTRIBUTE_RO_FUNCTION("axisValues", SCA_PythonJoystick, pyattr_get_axis_values), - KX_PYATTRIBUTE_RO_FUNCTION("name", SCA_PythonJoystick, pyattr_get_name), - { NULL } //Sentinel -}; - -// Use one function for numAxis, numButtons, and numHats -PyObject* SCA_PythonJoystick::pyattr_get_num_x(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_PythonJoystick* self = static_cast(self_v); - - if (strcmp(attrdef->m_name, "numButtons") == 0) - return PyLong_FromLong(self->m_joystick->GetNumberOfButtons()); - else if (strcmp(attrdef->m_name, "numAxis") == 0) - return PyLong_FromLong(self->m_joystick->GetNumberOfAxes()); - else if (strcmp(attrdef->m_name, "numHats") == 0) - return PyLong_FromLong(self->m_joystick->GetNumberOfHats()); - - // If we got here, we have a problem... - PyErr_SetString(PyExc_AttributeError, "invalid attribute"); - return NULL; -} - -PyObject* SCA_PythonJoystick::pyattr_get_active_buttons(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_PythonJoystick* self = static_cast(self_v); - - const int button_number = self->m_joystick->GetNumberOfButtons(); - - PyObject *list = PyList_New(0); - PyObject *value; - - for (int i=0; i < button_number; i++) { - if (self->m_joystick->aButtonPressIsPositive(i)) { - value = PyLong_FromLong(i); - PyList_Append(list, value); - Py_DECREF(value); - } - } - - return list; -} - -PyObject* SCA_PythonJoystick::pyattr_get_hat_values(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_PythonJoystick* self = static_cast(self_v); - - int hat_index = self->m_joystick->GetNumberOfHats(); - PyObject *list = PyList_New(hat_index); - - while (hat_index--) { - PyList_SET_ITEM(list, hat_index, PyLong_FromLong(self->m_joystick->GetHat(hat_index))); - } - - return list; -} - -PyObject* SCA_PythonJoystick::pyattr_get_axis_values(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_PythonJoystick* self = static_cast(self_v); - - int axis_index = self->m_joystick->GetNumberOfAxes(); - PyObject *list = PyList_New(axis_index); - int position; - - while (axis_index--) { - position = self->m_joystick->GetAxisPosition(axis_index); - - // We get back a range from -32768 to 32767, so we use an if here to - // get a perfect -1.0 to 1.0 mapping. Some oddball system might have an - // actual min of -32767 for shorts, so we use SHRT_MIN/MAX to be safe. - if (position < 0) - PyList_SET_ITEM(list, axis_index, PyFloat_FromDouble(position/((double)-SHRT_MIN))); - else - PyList_SET_ITEM(list, axis_index, PyFloat_FromDouble(position/(double)SHRT_MAX)); - } - - return list; -} - -PyObject* SCA_PythonJoystick::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_PythonJoystick* self = static_cast(self_v); - - return PyUnicode_FromString(self->m_joystick->GetName()); -} -#endif diff --git a/source/gameengine/GameLogic/SCA_PythonJoystick.h b/source/gameengine/GameLogic/SCA_PythonJoystick.h deleted file mode 100644 index ecde00d28b9..00000000000 --- a/source/gameengine/GameLogic/SCA_PythonJoystick.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. - * - * Contributor(s): Mitchell Stokes. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file SCA_PythonJoystick.h - * \ingroup gamelogic - */ - -#ifndef __SCA_PYTHONJOYSTICK_H__ -#define __SCA_PYTHONJOYSTICK_H__ - -#include "EXP_PyObjectPlus.h" - -class SCA_PythonJoystick : public PyObjectPlus -{ - Py_Header -private: - class SCA_Joystick *m_joystick; -#ifdef WITH_PYTHON - PyObject* m_event_dict; -#endif -public: - SCA_PythonJoystick(class SCA_Joystick* joystick); - virtual ~SCA_PythonJoystick(); - -#ifdef WITH_PYTHON - virtual PyObject* py_repr(void); - - static PyObject* pyattr_get_num_x(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_active_buttons(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_hat_values(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_axis_values(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_name(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); -#endif -}; - -#endif //__SCA_PYTHONJOYSTICK_H__ - diff --git a/source/gameengine/GameLogic/SCA_PythonKeyboard.cpp b/source/gameengine/GameLogic/SCA_PythonKeyboard.cpp deleted file mode 100644 index 9a96a7b0334..00000000000 --- a/source/gameengine/GameLogic/SCA_PythonKeyboard.cpp +++ /dev/null @@ -1,153 +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/GameLogic/SCA_PythonKeyboard.cpp - * \ingroup gamelogic - */ - - -#include "SCA_PythonKeyboard.h" -#include "SCA_IInputDevice.h" - -#include "GHOST_C-api.h" - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -SCA_PythonKeyboard::SCA_PythonKeyboard(SCA_IInputDevice* keyboard) -: PyObjectPlus(), -m_keyboard(keyboard) -{ -#ifdef WITH_PYTHON - m_event_dict = PyDict_New(); -#endif -} - -SCA_PythonKeyboard::~SCA_PythonKeyboard() -{ -#ifdef WITH_PYTHON - PyDict_Clear(m_event_dict); - Py_DECREF(m_event_dict); -#endif -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* clipboard */ -static PyObject *gPyGetClipboard(PyObject *args, PyObject *kwds) -{ - char *buf = (char *)GHOST_getClipboard(0); - return PyUnicode_FromString(buf?buf:""); -} - -static PyObject *gPySetClipboard(PyObject *args, PyObject *value) -{ - char* buf; - if (!PyArg_ParseTuple(value,"s:setClipboard",&buf)) - Py_RETURN_NONE; - - GHOST_putClipboard((GHOST_TInt8 *)buf, 0); - Py_RETURN_NONE; -} - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject SCA_PythonKeyboard::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "SCA_PythonKeyboard", - 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 SCA_PythonKeyboard::Methods[] = { - {"getClipboard", (PyCFunction) gPyGetClipboard, METH_VARARGS, "getCliboard doc"}, - {"setClipboard", (PyCFunction) gPySetClipboard, METH_VARARGS, "setCliboard doc"}, - {NULL,NULL} //Sentinel -}; - -PyAttributeDef SCA_PythonKeyboard::Attributes[] = { - KX_PYATTRIBUTE_RO_FUNCTION("events", SCA_PythonKeyboard, pyattr_get_events), - KX_PYATTRIBUTE_RO_FUNCTION("active_events", SCA_PythonKeyboard, pyattr_get_active_events), - { NULL } //Sentinel -}; - -PyObject *SCA_PythonKeyboard::pyattr_get_events(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_PythonKeyboard* self = static_cast(self_v); - - for (int i = SCA_IInputDevice::KX_BEGINKEY; i <= SCA_IInputDevice::KX_ENDKEY; i++) { - const SCA_InputEvent & inevent = self->m_keyboard->GetEventValue((SCA_IInputDevice::KX_EnumInputs)i); - PyObject *key = PyLong_FromLong(i); - PyObject *value = PyLong_FromLong(inevent.m_status); - - PyDict_SetItem(self->m_event_dict, key, value); - - Py_DECREF(key); - Py_DECREF(value); - } - Py_INCREF(self->m_event_dict); - return self->m_event_dict; -} - -PyObject *SCA_PythonKeyboard::pyattr_get_active_events(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_PythonKeyboard* self = static_cast(self_v); - - PyDict_Clear(self->m_event_dict); - - for (int i = SCA_IInputDevice::KX_BEGINKEY; i <= SCA_IInputDevice::KX_ENDKEY; i++) { - const SCA_InputEvent & inevent = self->m_keyboard->GetEventValue((SCA_IInputDevice::KX_EnumInputs)i); - - if (inevent.m_status != SCA_InputEvent::KX_NO_INPUTSTATUS) { - PyObject *key = PyLong_FromLong(i); - PyObject *value = PyLong_FromLong(inevent.m_status); - - PyDict_SetItem(self->m_event_dict, key, value); - - Py_DECREF(key); - Py_DECREF(value); - } - } - Py_INCREF(self->m_event_dict); - return self->m_event_dict; -} - -#endif diff --git a/source/gameengine/GameLogic/SCA_PythonKeyboard.h b/source/gameengine/GameLogic/SCA_PythonKeyboard.h deleted file mode 100644 index 3cbe250378c..00000000000 --- a/source/gameengine/GameLogic/SCA_PythonKeyboard.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. - * - * Contributor(s): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file SCA_PythonKeyboard.h - * \ingroup gamelogic - */ - -#ifndef __SCA_PYTHONKEYBOARD_H__ -#define __SCA_PYTHONKEYBOARD_H__ - -#include "EXP_PyObjectPlus.h" - -class SCA_PythonKeyboard : public PyObjectPlus -{ - Py_Header -private: - class SCA_IInputDevice *m_keyboard; -#ifdef WITH_PYTHON - PyObject *m_event_dict; -#endif -public: - SCA_PythonKeyboard(class SCA_IInputDevice* keyboard); - virtual ~SCA_PythonKeyboard(); - -#ifdef WITH_PYTHON - static PyObject* pyattr_get_events(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject* pyattr_get_active_events(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); -#endif -}; - -#endif /* __SCA_PYTHONKEYBOARD_H__ */ diff --git a/source/gameengine/GameLogic/SCA_PythonMouse.cpp b/source/gameengine/GameLogic/SCA_PythonMouse.cpp deleted file mode 100644 index 184b306a665..00000000000 --- a/source/gameengine/GameLogic/SCA_PythonMouse.cpp +++ /dev/null @@ -1,206 +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/GameLogic/SCA_PythonMouse.cpp - * \ingroup gamelogic - */ - - -#include "SCA_PythonMouse.h" -#include "SCA_IInputDevice.h" -#include "RAS_ICanvas.h" - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -SCA_PythonMouse::SCA_PythonMouse(SCA_IInputDevice* mouse, RAS_ICanvas* canvas) -: PyObjectPlus(), -m_mouse(mouse), -m_canvas(canvas) -{ -#ifdef WITH_PYTHON - m_event_dict = PyDict_New(); -#endif -} - -SCA_PythonMouse::~SCA_PythonMouse() -{ -#ifdef WITH_PYTHON - PyDict_Clear(m_event_dict); - Py_DECREF(m_event_dict); -#endif -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject SCA_PythonMouse::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "SCA_PythonMouse", - 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 SCA_PythonMouse::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef SCA_PythonMouse::Attributes[] = { - KX_PYATTRIBUTE_RO_FUNCTION("events", SCA_PythonMouse, pyattr_get_events), - KX_PYATTRIBUTE_RO_FUNCTION("active_events", SCA_PythonMouse, pyattr_get_active_events), - KX_PYATTRIBUTE_RW_FUNCTION("position", SCA_PythonMouse, pyattr_get_position, pyattr_set_position), - KX_PYATTRIBUTE_RW_FUNCTION("visible", SCA_PythonMouse, pyattr_get_visible, pyattr_set_visible), - { NULL } //Sentinel -}; - -PyObject *SCA_PythonMouse::pyattr_get_events(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_PythonMouse* self = static_cast(self_v); - - for (int i = SCA_IInputDevice::KX_BEGINMOUSE; i <= SCA_IInputDevice::KX_ENDMOUSE; i++) { - const SCA_InputEvent &inevent = self->m_mouse->GetEventValue((SCA_IInputDevice::KX_EnumInputs)i); - PyObject *key = PyLong_FromLong(i); - PyObject *value = PyLong_FromLong(inevent.m_status); - - PyDict_SetItem(self->m_event_dict, key, value); - - Py_DECREF(key); - Py_DECREF(value); - } - Py_INCREF(self->m_event_dict); - return self->m_event_dict; -} - -PyObject *SCA_PythonMouse::pyattr_get_active_events(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_PythonMouse* self = static_cast(self_v); - - PyDict_Clear(self->m_event_dict); - - for (int i = SCA_IInputDevice::KX_BEGINMOUSE; i <= SCA_IInputDevice::KX_ENDMOUSE; i++) { - const SCA_InputEvent &inevent = self->m_mouse->GetEventValue((SCA_IInputDevice::KX_EnumInputs)i); - - if (inevent.m_status != SCA_InputEvent::KX_NO_INPUTSTATUS) { - - PyObject *key = PyLong_FromLong(i); - PyObject *value = PyLong_FromLong(inevent.m_status); - - PyDict_SetItem(self->m_event_dict, key, value); - - Py_DECREF(key); - Py_DECREF(value); - } - } - Py_INCREF(self->m_event_dict); - return self->m_event_dict; -} - -PyObject *SCA_PythonMouse::pyattr_get_position(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_PythonMouse* self = static_cast(self_v); - const SCA_InputEvent & xevent = self->m_mouse->GetEventValue(SCA_IInputDevice::KX_MOUSEX); - const SCA_InputEvent & yevent = self->m_mouse->GetEventValue(SCA_IInputDevice::KX_MOUSEY); - - float x_coord, y_coord; - - x_coord = self->m_canvas->GetMouseNormalizedX(xevent.m_eventval); - y_coord = self->m_canvas->GetMouseNormalizedY(yevent.m_eventval); - - PyObject *ret = PyTuple_New(2); - - PyTuple_SET_ITEM(ret, 0, PyFloat_FromDouble(x_coord)); - PyTuple_SET_ITEM(ret, 1, PyFloat_FromDouble(y_coord)); - - return ret; -} - -int SCA_PythonMouse::pyattr_set_position(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - SCA_PythonMouse* self = static_cast(self_v); - int x, y; - float pyx, pyy; - if (!PyArg_ParseTuple(value, "ff:position", &pyx, &pyy)) - return PY_SET_ATTR_FAIL; - - x = (int)(pyx*self->m_canvas->GetWidth()); - y = (int)(pyy*self->m_canvas->GetHeight()); - - self->m_canvas->SetMousePosition(x, y); - - return PY_SET_ATTR_SUCCESS; -} - -PyObject *SCA_PythonMouse::pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_PythonMouse* self = static_cast(self_v); - - int visible; - - if (self->m_canvas->GetMouseState() == RAS_ICanvas::MOUSE_INVISIBLE) - visible = 0; - else - visible = 1; - - return PyBool_FromLong(visible); -} - -int SCA_PythonMouse::pyattr_set_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - SCA_PythonMouse* self = static_cast(self_v); - - int visible = PyObject_IsTrue(value); - - if (visible == -1) - { - PyErr_SetString(PyExc_AttributeError, "SCA_PythonMouse.visible = bool: SCA_PythonMouse, expected True or False"); - return PY_SET_ATTR_FAIL; - } - - if (visible) - self->m_canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL); - else - self->m_canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE); - - return PY_SET_ATTR_SUCCESS; -} - -#endif diff --git a/source/gameengine/GameLogic/SCA_PythonMouse.h b/source/gameengine/GameLogic/SCA_PythonMouse.h deleted file mode 100644 index 6dde90b3482..00000000000 --- a/source/gameengine/GameLogic/SCA_PythonMouse.h +++ /dev/null @@ -1,59 +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 SCA_PythonMouse.h - * \ingroup gamelogic - */ - -#ifndef __SCA_PYTHONMOUSE_H__ -#define __SCA_PYTHONMOUSE_H__ - -#include "EXP_PyObjectPlus.h" - -class SCA_PythonMouse : public PyObjectPlus -{ - Py_Header -private: - class SCA_IInputDevice *m_mouse; - class RAS_ICanvas *m_canvas; -#ifdef WITH_PYTHON - PyObject *m_event_dict; -#endif -public: - SCA_PythonMouse(class SCA_IInputDevice* mouse, class RAS_ICanvas* canvas); - virtual ~SCA_PythonMouse(); - - void Show(bool visible); - -#ifdef WITH_PYTHON - KX_PYMETHOD_DOC(SCA_PythonMouse, show); - - static PyObject *pyattr_get_events(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_active_events(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static PyObject *pyattr_get_position(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_position(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); -#endif -}; - -#endif /* __SCA_PYTHONMOUSE_H__ */ diff --git a/source/gameengine/GameLogic/SCA_RandomActuator.cpp b/source/gameengine/GameLogic/SCA_RandomActuator.cpp deleted file mode 100644 index 8d75be9089d..00000000000 --- a/source/gameengine/GameLogic/SCA_RandomActuator.cpp +++ /dev/null @@ -1,543 +0,0 @@ -/* - * Set random/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/GameLogic/SCA_RandomActuator.cpp - * \ingroup gamelogic - */ - - -#include -#include - -#include "EXP_BoolValue.h" -#include "EXP_IntValue.h" -#include "EXP_FloatValue.h" -#include "SCA_IActuator.h" -#include "SCA_RandomActuator.h" -#include "MT_Transform.h" - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -SCA_RandomActuator::SCA_RandomActuator(SCA_IObject *gameobj, - long seed, - SCA_RandomActuator::KX_RANDOMACT_MODE mode, - float para1, - float para2, - const STR_String &propName) - : SCA_IActuator(gameobj, KX_ACT_RANDOM), - m_propname(propName), - m_parameter1(para1), - m_parameter2(para2), - m_distribution(mode) -{ - m_base = new SCA_RandomNumberGenerator(seed); - m_counter = 0; - enforceConstraints(); -} - - - -SCA_RandomActuator::~SCA_RandomActuator() -{ - m_base->Release(); -} - - - -CValue* SCA_RandomActuator::GetReplica() -{ - SCA_RandomActuator* replica = new SCA_RandomActuator(*this); - // replication just copy the m_base pointer => common random generator - replica->ProcessReplica(); - return replica; -} - -void SCA_RandomActuator::ProcessReplica() -{ - SCA_IActuator::ProcessReplica(); - // increment reference count so that we can release the generator at the end - m_base->AddRef(); -} - - - -bool SCA_RandomActuator::Update() -{ - //bool result = false; /*unused*/ - bool bNegativeEvent = IsNegativeEvent(); - - RemoveAllEvents(); - - - CValue *tmpval = NULL; - - if (bNegativeEvent) - return false; // do nothing on negative events - - switch (m_distribution) { - case KX_RANDOMACT_BOOL_CONST: { - /* un petit peu filthy */ - bool res = !(m_parameter1 < 0.5); - tmpval = new CBoolValue(res); - } - break; - case KX_RANDOMACT_BOOL_UNIFORM: { - /* flip a coin */ - bool res; - if (m_counter > 31) { - m_previous = m_base->Draw(); - res = ((m_previous & 0x1) == 0); - m_counter = 1; - } else { - res = (((m_previous >> m_counter) & 0x1) == 0); - m_counter++; - } - tmpval = new CBoolValue(res); - } - break; - case KX_RANDOMACT_BOOL_BERNOUILLI: { - /* 'percentage' */ - bool res; - res = (m_base->DrawFloat() < m_parameter1); - tmpval = new CBoolValue(res); - } - break; - case KX_RANDOMACT_INT_CONST: { - /* constant */ - tmpval = new CIntValue((int) floor(m_parameter1)); - } - break; - case KX_RANDOMACT_INT_UNIFORM: { - /* uniform (toss a die) */ - int res; - /* The [0, 1] interval is projected onto the [min, max+1] domain, */ - /* and then rounded. */ - res = (int)floor( ((m_parameter2 - m_parameter1 + 1) * m_base->DrawFloat()) + m_parameter1); - tmpval = new CIntValue(res); - } - break; - case KX_RANDOMACT_INT_POISSON: { - /* poisson (queues) */ - /* If x_1, x_2, ... is a sequence of random numbers with uniform */ - /* distribution between zero and one, k is the first integer for */ - /* which the product x_1*x_2*...*x_k < exp(-\lamba). */ - float a, b; - int res = 0; - /* The - sign is important here! The number to test for, a, must be */ - /* between 0 and 1. */ - a = exp(-m_parameter1); - /* a quickly reaches 0.... so we guard explicitly for that. */ - if (a < FLT_MIN) a = FLT_MIN; - b = m_base->DrawFloat(); - while (b >= a) { - b = b * m_base->DrawFloat(); - res++; - }; - tmpval = new CIntValue(res); - } - break; - case KX_RANDOMACT_FLOAT_CONST: { - /* constant */ - tmpval = new CFloatValue(m_parameter1); - } - break; - case KX_RANDOMACT_FLOAT_UNIFORM: { - float res = ((m_parameter2 - m_parameter1) * m_base->DrawFloat()) + m_parameter1; - tmpval = new CFloatValue(res); - } - break; - case KX_RANDOMACT_FLOAT_NORMAL: { - /* normal (big numbers): para1 = mean, para2 = std dev */ - - /* 070301 - nzc: Changed the termination condition. I think I - * made a small mistake here, but it only affects distro's where - * the seed equals 0. In that case, the algorithm locks. Let's - * just guard that case separately. - */ - - float x = 0.0, y = 0.0, s = 0.0, t = 0.0; - if (m_base->GetSeed() == 0) { - /* 070301 - nzc: Just taking the mean here seems reasonable. */ - tmpval = new CFloatValue(m_parameter1); - } - else { - /* 070301 - nzc - * Now, with seed != 0, we will most assuredly get some - * sensible values. The termination condition states two - * things: - * 1. s >= 0 is not allowed: to prevent the distro from - * getting a bias towards high values. This is a small - * correction, really, and might also be left out. - * 2. s == 0 is not allowed: to prevent a division by zero - * when renormalising the drawn value to the desired - * distribution shape. As a side effect, the distro will - * never yield the exact mean. - * I am not sure whether this is consistent, since the error - * cause by #2 is of the same magnitude as the one - * prevented by #1. The error introduced into the SD will be - * improved, though. By how much? Hard to say... If you like - * the maths, feel free to analyse. Be aware that this is - * one of the really old standard algorithms. I think the - * original came in Fortran, was translated to Pascal, and - * then someone came up with the C code. My guess it that - * this will be quite sufficient here. - */ - do { - x = 2.0f * m_base->DrawFloat() - 1.0f; - y = 2.0f * m_base->DrawFloat() - 1.0f; - s = x * x + y * y; - } while ((s >= 1.0f) || (s == 0.0f)); - t = x * sqrtf((-2.0 * log(s)) / s); - tmpval = new CFloatValue(m_parameter1 + m_parameter2 * t); - } - } - break; - case KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL: { - /* 1st order fall-off. I am very partial to using the half-life as */ - /* controlling parameter. Using the 'normal' exponent is not very */ - /* intuitive... */ - /* tmpval = new CFloatValue( (1.0 / m_parameter1) */ - tmpval = new CFloatValue((m_parameter1) * (-log(1.0 - m_base->DrawFloat()))); - - } - break; - default: - { - /* unknown distribution... */ - static bool randomWarning = false; - if (!randomWarning) { - randomWarning = true; - std::cout << "RandomActuator '" << GetName() << "' has an unknown distribution." << std::endl; - } - return false; - } - } - - /* Round up: assign it */ - CValue *prop = GetParent()->GetProperty(m_propname); - if (prop) { - prop->SetValue(tmpval); - } - tmpval->Release(); - - return false; -} - -void SCA_RandomActuator::enforceConstraints() -{ - /* The constraints that are checked here are the ones fundamental to */ - /* the various distributions. Limitations of the algorithms are checked */ - /* elsewhere (or they should be... ). */ - switch (m_distribution) { - case KX_RANDOMACT_BOOL_CONST: - case KX_RANDOMACT_BOOL_UNIFORM: - case KX_RANDOMACT_INT_CONST: - case KX_RANDOMACT_INT_UNIFORM: - case KX_RANDOMACT_FLOAT_UNIFORM: - case KX_RANDOMACT_FLOAT_CONST: - ; /* Nothing to be done here. We allow uniform distro's to have */ - /* 'funny' domains, i.e. max < min. This does not give problems. */ - break; - case KX_RANDOMACT_BOOL_BERNOUILLI: - /* clamp to [0, 1] */ - if (m_parameter1 < 0.0) { - m_parameter1 = 0.0; - } else if (m_parameter1 > 1.0) { - m_parameter1 = 1.0; - } - break; - case KX_RANDOMACT_INT_POISSON: - /* non-negative */ - if (m_parameter1 < 0.0) { - m_parameter1 = 0.0; - } - break; - case KX_RANDOMACT_FLOAT_NORMAL: - /* standard dev. is non-negative */ - if (m_parameter2 < 0.0) { - m_parameter2 = 0.0; - } - break; - case KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL: - /* halflife must be non-negative */ - if (m_parameter1 < 0.0) { - m_parameter1 = 0.0; - } - break; - default: - ; /* unknown distribution... */ - } -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject SCA_RandomActuator::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "SCA_RandomActuator", - 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 SCA_RandomActuator::Methods[] = { - KX_PYMETHODTABLE(SCA_RandomActuator, setBoolConst), - KX_PYMETHODTABLE_NOARGS(SCA_RandomActuator, setBoolUniform), - KX_PYMETHODTABLE(SCA_RandomActuator, setBoolBernouilli), - - KX_PYMETHODTABLE(SCA_RandomActuator, setIntConst), - KX_PYMETHODTABLE(SCA_RandomActuator, setIntUniform), - KX_PYMETHODTABLE(SCA_RandomActuator, setIntPoisson), - - KX_PYMETHODTABLE(SCA_RandomActuator, setFloatConst), - KX_PYMETHODTABLE(SCA_RandomActuator, setFloatUniform), - KX_PYMETHODTABLE(SCA_RandomActuator, setFloatNormal), - KX_PYMETHODTABLE(SCA_RandomActuator, setFloatNegativeExponential), - {NULL,NULL} //Sentinel -}; - -PyAttributeDef SCA_RandomActuator::Attributes[] = { - KX_PYATTRIBUTE_FLOAT_RO("para1",SCA_RandomActuator,m_parameter1), - KX_PYATTRIBUTE_FLOAT_RO("para2",SCA_RandomActuator,m_parameter2), - KX_PYATTRIBUTE_ENUM_RO("distribution",SCA_RandomActuator,m_distribution), - KX_PYATTRIBUTE_STRING_RW_CHECK("propName",0,MAX_PROP_NAME,false,SCA_RandomActuator,m_propname,CheckProperty), - KX_PYATTRIBUTE_RW_FUNCTION("seed",SCA_RandomActuator,pyattr_get_seed,pyattr_set_seed), - { NULL } //Sentinel -}; - -PyObject *SCA_RandomActuator::pyattr_get_seed(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_RandomActuator* act = static_cast(self); - return PyLong_FromLong(act->m_base->GetSeed()); -} - -int SCA_RandomActuator::pyattr_set_seed(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - SCA_RandomActuator* act = static_cast(self); - if (PyLong_Check(value)) { - act->m_base->SetSeed(PyLong_AsLong(value)); - return PY_SET_ATTR_SUCCESS; - } - else { - PyErr_SetString(PyExc_TypeError, "actuator.seed = int: Random Actuator, expected an integer"); - return PY_SET_ATTR_FAIL; - } -} - -/* 11. setBoolConst */ -KX_PYMETHODDEF_DOC_VARARGS(SCA_RandomActuator, setBoolConst, -"setBoolConst(value)\n" -"\t- value: 0 or 1\n" -"\tSet this generator to produce a constant boolean value.\n") -{ - int paraArg; - if (!PyArg_ParseTuple(args, "i:setBoolConst", ¶Arg)) { - return NULL; - } - - m_distribution = KX_RANDOMACT_BOOL_CONST; - m_parameter1 = (paraArg) ? 1.0 : 0.0; - - Py_RETURN_NONE; -} -/* 12. setBoolUniform, */ -KX_PYMETHODDEF_DOC_NOARGS(SCA_RandomActuator, setBoolUniform, -"setBoolUniform()\n" -"\tSet this generator to produce true and false, each with 50%% chance of occurring\n") -{ - /* no args */ - m_distribution = KX_RANDOMACT_BOOL_UNIFORM; - enforceConstraints(); - Py_RETURN_NONE; -} -/* 13. setBoolBernouilli, */ -KX_PYMETHODDEF_DOC_VARARGS(SCA_RandomActuator, setBoolBernouilli, -"setBoolBernouilli(value)\n" -"\t- value: a float between 0 and 1\n" -"\tReturn false value * 100%% of the time.\n") -{ - float paraArg; - if (!PyArg_ParseTuple(args, "f:setBoolBernouilli", ¶Arg)) { - return NULL; - } - - m_distribution = KX_RANDOMACT_BOOL_BERNOUILLI; - m_parameter1 = paraArg; - enforceConstraints(); - Py_RETURN_NONE; -} -/* 14. setIntConst,*/ -KX_PYMETHODDEF_DOC_VARARGS(SCA_RandomActuator, setIntConst, -"setIntConst(value)\n" -"\t- value: integer\n" -"\tAlways return value\n") -{ - int paraArg; - if (!PyArg_ParseTuple(args, "i:setIntConst", ¶Arg)) { - return NULL; - } - - m_distribution = KX_RANDOMACT_INT_CONST; - m_parameter1 = paraArg; - enforceConstraints(); - Py_RETURN_NONE; -} -/* 15. setIntUniform,*/ -KX_PYMETHODDEF_DOC_VARARGS(SCA_RandomActuator, setIntUniform, -"setIntUniform(lower_bound, upper_bound)\n" -"\t- lower_bound: integer\n" -"\t- upper_bound: integer\n" -"\tReturn a random integer between lower_bound and\n" -"\tupper_bound. The boundaries are included.\n") -{ - int paraArg1, paraArg2; - if (!PyArg_ParseTuple(args, "ii:setIntUniform", ¶Arg1, ¶Arg2)) { - return NULL; - } - - m_distribution = KX_RANDOMACT_INT_UNIFORM; - m_parameter1 = paraArg1; - m_parameter2 = paraArg2; - enforceConstraints(); - Py_RETURN_NONE; -} -/* 16. setIntPoisson, */ -KX_PYMETHODDEF_DOC_VARARGS(SCA_RandomActuator, setIntPoisson, -"setIntPoisson(value)\n" -"\t- value: float\n" -"\tReturn a Poisson-distributed number. This performs a series\n" -"\tof Bernouilli tests with parameter value. It returns the\n" -"\tnumber of tries needed to achieve succes.\n") -{ - float paraArg; - if (!PyArg_ParseTuple(args, "f:setIntPoisson", ¶Arg)) { - return NULL; - } - - m_distribution = KX_RANDOMACT_INT_POISSON; - m_parameter1 = paraArg; - enforceConstraints(); - Py_RETURN_NONE; -} -/* 17. setFloatConst */ -KX_PYMETHODDEF_DOC_VARARGS(SCA_RandomActuator, setFloatConst, -"setFloatConst(value)\n" -"\t- value: float\n" -"\tAlways return value\n") -{ - float paraArg; - if (!PyArg_ParseTuple(args, "f:setFloatConst", ¶Arg)) { - return NULL; - } - - m_distribution = KX_RANDOMACT_FLOAT_CONST; - m_parameter1 = paraArg; - enforceConstraints(); - Py_RETURN_NONE; -} -/* 18. setFloatUniform, */ -KX_PYMETHODDEF_DOC_VARARGS(SCA_RandomActuator, setFloatUniform, -"setFloatUniform(lower_bound, upper_bound)\n" -"\t- lower_bound: float\n" -"\t- upper_bound: float\n" -"\tReturn a random integer between lower_bound and\n" -"\tupper_bound.\n") -{ - float paraArg1, paraArg2; - if (!PyArg_ParseTuple(args, "ff:setFloatUniform", ¶Arg1, ¶Arg2)) { - return NULL; - } - - m_distribution = KX_RANDOMACT_FLOAT_UNIFORM; - m_parameter1 = paraArg1; - m_parameter2 = paraArg2; - enforceConstraints(); - Py_RETURN_NONE; -} -/* 19. setFloatNormal, */ -KX_PYMETHODDEF_DOC_VARARGS(SCA_RandomActuator, setFloatNormal, -"setFloatNormal(mean, standard_deviation)\n" -"\t- mean: float\n" -"\t- standard_deviation: float\n" -"\tReturn normal-distributed numbers. The average is mean, and the\n" -"\tdeviation from the mean is characterized by standard_deviation.\n") -{ - float paraArg1, paraArg2; - if (!PyArg_ParseTuple(args, "ff:setFloatNormal", ¶Arg1, ¶Arg2)) { - return NULL; - } - - m_distribution = KX_RANDOMACT_FLOAT_NORMAL; - m_parameter1 = paraArg1; - m_parameter2 = paraArg2; - enforceConstraints(); - Py_RETURN_NONE; -} -/* 20. setFloatNegativeExponential, */ -KX_PYMETHODDEF_DOC_VARARGS(SCA_RandomActuator, setFloatNegativeExponential, -"setFloatNegativeExponential(half_life)\n" -"\t- half_life: float\n" -"\tReturn negative-exponentially distributed numbers. The half-life 'time'\n" -"\tis characterized by half_life.\n") -{ - float paraArg; - if (!PyArg_ParseTuple(args, "f:setFloatNegativeExponential", ¶Arg)) { - return NULL; - } - - m_distribution = KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL; - m_parameter1 = paraArg; - enforceConstraints(); - Py_RETURN_NONE; -} - -#endif - -/* eof */ diff --git a/source/gameengine/GameLogic/SCA_RandomActuator.h b/source/gameengine/GameLogic/SCA_RandomActuator.h deleted file mode 100644 index 32b29fc4f43..00000000000 --- a/source/gameengine/GameLogic/SCA_RandomActuator.h +++ /dev/null @@ -1,120 +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 SCA_RandomActuator.h - * \ingroup gamelogic - * \brief Draw a random number, and put it in a property - */ - -#ifndef __SCA_RANDOMACTUATOR_H__ -#define __SCA_RANDOMACTUATOR_H__ - -#include "SCA_IActuator.h" -#include "SCA_RandomNumberGenerator.h" - -class SCA_RandomActuator : public SCA_IActuator -{ - Py_Header - /** Property to assign to */ - STR_String m_propname; - - /** First parameter. The meaning of the parameters depends on the - * distribution */ - float m_parameter1; - /** Second parameter. The meaning of the parameters depends on the - * distribution */ - float m_parameter2; - - /** The base generator */ - SCA_RandomNumberGenerator *m_base; - - /** just a generic, persistent counter */ - int m_counter; - - /** cache for the previous draw */ - long m_previous; - - /** apply constraints for the chosen distribution to the parameters */ - void enforceConstraints(void); - - public: - - enum KX_RANDOMACT_MODE { - KX_RANDOMACT_NODEF, - KX_RANDOMACT_BOOL_CONST, - KX_RANDOMACT_BOOL_UNIFORM, - KX_RANDOMACT_BOOL_BERNOUILLI, - KX_RANDOMACT_INT_CONST, - KX_RANDOMACT_INT_UNIFORM, - KX_RANDOMACT_INT_POISSON, - KX_RANDOMACT_FLOAT_CONST, - KX_RANDOMACT_FLOAT_UNIFORM, - KX_RANDOMACT_FLOAT_NORMAL, - KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL, - KX_RANDOMACT_MAX - }; - /** distribution type */ - KX_RANDOMACT_MODE m_distribution; - - SCA_RandomActuator(class SCA_IObject* gameobj, - long seed, - KX_RANDOMACT_MODE mode, - float para1, - float para2, - const STR_String &propName); - virtual ~SCA_RandomActuator(); - virtual bool Update(); - - virtual CValue* GetReplica(); - virtual void ProcessReplica(); - -#ifdef WITH_PYTHON - - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - - static PyObject *pyattr_get_seed(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_seed(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); - - KX_PYMETHOD_DOC_VARARGS(SCA_RandomActuator, setBoolConst); - KX_PYMETHOD_DOC_NOARGS(SCA_RandomActuator, setBoolUniform); - KX_PYMETHOD_DOC_VARARGS(SCA_RandomActuator, setBoolBernouilli); - KX_PYMETHOD_DOC_VARARGS(SCA_RandomActuator, setIntConst); - KX_PYMETHOD_DOC_VARARGS(SCA_RandomActuator, setIntUniform); - KX_PYMETHOD_DOC_VARARGS(SCA_RandomActuator, setIntPoisson); - KX_PYMETHOD_DOC_VARARGS(SCA_RandomActuator, setFloatConst); - KX_PYMETHOD_DOC_VARARGS(SCA_RandomActuator, setFloatUniform); - KX_PYMETHOD_DOC_VARARGS(SCA_RandomActuator, setFloatNormal); - KX_PYMETHOD_DOC_VARARGS(SCA_RandomActuator, setFloatNegativeExponential); - -#endif /* WITH_PYTHON */ - -}; /* end of class KX_EditObjectActuator : public SCA_PropertyActuator */ - -#endif - diff --git a/source/gameengine/GameLogic/SCA_RandomEventManager.cpp b/source/gameengine/GameLogic/SCA_RandomEventManager.cpp deleted file mode 100644 index 2ec6eb1db1b..00000000000 --- a/source/gameengine/GameLogic/SCA_RandomEventManager.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Manager for random 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/GameLogic/SCA_RandomEventManager.cpp - * \ingroup gamelogic - */ - -#include "SCA_RandomEventManager.h" -#include "SCA_LogicManager.h" -#include "SCA_ISensor.h" -#include -using namespace std; - -#include -#include - -SCA_RandomEventManager::SCA_RandomEventManager(class SCA_LogicManager* logicmgr) - : SCA_EventManager(logicmgr, RANDOM_EVENTMGR) -{ -} - - -void SCA_RandomEventManager::NextFrame() -{ - SG_DList::iterator it(m_sensors); - for (it.begin();!it.end();++it) - { - (*it)->Activate(m_logicmgr); - } -} - diff --git a/source/gameengine/GameLogic/SCA_RandomEventManager.h b/source/gameengine/GameLogic/SCA_RandomEventManager.h deleted file mode 100644 index 2d83c5fcdca..00000000000 --- a/source/gameengine/GameLogic/SCA_RandomEventManager.h +++ /dev/null @@ -1,54 +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 SCA_RandomEventManager.h - * \ingroup gamelogic - * \brief Manager for random events - */ - -#ifndef __SCA_RANDOMEVENTMANAGER_H__ -#define __SCA_RANDOMEVENTMANAGER_H__ - -#include "SCA_EventManager.h" -#include - -using namespace std; - -class SCA_RandomEventManager : public SCA_EventManager -{ -public: - SCA_RandomEventManager(class SCA_LogicManager* logicmgr); - - virtual void NextFrame(); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_RandomEventManager") -#endif -}; - -#endif /* __SCA_RANDOMEVENTMANAGER_H__ */ diff --git a/source/gameengine/GameLogic/SCA_RandomNumberGenerator.cpp b/source/gameengine/GameLogic/SCA_RandomNumberGenerator.cpp deleted file mode 100644 index eca678f4e89..00000000000 --- a/source/gameengine/GameLogic/SCA_RandomNumberGenerator.cpp +++ /dev/null @@ -1,133 +0,0 @@ -/** \file gameengine/GameLogic/SCA_RandomNumberGenerator.cpp - * \ingroup gamelogic - */ -/** - * Generate random numbers that can be used by other components. We - * convert to different types/distributions elsewhere. This just - * delivers a clean, random bitvector. - * - */ - -/* A C-program for MT19937: Real number version */ -/* genrand() generates one pseudorandom real number (double) */ -/* which is uniformly distributed on [0,1]-interval, for each */ -/* call. sgenrand(seed) set initial values to the working area */ -/* of 624 words. Before genrand(), sgenrand(seed) must be */ -/* called once. (seed is any 32-bit integer except for 0). */ -/* Integer generator is obtained by modifying two lines. */ -/* Coded by Takuji Nishimura, considering the suggestions by */ -/* Topher Cooper and Marc Rieffel in July-Aug. 1997. */ - -/* This library is free software; you can redistribute it and/or */ -/* modify it under the terms of the GNU Library General Public */ -/* License as published by the Free Software Foundation; either */ -/* version 2 of the License, or (at your option) any later */ -/* version. */ -/* This library 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 Library General Public License for more details. */ -/* You should have received a copy of the GNU Library General */ -/* Public License along with this library; if not, write to the */ -/* Free Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA */ -/* 02110-1301, USA */ - -/* Copyright (C) 1997 Makoto Matsumoto and Takuji Nishimura. */ -/* When you use this, send an email to: matumoto@math.keio.ac.jp */ -/* with an appropriate reference to your work. */ - -#include -#include "SCA_RandomNumberGenerator.h" - -/* Period parameters */ -#define N 624 -#define M 397 -#define MATRIX_A 0x9908b0df /* constant vector a */ -#define UPPER_MASK 0x80000000 /* most significant w-r bits */ -#define LOWER_MASK 0x7fffffff /* least significant r bits */ - -/* Tempering parameters */ -#define TEMPERING_MASK_B 0x9d2c5680 -#define TEMPERING_MASK_C 0xefc60000 -#define TEMPERING_SHIFT_U(y) (y >> 11) -#define TEMPERING_SHIFT_S(y) (y << 7) -#define TEMPERING_SHIFT_T(y) (y << 15) -#define TEMPERING_SHIFT_L(y) (y >> 18) - -SCA_RandomNumberGenerator::SCA_RandomNumberGenerator(long seed) -{ - // int mti = N + 1; /*unused*/ - m_seed = seed; - m_refcount = 1; - SetStartVector(); -} - -SCA_RandomNumberGenerator::~SCA_RandomNumberGenerator() -{ - /* intentionally empty */ -} - -void SCA_RandomNumberGenerator::SetStartVector(void) -{ - /* setting initial seeds to mt[N] using */ - /* the generator Line 25 of Table 1 in */ - /* [KNUTH 1981, The Art of Computer Programming */ - /* Vol. 2 (2nd Ed.), pp102] */ - mt[0] = m_seed & 0xffffffff; - for (mti = 1; mti < N; mti++) - mt[mti] = (69069 * mt[mti-1]) & 0xffffffff; -} - -long SCA_RandomNumberGenerator::GetSeed() { return m_seed; } -void SCA_RandomNumberGenerator::SetSeed(long newseed) -{ - m_seed = newseed; - SetStartVector(); -} - -/** - * This is the important part: copied verbatim :) - */ -unsigned long SCA_RandomNumberGenerator::Draw() -{ - static unsigned long mag01[2] = { 0x0, MATRIX_A }; - /* mag01[x] = x * MATRIX_A for x=0,1 */ - - unsigned long y; - - if (mti >= N) { /* generate N words at one time */ - int kk; - - /* I set this in the constructor, so it is always satisfied ! */ - // if (mti == N+1) /* if sgenrand() has not been called, */ - // GEN_srand(4357); /* a default initial seed is used */ - - for (kk = 0; kk < N - M; kk++) { - y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); - mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1]; - } - for (; kk < N-1; kk++) { - y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); - mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1]; - } - y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); - mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1]; - - mti = 0; - } - - y = mt[mti++]; - y ^= TEMPERING_SHIFT_U(y); - y ^= TEMPERING_SHIFT_S(y) & TEMPERING_MASK_B; - y ^= TEMPERING_SHIFT_T(y) & TEMPERING_MASK_C; - y ^= TEMPERING_SHIFT_L(y); - - return y; -} - -float SCA_RandomNumberGenerator::DrawFloat() -{ - return ( (float) Draw()/ (unsigned long) 0xffffffff ); -} - -/* eof */ diff --git a/source/gameengine/GameLogic/SCA_RandomNumberGenerator.h b/source/gameengine/GameLogic/SCA_RandomNumberGenerator.h deleted file mode 100644 index 10818cb4e8f..00000000000 --- a/source/gameengine/GameLogic/SCA_RandomNumberGenerator.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 SCA_RandomNumberGenerator.h - * \ingroup gamelogic - * \brief Generate random numbers that can be used by other components. Each - * generator needs its own generator, so that the seed can be set - * on a per-generator basis. - */ - -#ifndef __SCA_RANDOMNUMBERGENERATOR_H__ -#define __SCA_RANDOMNUMBERGENERATOR_H__ - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -class SCA_RandomNumberGenerator { - - /* reference counted for memleak */ - int m_refcount; - - /** base seed */ - long m_seed; - - /* A bit silly.. The N parameter is a define in the .cpp file */ - /** the array for the state vector */ - /* unsigned long mt[N]; */ - unsigned long mt[624]; - - /** mti==N+1 means mt[KX_MT_VectorLength] is not initialized */ - int mti; /* initialized in the cpp file */ - - /** Calculate a start vector */ - void SetStartVector(void); - public: - SCA_RandomNumberGenerator(long seed); - ~SCA_RandomNumberGenerator(); - unsigned long Draw(); - float DrawFloat(); - long GetSeed(); - void SetSeed(long newseed); - SCA_RandomNumberGenerator* AddRef() - { - ++m_refcount; - return this; - } - void Release() - { - if (--m_refcount == 0) - delete this; - } - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_RandomNumberGenerator") -#endif -}; - -#endif /* __SCA_RANDOMNUMBERGENERATOR_H__ */ - diff --git a/source/gameengine/GameLogic/SCA_RandomSensor.cpp b/source/gameengine/GameLogic/SCA_RandomSensor.cpp deleted file mode 100644 index 8f2dc8d80f5..00000000000 --- a/source/gameengine/GameLogic/SCA_RandomSensor.cpp +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Generate random pulses - * - * - * ***** 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/GameLogic/SCA_RandomSensor.cpp - * \ingroup gamelogic - */ - - -#include - -#include "SCA_RandomSensor.h" -#include "SCA_EventManager.h" -#include "SCA_RandomEventManager.h" -#include "SCA_LogicManager.h" -#include "EXP_ConstExpr.h" -#include - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -SCA_RandomSensor::SCA_RandomSensor(SCA_EventManager* eventmgr, - SCA_IObject* gameobj, - int startseed) - : SCA_ISensor(gameobj,eventmgr) -{ - m_basegenerator = new SCA_RandomNumberGenerator(startseed); - Init(); -} - - - -SCA_RandomSensor::~SCA_RandomSensor() -{ - m_basegenerator->Release(); -} - -void SCA_RandomSensor::Init() -{ - m_iteration = 0; - m_interval = 0; - m_lastdraw = false; - m_currentDraw = m_basegenerator->Draw(); -} - - -CValue* SCA_RandomSensor::GetReplica() -{ - CValue* replica = new SCA_RandomSensor(*this); - // this will copy properties and so on... - replica->ProcessReplica(); - - return replica; -} - -void SCA_RandomSensor::ProcessReplica() -{ - SCA_ISensor::ProcessReplica(); - // increment reference count so that we can release the generator at this end - m_basegenerator->AddRef(); -} - - -bool SCA_RandomSensor::IsPositiveTrigger() -{ - return (m_invert !=m_lastdraw); -} - - -bool SCA_RandomSensor::Evaluate() -{ - /* Random generator is the generator from Line 25 of Table 1 in */ - /* [KNUTH 1981, The Art of Computer Programming Vol. 2 */ - /* (2nd Ed.), pp102] */ - /* It's a very simple max. length sequence generator. We can */ - /* draw 32 bool values before having to generate the next */ - /* sequence value. There are some theorems that will tell you */ - /* this is a reasonable way of generating bools. Check Knuth. */ - /* Furthermore, we only draw each -eth frame. */ - - bool evaluateResult = false; - - if (++m_interval > m_skipped_ticks) { - bool drawResult = false; - m_interval = 0; - if (m_iteration > 31) { - m_currentDraw = m_basegenerator->Draw(); - drawResult = (m_currentDraw & 0x1) == 0; - m_iteration = 1; - } else { - drawResult = ((m_currentDraw >> m_iteration) & 0x1) == 0; - m_iteration++; - } - evaluateResult = drawResult != m_lastdraw; - m_lastdraw = drawResult; - } - - /* now pass this result to some controller */ - return evaluateResult; -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject SCA_RandomSensor::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "SCA_RandomSensor", - 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 SCA_RandomSensor::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef SCA_RandomSensor::Attributes[] = { - KX_PYATTRIBUTE_BOOL_RO("lastDraw",SCA_RandomSensor,m_lastdraw), - KX_PYATTRIBUTE_RW_FUNCTION("seed", SCA_RandomSensor, pyattr_get_seed, pyattr_set_seed), - {NULL} //Sentinel -}; - -PyObject *SCA_RandomSensor::pyattr_get_seed(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) -{ - SCA_RandomSensor* self = static_cast(self_v); - return PyLong_FromLong(self->m_basegenerator->GetSeed()); -} - -int SCA_RandomSensor::pyattr_set_seed(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) -{ - SCA_RandomSensor* self = static_cast(self_v); - if (!PyLong_Check(value)) { - PyErr_SetString(PyExc_TypeError, "sensor.seed = int: Random Sensor, expected an integer"); - return PY_SET_ATTR_FAIL; - } - self->m_basegenerator->SetSeed(PyLong_AsLong(value)); - return PY_SET_ATTR_SUCCESS; -} - -#endif // WITH_PYTHON - -/* eof */ diff --git a/source/gameengine/GameLogic/SCA_RandomSensor.h b/source/gameengine/GameLogic/SCA_RandomSensor.h deleted file mode 100644 index 66107b7b74b..00000000000 --- a/source/gameengine/GameLogic/SCA_RandomSensor.h +++ /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. - * - * 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 SCA_RandomSensor.h - * \ingroup gamelogic - * \brief Generate random pulses - */ - -#ifndef __SCA_RANDOMSENSOR_H__ -#define __SCA_RANDOMSENSOR_H__ - -#include "SCA_ISensor.h" -#include "EXP_BoolValue.h" -#include "SCA_RandomNumberGenerator.h" - -class SCA_RandomSensor : public SCA_ISensor -{ - Py_Header - - unsigned int m_currentDraw; - int m_iteration; - int m_interval; - SCA_RandomNumberGenerator *m_basegenerator; - bool m_lastdraw; -public: - SCA_RandomSensor(class SCA_EventManager* rndmgr, - SCA_IObject* gameobj, - int startseed); - virtual ~SCA_RandomSensor(); - virtual CValue* GetReplica(); - virtual void ProcessReplica(); - virtual bool Evaluate(); - virtual bool IsPositiveTrigger(); - virtual void Init(); - -#ifdef WITH_PYTHON - - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - - static PyObject* pyattr_get_seed(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef); - static int pyattr_set_seed(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value); -#endif -}; - -#endif /* __SCA_RANDOMSENSOR_H__ */ diff --git a/source/gameengine/GameLogic/SCA_TimeEventManager.cpp b/source/gameengine/GameLogic/SCA_TimeEventManager.cpp deleted file mode 100644 index c56a1496823..00000000000 --- a/source/gameengine/GameLogic/SCA_TimeEventManager.cpp +++ /dev/null @@ -1,120 +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/GameLogic/SCA_TimeEventManager.cpp - * \ingroup gamelogic - */ - -#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 "SCA_TimeEventManager.h" - -#include "SCA_LogicManager.h" -#include "EXP_FloatValue.h" - -SCA_TimeEventManager::SCA_TimeEventManager(SCA_LogicManager* logicmgr) -: SCA_EventManager(NULL, TIME_EVENTMGR) -{ -} - - - -SCA_TimeEventManager::~SCA_TimeEventManager() -{ - for (vector::iterator it = m_timevalues.begin(); - !(it == m_timevalues.end()); ++it) - { - (*it)->Release(); - } -} - - - -void SCA_TimeEventManager::RegisterSensor(SCA_ISensor* sensor) -{ - // not yet -} - -void SCA_TimeEventManager::RemoveSensor(SCA_ISensor* sensor) -{ - // empty -} - - - -void SCA_TimeEventManager::NextFrame(double curtime, double fixedtime) -{ - if (m_timevalues.size() > 0 && fixedtime > 0.0) - { - CFloatValue* floatval = new CFloatValue(curtime); - - // update sensors, but ... need deltatime ! - for (vector::iterator it = m_timevalues.begin(); - !(it == m_timevalues.end()); ++it) - { - float newtime = (*it)->GetNumber() + fixedtime; - floatval->SetFloat(newtime); - (*it)->SetValue(floatval); - } - - floatval->Release(); - } -} - - - -void SCA_TimeEventManager::AddTimeProperty(CValue* timeval) -{ - timeval->AddRef(); - m_timevalues.push_back(timeval); -} - - - -void SCA_TimeEventManager::RemoveTimeProperty(CValue* timeval) -{ - for (vector::iterator it = m_timevalues.begin(); - !(it == m_timevalues.end()); ++it) - { - if ((*it) == timeval) - { - this->m_timevalues.erase(it); - timeval->Release(); - break; - } - } -} - -vector SCA_TimeEventManager::GetTimeValues() -{ - return m_timevalues; -} - diff --git a/source/gameengine/GameLogic/SCA_TimeEventManager.h b/source/gameengine/GameLogic/SCA_TimeEventManager.h deleted file mode 100644 index 38d7e3fc4d4..00000000000 --- a/source/gameengine/GameLogic/SCA_TimeEventManager.h +++ /dev/null @@ -1,62 +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 SCA_TimeEventManager.h - * \ingroup gamelogic - */ - -#ifndef __SCA_TIMEEVENTMANAGER_H__ -#define __SCA_TIMEEVENTMANAGER_H__ - -#include "SCA_EventManager.h" -#include "EXP_Value.h" -#include - -using namespace std; - -class SCA_TimeEventManager : public SCA_EventManager -{ - vector m_timevalues; // values that need their time updated regularly - -public: - SCA_TimeEventManager(class SCA_LogicManager* logicmgr); - virtual ~SCA_TimeEventManager(); - - virtual void NextFrame(double curtime, double fixedtime); - virtual void RegisterSensor(class SCA_ISensor* sensor); - virtual void RemoveSensor(class SCA_ISensor* sensor); - void AddTimeProperty(CValue* timeval); - void RemoveTimeProperty(CValue* timeval); - - vector GetTimeValues(); - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_TimeEventManager") -#endif -}; - -#endif /* __SCA_TIMEEVENTMANAGER_H__ */ diff --git a/source/gameengine/GameLogic/SCA_XNORController.cpp b/source/gameengine/GameLogic/SCA_XNORController.cpp deleted file mode 100644 index f97d11cabf3..00000000000 --- a/source/gameengine/GameLogic/SCA_XNORController.cpp +++ /dev/null @@ -1,137 +0,0 @@ -/* - * 'Xnor' together all inputs - * - * - * ***** 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/GameLogic/SCA_XNORController.cpp - * \ingroup gamelogic - */ - - -#include "SCA_XNORController.h" -#include "SCA_ISensor.h" -#include "SCA_LogicManager.h" -#include "EXP_BoolValue.h" - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -SCA_XNORController::SCA_XNORController(SCA_IObject* gameobj) - : - SCA_IController(gameobj) -{ -} - - - -SCA_XNORController::~SCA_XNORController() -{ -} - - - -void SCA_XNORController::Trigger(SCA_LogicManager* logicmgr) -{ - - bool sensorresult = true; - - for (vector::const_iterator is=m_linkedsensors.begin(); - !(is==m_linkedsensors.end());is++) - { - SCA_ISensor* sensor = *is; - if (sensor->GetState()) - { - if (sensorresult == false) - { - sensorresult = true; - break; - } - sensorresult = false; - } - } - - for (vector::const_iterator i=m_linkedactuators.begin(); - !(i==m_linkedactuators.end());i++) - { - SCA_IActuator* actua = *i; - logicmgr->AddActiveActuator(actua,sensorresult); - } -} - - - -CValue* SCA_XNORController::GetReplica() -{ - CValue* replica = new SCA_XNORController(*this); - // this will copy properties and so on... - replica->ProcessReplica(); - - return replica; -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject SCA_XNORController::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "SCA_XNORController", - 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_IController::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef SCA_XNORController::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef SCA_XNORController::Attributes[] = { - { NULL } //Sentinel -}; - -#endif // WITH_PYTHON - -/* eof */ diff --git a/source/gameengine/GameLogic/SCA_XNORController.h b/source/gameengine/GameLogic/SCA_XNORController.h deleted file mode 100644 index c257b71273e..00000000000 --- a/source/gameengine/GameLogic/SCA_XNORController.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 SCA_XNORController.h - * \ingroup gamelogic - */ - -#ifndef __SCA_XNORCONTROLLER_H__ -#define __SCA_XNORCONTROLLER_H__ - -#include "SCA_IController.h" - -class SCA_XNORController : public SCA_IController -{ - Py_Header - //virtual void Trigger(class SCA_LogicManager* logicmgr); -public: - SCA_XNORController(SCA_IObject* gameobj); - virtual ~SCA_XNORController(); - virtual CValue* GetReplica(); - virtual void Trigger(SCA_LogicManager* logicmgr); - - /* --------------------------------------------------------------------- */ - /* Python interface ---------------------------------------------------- */ - /* --------------------------------------------------------------------- */ - -}; - -#endif /* __SCA_XNORCONTROLLER_H__ */ diff --git a/source/gameengine/GameLogic/SCA_XORController.cpp b/source/gameengine/GameLogic/SCA_XORController.cpp deleted file mode 100644 index bb1ea822bd8..00000000000 --- a/source/gameengine/GameLogic/SCA_XORController.cpp +++ /dev/null @@ -1,136 +0,0 @@ -/* - * 'Xor' together all inputs - * - * - * ***** 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/GameLogic/SCA_XORController.cpp - * \ingroup gamelogic - */ - - -#include "SCA_XORController.h" -#include "SCA_ISensor.h" -#include "SCA_LogicManager.h" -#include "EXP_BoolValue.h" - -/* ------------------------------------------------------------------------- */ -/* Native functions */ -/* ------------------------------------------------------------------------- */ - -SCA_XORController::SCA_XORController(SCA_IObject* gameobj) - : - SCA_IController(gameobj) -{ -} - - - -SCA_XORController::~SCA_XORController() -{ -} - - - -void SCA_XORController::Trigger(SCA_LogicManager* logicmgr) -{ - - bool sensorresult = false; - - for (vector::const_iterator is=m_linkedsensors.begin(); - !(is==m_linkedsensors.end());is++) - { - SCA_ISensor* sensor = *is; - if (sensor->GetState()) - { - if (sensorresult == true) - { - sensorresult = false; - break; - } - sensorresult = true; - } - } - - for (vector::const_iterator i=m_linkedactuators.begin(); - !(i==m_linkedactuators.end());i++) - { - SCA_IActuator* actua = *i; - logicmgr->AddActiveActuator(actua,sensorresult); - } -} - - - -CValue* SCA_XORController::GetReplica() -{ - CValue* replica = new SCA_XORController(*this); - // this will copy properties and so on... - replica->ProcessReplica(); - - return replica; -} - -#ifdef WITH_PYTHON - -/* ------------------------------------------------------------------------- */ -/* Python functions */ -/* ------------------------------------------------------------------------- */ - -/* Integration hooks ------------------------------------------------------- */ -PyTypeObject SCA_XORController::Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "SCA_XORController", - 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_IController::Type, - 0,0,0,0,0,0, - py_base_new -}; - -PyMethodDef SCA_XORController::Methods[] = { - {NULL,NULL} //Sentinel -}; - -PyAttributeDef SCA_XORController::Attributes[] = { - { NULL } //Sentinel -}; -#endif // WITH_PYTHON - -/* eof */ diff --git a/source/gameengine/GameLogic/SCA_XORController.h b/source/gameengine/GameLogic/SCA_XORController.h deleted file mode 100644 index c64a3380ede..00000000000 --- a/source/gameengine/GameLogic/SCA_XORController.h +++ /dev/null @@ -1,48 +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 SCA_XORController.h - * \ingroup gamelogic - */ - -#ifndef __SCA_XORCONTROLLER_H__ -#define __SCA_XORCONTROLLER_H__ - -#include "SCA_IController.h" - -class SCA_XORController : public SCA_IController -{ - Py_Header - //virtual void Trigger(class SCA_LogicManager* logicmgr); -public: - SCA_XORController(SCA_IObject* gameobj); - virtual ~SCA_XORController(); - virtual CValue* GetReplica(); - virtual void Trigger(SCA_LogicManager* logicmgr); -}; - -#endif /* __SCA_XORCONTROLLER_H__ */ diff --git a/source/gameengine/GamePlayer/CMakeLists.txt b/source/gameengine/GamePlayer/CMakeLists.txt deleted file mode 100644 index e77609985dc..00000000000 --- a/source/gameengine/GamePlayer/CMakeLists.txt +++ /dev/null @@ -1,27 +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 ***** - -add_subdirectory(common) -add_subdirectory(ghost) diff --git a/source/gameengine/GamePlayer/common/CMakeLists.txt b/source/gameengine/GamePlayer/common/CMakeLists.txt deleted file mode 100644 index e6c980de566..00000000000 --- a/source/gameengine/GamePlayer/common/CMakeLists.txt +++ /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) 2006, Blender Foundation -# All rights reserved. -# -# The Original Code is: all of this file. -# -# Contributor(s): Jacques Beaurain. -# -# ***** END GPL LICENSE BLOCK ***** - -set(INC - . - ../ghost - ../../BlenderRoutines - ../../Converter - ../../Expressions - ../../GameLogic - ../../Ketsji - ../../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 - ../../../../intern/container - ../../../../intern/ghost - ../../../../intern/glew-mx - ../../../../intern/guardedalloc - ../../../../intern/string -) - -set(INC_SYS - ../../../../intern/moto/include - ${GLEW_INCLUDE_PATH} - ${PYTHON_INCLUDE_DIRS} - ${PNG_INCLUDE_DIRS} - ${ZLIB_INCLUDE_DIRS} -) - -set(SRC - GPC_Canvas.cpp - GPC_KeyboardDevice.cpp - GPC_MouseDevice.cpp - - GPC_Canvas.h - GPC_KeyboardDevice.h - GPC_MouseDevice.h -) - -add_definitions(${GL_DEFINITIONS}) - -blender_add_lib_nolist(ge_player_common "${SRC}" "${INC}" "${INC_SYS}") diff --git a/source/gameengine/GamePlayer/common/GPC_Canvas.cpp b/source/gameengine/GamePlayer/common/GPC_Canvas.cpp deleted file mode 100644 index 2b355407d46..00000000000 --- a/source/gameengine/GamePlayer/common/GPC_Canvas.cpp +++ /dev/null @@ -1,168 +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/GamePlayer/common/GPC_Canvas.cpp - * \ingroup player - */ - - -#include "RAS_IPolygonMaterial.h" -#include "GPC_Canvas.h" - -#include "DNA_scene_types.h" -#include "DNA_space_types.h" - -#include "BKE_image.h" -#include "MEM_guardedalloc.h" - - -GPC_Canvas::GPC_Canvas( - int width, - int height -) : - m_width(width), - m_height(height) -{ - // initialize area so that it's available for game logic on frame 1 (ImageViewport) - m_displayarea.m_x1 = 0; - m_displayarea.m_y1 = 0; - m_displayarea.m_x2 = width; - m_displayarea.m_y2 = height; - m_frame = 1; - - glGetIntegerv(GL_VIEWPORT, (GLint*)m_viewport); -} - - -GPC_Canvas::~GPC_Canvas() -{ -} - - -void GPC_Canvas::Resize(int width, int height) -{ - m_width = width; - m_height = height; - - // initialize area so that it's available for game logic on frame 1 (ImageViewport) - m_displayarea.m_x1 = 0; - m_displayarea.m_y1 = 0; - m_displayarea.m_x2 = width; - m_displayarea.m_y2 = height; -} - - -void GPC_Canvas::ClearColor(float r, float g, float b, float a) -{ - ::glClearColor(r,g,b,a); -} - -void GPC_Canvas::SetViewPort(int x1, int y1, int x2, int y2) -{ - /* x1 and y1 are the min pixel coordinate (e.g. 0) - x2 and y2 are the max pixel coordinate - the width,height is calculated including both pixels - therefore: max - min + 1 - */ - - /* XXX, nasty, this needs to go somewhere else, - * but where... definitely need to clean up this - * whole canvas/rendertools mess. - */ - glEnable(GL_SCISSOR_TEST); - - m_viewport[0] = x1; - m_viewport[1] = y1; - m_viewport[2] = x2-x1 + 1; - m_viewport[3] = y2-y1 + 1; - - glViewport(x1,y1,x2-x1 + 1,y2-y1 + 1); - glScissor(x1,y1,x2-x1 + 1,y2-y1 + 1); -} - -void GPC_Canvas::UpdateViewPort(int x1, int y1, int x2, int y2) -{ - m_viewport[0] = x1; - m_viewport[1] = y1; - m_viewport[2] = x2; - m_viewport[3] = y2; -} - -const int *GPC_Canvas::GetViewPort() -{ -#ifdef DEBUG - // If we're in a debug build, we might as well make sure our values don't differ - // from what the gpu thinks we have. This could lead to nasty, hard to find bugs. - int viewport[4]; - glGetIntegerv(GL_VIEWPORT, viewport); - assert(viewport[0] == m_viewport[0]); - assert(viewport[1] == m_viewport[1]); - assert(viewport[2] == m_viewport[2]); - assert(viewport[3] == m_viewport[3]); -#endif - - return m_viewport; -} - -void GPC_Canvas::ClearBuffer( - int type -) { - - int ogltype = 0; - if (type & RAS_ICanvas::COLOR_BUFFER ) - ogltype |= GL_COLOR_BUFFER_BIT; - if (type & RAS_ICanvas::DEPTH_BUFFER ) - ogltype |= GL_DEPTH_BUFFER_BIT; - - ::glClear(ogltype); -} - - void -GPC_Canvas:: -MakeScreenShot( - const char* filename -) { - // copy image data - unsigned int dumpsx = GetWidth(); - unsigned int dumpsy = GetHeight(); - unsigned int *pixels = (unsigned int *)MEM_mallocN(sizeof(int) * dumpsx * dumpsy, "pixels"); - - if (!pixels) { - std::cout << "Cannot allocate pixels array" << std::endl; - return; - } - - glReadPixels(0, 0, dumpsx, dumpsy, GL_RGBA, GL_UNSIGNED_BYTE, pixels); - - // initialize image file format data - ImageFormatData *im_format = (ImageFormatData *)MEM_mallocN(sizeof(ImageFormatData), "im_format"); - BKE_imformat_defaults(im_format); - - /* save_screenshot() frees dumprect and im_format */ - save_screenshot(filename, dumpsx, dumpsy, pixels, im_format); -} - diff --git a/source/gameengine/GamePlayer/common/GPC_Canvas.h b/source/gameengine/GamePlayer/common/GPC_Canvas.h deleted file mode 100644 index 688ed8ac0f4..00000000000 --- a/source/gameengine/GamePlayer/common/GPC_Canvas.h +++ /dev/null @@ -1,147 +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 GPC_Canvas.h - * \ingroup player - */ - -#ifndef __GPC_CANVAS_H__ -#define __GPC_CANVAS_H__ - -#include "RAS_ICanvas.h" -#include "RAS_Rect.h" - -#ifdef WIN32 -# pragma warning (disable:4786) // suppress stl-MSVC debug info warning -# include -#endif /* WIN32 */ - -#include "GPU_glew.h" - -#include - - -class GPC_Canvas : public RAS_ICanvas -{ -protected: - - /** Width of the context. */ - int m_width; - /** Height of the context. */ - int m_height; - /** Rect that defines the area used for rendering, - * relative to the context */ - RAS_Rect m_displayarea; - - int m_viewport[4]; - -public: - - GPC_Canvas(int width, int height); - - virtual ~GPC_Canvas(); - - void Resize(int width, int height); - - virtual void ResizeWindow(int width, int height) {} - - virtual void GetDisplayDimensions(int &width, int &height) {} - - /** - * \section Methods inherited from abstract base class RAS_ICanvas. - */ - - int - GetWidth( - ) const { - return m_width; - } - - int - GetHeight( - ) const { - return m_height; - } - - const - RAS_Rect & - GetDisplayArea( - ) const { - return m_displayarea; - }; - - void - SetDisplayArea( - RAS_Rect *rect - ) { - m_displayarea= *rect; - }; - - RAS_Rect & - GetWindowArea( - ) { - return m_displayarea; - } - - void - BeginFrame( - ) {}; - - /** - * Draws overlay banners and progress bars. - */ - void - EndFrame( - ) {}; - - void SetViewPort(int x1, int y1, int x2, int y2); - void UpdateViewPort(int x1, int y1, int x2, int y2); - const int *GetViewPort(); - - void ClearColor(float r, float g, float b, float a); - - /** - * \section Methods inherited from abstract base class RAS_ICanvas. - * Semantics are not yet honored. - */ - - void SetMouseState(RAS_MouseState mousestate) - { - // not yet - } - - void SetMousePosition(int x, int y) - { - // not yet - } - - virtual void MakeScreenShot(const char* filename); - - void ClearBuffer(int type); -}; - -#endif /* __GPC_CANVAS_H__ */ diff --git a/source/gameengine/GamePlayer/common/GPC_KeyboardDevice.cpp b/source/gameengine/GamePlayer/common/GPC_KeyboardDevice.cpp deleted file mode 100644 index 0821d1d3b23..00000000000 --- a/source/gameengine/GamePlayer/common/GPC_KeyboardDevice.cpp +++ /dev/null @@ -1,128 +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/GamePlayer/common/GPC_KeyboardDevice.cpp - * \ingroup player - */ - - -#include "GPC_KeyboardDevice.h" - -#include - -/** - * NextFrame toggles currentTable with previousTable, - * and copies relevant event information from previous to current table - * (pressed keys need to be remembered). - */ -void GPC_KeyboardDevice::NextFrame() -{ - SCA_IInputDevice::NextFrame(); - - // Now convert justpressed key events into regular (active) keyevents - int previousTable = 1-m_currentTable; - for (int keyevent= KX_BEGINKEY; keyevent<= KX_ENDKEY;keyevent++) - { - SCA_InputEvent& oldevent = m_eventStatusTables[previousTable][keyevent]; - if (oldevent.m_status == SCA_InputEvent::KX_JUSTACTIVATED || - oldevent.m_status == SCA_InputEvent::KX_ACTIVE ) - { - m_eventStatusTables[m_currentTable][keyevent] = oldevent; - m_eventStatusTables[m_currentTable][keyevent].m_status = SCA_InputEvent::KX_ACTIVE; - //m_eventStatusTables[m_currentTable][keyevent].m_status = SCA_InputEvent::KX_JUSTACTIVATED; - } - } -} - - - -/** - * ConvertBPEvent translates Windows keyboard events into ketsji kbd events. - * Extra event information is stored, like ramp-mode (just released/pressed) - */ -bool GPC_KeyboardDevice::ConvertEvent(int incode, int val, unsigned int unicode) -{ - bool result = false; - - // convert event - KX_EnumInputs kxevent = this->ToNative(incode); - - // only process it, if it's a key - if (kxevent >= KX_BEGINKEY && kxevent <= KX_ENDKEY) - { - int previousTable = 1-m_currentTable; - - if (val > 0) - { - if (kxevent == SCA_IInputDevice::KX_ESCKEY && val != 0 && !m_hookesc) - result = true; - - // todo: convert val ?? - m_eventStatusTables[m_currentTable][kxevent].m_eventval = val ; //??? - m_eventStatusTables[m_currentTable][kxevent].m_unicode = unicode ; - - switch (m_eventStatusTables[previousTable][kxevent].m_status) - { - case SCA_InputEvent::KX_JUSTACTIVATED: - case SCA_InputEvent::KX_ACTIVE: - { - m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_ACTIVE; - break; - } - - case SCA_InputEvent::KX_NO_INPUTSTATUS: - default: - { - m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_JUSTACTIVATED; - } - } - - } else - { - - switch (m_eventStatusTables[previousTable][kxevent].m_status) - { - case SCA_InputEvent::KX_JUSTACTIVATED: - case SCA_InputEvent::KX_ACTIVE: - { - m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_JUSTRELEASED; - break; - } - default: - { - m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_NO_INPUTSTATUS; - } - } - } - } - return result; -} - -void GPC_KeyboardDevice::HookEscape() -{ - m_hookesc = true; -} diff --git a/source/gameengine/GamePlayer/common/GPC_KeyboardDevice.h b/source/gameengine/GamePlayer/common/GPC_KeyboardDevice.h deleted file mode 100644 index d9842a42e0a..00000000000 --- a/source/gameengine/GamePlayer/common/GPC_KeyboardDevice.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 GPC_KeyboardDevice.h - * \ingroup player - */ - -#ifndef __GPC_KEYBOARDDEVICE_H__ -#define __GPC_KEYBOARDDEVICE_H__ - -#ifdef WIN32 -#pragma warning (disable:4786) -#endif /* WIN32 */ - -#include "SCA_IInputDevice.h" - -#include - - -/** - * System independent implementation of SCA_IInputDevice. - * System dependent keyboard devices need only to inherit this class - * and fill the m_reverseKeyTranslateTable key translation map. - * \see SCA_IInputDevice - */ - -class GPC_KeyboardDevice : public SCA_IInputDevice -{ -protected: - - /** - * This map converts system dependent keyboard codes into Ketsji codes. - * System dependent keyboard codes are stored as ints. - */ - std::map m_reverseKeyTranslateTable; - short m_exitkey; - -public: - bool m_hookesc; - GPC_KeyboardDevice() - : m_hookesc(false) - { - } - - virtual ~GPC_KeyboardDevice(void) - { - } - - virtual bool IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode) - { - return false; - } - - virtual void NextFrame(); - - virtual KX_EnumInputs ToNative(int incode) - { - return m_reverseKeyTranslateTable[incode]; - } - - virtual bool ConvertEvent(int incode, int val, unsigned int unicode); - - virtual void HookEscape(); -}; - -#endif /* __GPC_KEYBOARDDEVICE_H__ */ diff --git a/source/gameengine/GamePlayer/common/GPC_MouseDevice.cpp b/source/gameengine/GamePlayer/common/GPC_MouseDevice.cpp deleted file mode 100644 index 94045d532af..00000000000 --- a/source/gameengine/GamePlayer/common/GPC_MouseDevice.cpp +++ /dev/null @@ -1,214 +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/GamePlayer/common/GPC_MouseDevice.cpp - * \ingroup player - */ - - -#include "GPC_MouseDevice.h" - -GPC_MouseDevice::GPC_MouseDevice() -{ - -} -GPC_MouseDevice::~GPC_MouseDevice() -{ - -} - -/** - * IsPressed gives boolean information about mouse status, true if pressed, false if not. - */ -bool GPC_MouseDevice::IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode) -{ - const SCA_InputEvent & inevent = m_eventStatusTables[m_currentTable][inputcode]; - bool pressed = (inevent.m_status == SCA_InputEvent::KX_JUSTACTIVATED || - inevent.m_status == SCA_InputEvent::KX_ACTIVE); - return pressed; -} - - -/** - * NextFrame toggles currentTable with previousTable, - * and copies relevant event information from previous to current table - * (pressed keys need to be remembered). - */ -void GPC_MouseDevice::NextFrame() -{ - SCA_IInputDevice::NextFrame(); - - // Convert just pressed events into regular (active) events - int previousTable = 1-m_currentTable; - for (int mouseevent= KX_BEGINMOUSE; mouseevent< KX_ENDMOUSEBUTTONS; mouseevent++) { - SCA_InputEvent& oldevent = m_eventStatusTables[previousTable][mouseevent]; - if (oldevent.m_status == SCA_InputEvent::KX_JUSTACTIVATED || - oldevent.m_status == SCA_InputEvent::KX_ACTIVE) - { - m_eventStatusTables[m_currentTable][mouseevent] = oldevent; - m_eventStatusTables[m_currentTable][mouseevent].m_status = SCA_InputEvent::KX_ACTIVE; - } - } - for (int mousemove= KX_ENDMOUSEBUTTONS; mousemove< KX_ENDMOUSE; mousemove++) { - SCA_InputEvent& oldevent = m_eventStatusTables[previousTable][mousemove]; - m_eventStatusTables[m_currentTable][mousemove] = oldevent; - if (oldevent.m_status == SCA_InputEvent::KX_JUSTACTIVATED || - oldevent.m_status == SCA_InputEvent::KX_ACTIVE) - { - m_eventStatusTables[m_currentTable][mousemove].m_status = SCA_InputEvent::KX_JUSTRELEASED; - } - else { - if (oldevent.m_status == SCA_InputEvent::KX_JUSTRELEASED) { - m_eventStatusTables[m_currentTable][mousemove].m_status = SCA_InputEvent::KX_NO_INPUTSTATUS; - } - } - } -} - - -bool GPC_MouseDevice::ConvertButtonEvent(TButtonId button, bool isDown) -{ - bool result = false; - - switch (button) - { - case buttonLeft: - result = ConvertEvent(KX_LEFTMOUSE, isDown, 0); - break; - case buttonMiddle: - result = ConvertEvent(KX_MIDDLEMOUSE, isDown, 0); - break; - case buttonRight: - result = ConvertEvent(KX_RIGHTMOUSE, isDown, 0); - break; - case buttonWheelUp: - result = ConvertEvent(KX_WHEELUPMOUSE, isDown, 0); - break; - case buttonWheelDown: - result = ConvertEvent(KX_WHEELDOWNMOUSE, isDown, 0); - break; - default: - // Should not happen! - break; - } - - return result; -} - -/** - * Splits combined button and x,y cursor move events into separate Ketsji - * x and y move and button events. - */ -bool GPC_MouseDevice::ConvertButtonEvent(TButtonId button, bool isDown, int x, int y) -{ - // First update state tables for cursor move. - bool result = ConvertMoveEvent(x, y); - - // Now update for button state. - if (result) { - result = ConvertButtonEvent(button, isDown); - } - - return result; -} - -/** - * Splits combined x,y move into separate Ketsji x and y move events. - */ -bool GPC_MouseDevice::ConvertMoveEvent(int x, int y) -{ - bool result; - - // Convert to local coordinates? - result = ConvertEvent(KX_MOUSEX, x, 0); - if (result) { - result = ConvertEvent(KX_MOUSEY, y, 0); - } - - return result; -} - - -bool GPC_MouseDevice::ConvertEvent(KX_EnumInputs kxevent, int eventval, unsigned int unicode) -{ - bool result = true; - - // Only process it, if it's a mouse event - if (kxevent > KX_BEGINMOUSE && kxevent < KX_ENDMOUSE) { - int previousTable = 1-m_currentTable; - - if (eventval > 0) { - m_eventStatusTables[m_currentTable][kxevent].m_eventval = eventval; - - switch (m_eventStatusTables[previousTable][kxevent].m_status) - { - case SCA_InputEvent::KX_ACTIVE: - case SCA_InputEvent::KX_JUSTACTIVATED: - { - m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_ACTIVE; - break; - } - case SCA_InputEvent::KX_JUSTRELEASED: - { - if ( kxevent > KX_BEGINMOUSEBUTTONS && kxevent < KX_ENDMOUSEBUTTONS) - { - m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_JUSTACTIVATED; - } else - { - m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_ACTIVE; - - } - break; - } - default: - { - m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_JUSTACTIVATED; - } - } - - } - else { - switch (m_eventStatusTables[previousTable][kxevent].m_status) - { - case SCA_InputEvent::KX_JUSTACTIVATED: - case SCA_InputEvent::KX_ACTIVE: - { - m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_JUSTRELEASED; - break; - } - default: - { - m_eventStatusTables[m_currentTable][kxevent].m_status = SCA_InputEvent::KX_NO_INPUTSTATUS; - } - } - } - } - else { - result = false; - } - return result; -} diff --git a/source/gameengine/GamePlayer/common/GPC_MouseDevice.h b/source/gameengine/GamePlayer/common/GPC_MouseDevice.h deleted file mode 100644 index 24922197723..00000000000 --- a/source/gameengine/GamePlayer/common/GPC_MouseDevice.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 GPC_MouseDevice.h - * \ingroup player - */ - -#ifndef __GPC_MOUSEDEVICE_H__ -#define __GPC_MOUSEDEVICE_H__ - -#ifdef WIN32 -#pragma warning (disable:4786) -#endif /* WIN32 */ - -#include "SCA_IInputDevice.h" - - -/** - * Generic Ketsji mouse device. - * \see SCA_IInputDevice - */ -class GPC_MouseDevice : public SCA_IInputDevice -{ -public: - /** - * Button identifier. - */ - typedef enum { - buttonLeft, - buttonMiddle, - buttonRight, - buttonWheelUp, - buttonWheelDown - } TButtonId; - - GPC_MouseDevice(); - virtual ~GPC_MouseDevice(void); - - virtual bool IsPressed(SCA_IInputDevice::KX_EnumInputs inputcode); - virtual void NextFrame(); - - /** - * Call this routine to update the mouse device when a button state changes. - * \param button Which button state changes. - * \param isDown The new state of the button. - * \return Indication as to whether the event was processed. - */ - virtual bool ConvertButtonEvent(TButtonId button, bool isDown); - - /** - * Call this routine to update the mouse device when a button state and - * cursor position changes at the same time (e.g. in Win32 messages). - * \param button Which button state changes. - * \param isDown The new state of the button. - * \param x Position x-coordinate of the cursor at the time of the state change. - * \param y Position y-coordinate of the cursor at the time of the state change. - * \return Indication as to whether the event was processed. - */ - virtual bool ConvertButtonEvent(TButtonId button, bool isDown, int x, int y); - - /** - * Call this routine to update the mouse device when the cursor has moved. - * \param x Position x-coordinate of the cursor. - * \param y Position y-coordinate of the cursor. - * \return Indication as to whether the event was processed. - */ - virtual bool ConvertMoveEvent(int x, int y); - -protected: - /** - * This routine converts a single mouse event to a Ketsji mouse event. - * \param kxevent Ketsji event code. - * \param eventval Value for this event. - * \return Indication as to whether the event was processed. - */ - virtual bool ConvertEvent(KX_EnumInputs kxevent, int eventval, unsigned int unicode); -}; - -#endif /* __GPC_MOUSEDEVICE_H__ */ diff --git a/source/gameengine/GamePlayer/ghost/CMakeLists.txt b/source/gameengine/GamePlayer/ghost/CMakeLists.txt deleted file mode 100644 index 5bce9fcd248..00000000000 --- a/source/gameengine/GamePlayer/ghost/CMakeLists.txt +++ /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) 2006, Blender Foundation -# All rights reserved. -# -# The Original Code is: all of this file. -# -# Contributor(s): Jacques Beaurain. -# -# ***** END GPL LICENSE BLOCK ***** - -set(INC - . - ../common - ../../BlenderRoutines - ../../Converter - ../../Expressions - ../../GameLogic - ../../Ketsji - ../../Network - ../../Network/LoopBackNetwork - ../../Physics/common - ../../Rasterizer - ../../Rasterizer/RAS_OpenGLRasterizer - ../../SceneGraph - ../../../blender - ../../../blender/blenfont - ../../../blender/blenkernel - ../../../blender/blenlib - ../../../blender/blenloader - ../../../blender/blentranslation - ../../../blender/depsgraph - ../../../blender/gpu - ../../../blender/imbuf - ../../../blender/makesdna - ../../../blender/makesrna - ../../../../intern/container - ../../../../intern/ghost - ../../../../intern/glew-mx - ../../../../intern/guardedalloc - ../../../../intern/string - ../../../../intern/memutil -) - -set(INC_SYS - ../../../../intern/moto/include - ${GLEW_INCLUDE_PATH} - ${PYTHON_INCLUDE_DIRS} - ${BOOST_INCLUDE_DIR} -) - -set(SRC - GPG_Application.cpp - GPG_Canvas.cpp - GPG_KeyboardDevice.cpp - GPG_System.cpp - GPG_ghost.cpp - - GPG_Application.h - GPG_Canvas.h - GPG_KeyboardDevice.h - GPG_System.h -) - -add_definitions(${GL_DEFINITIONS}) - -if(WIN32) - blender_include_dirs(../../../../intern/utfconv) -endif() - -if(WITH_INPUT_NDOF) - add_definitions(-DWITH_INPUT_NDOF) -endif(WITH_INPUT_NDOF) - -if(WITH_CODEC_FFMPEG) - add_definitions(-DWITH_FFMPEG) -endif() - -if(WITH_INTERNATIONAL) - add_definitions(-DWITH_INTERNATIONAL) -endif() - -if(WITH_AUDASPACE) - add_definitions(-DWITH_AUDASPACE) - - list(APPEND INC_SYS - ${AUDASPACE_C_INCLUDE_DIRS} - ) -endif() - -if(WITH_SDL AND WITH_SDL_DYNLOAD) - list(APPEND INC - ../../../../extern/sdlew/include - ) - add_definitions(-DWITH_SDL_DYNLOAD) -endif() - -blender_add_lib_nolist(ge_player_ghost "${SRC}" "${INC}" "${INC_SYS}") diff --git a/source/gameengine/GamePlayer/ghost/GPG_Application.cpp b/source/gameengine/GamePlayer/ghost/GPG_Application.cpp deleted file mode 100644 index 1b6b6defdf9..00000000000 --- a/source/gameengine/GamePlayer/ghost/GPG_Application.cpp +++ /dev/null @@ -1,998 +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 ***** - * GHOST Blender Player application implementation file. - */ - -/** \file gameengine/GamePlayer/ghost/GPG_Application.cpp - * \ingroup player - */ - - -#ifdef WIN32 -# pragma warning (disable:4786) // suppress stl-MSVC debug info warning -# include -#endif - -#include "GPU_glew.h" -#include "GPU_extensions.h" -#include "GPU_init_exit.h" - -#include "GPG_Application.h" -#include "BL_BlenderDataConversion.h" - -#include -#include -#include - -/********************************** - * Begin Blender include block - **********************************/ -#ifdef __cplusplus -extern "C" -{ -#endif // __cplusplus -#include "BLI_blenlib.h" -#include "BLO_readfile.h" -#include "BKE_global.h" -#include "BKE_main.h" -#include "BKE_sound.h" -#include "IMB_imbuf.h" -#include "DNA_scene_types.h" -#ifdef __cplusplus -} -#endif // __cplusplus -/********************************** - * End Blender include block - **********************************/ - - -#include "BL_System.h" -#include "KX_KetsjiEngine.h" - -// include files needed by "KX_BlenderSceneConverter.h" -#include "CTR_Map.h" -#include "SCA_IActuator.h" -#include "RAS_MeshObject.h" -#include "RAS_OpenGLRasterizer.h" -#include "RAS_ListRasterizer.h" -#include "KX_PythonInit.h" -#include "KX_PyConstraintBinding.h" -#include "BL_Material.h" // MAXTEX - -#include "KX_BlenderSceneConverter.h" -#include "NG_LoopBackNetworkDeviceInterface.h" - -#include "GPC_MouseDevice.h" -#include "GPG_Canvas.h" -#include "GPG_KeyboardDevice.h" -#include "GPG_System.h" - -#include "STR_String.h" - -#include "GHOST_ISystem.h" -#include "GHOST_IEvent.h" -#include "GHOST_IEventConsumer.h" -#include "GHOST_IWindow.h" -#include "GHOST_Rect.h" - -#ifdef WITH_AUDASPACE -# include -#endif - -static void frameTimerProc(GHOST_ITimerTask* task, GHOST_TUns64 time); - -static GHOST_ISystem* fSystem = 0; -static const int kTimerFreq = 10; - -GPG_Application::GPG_Application(GHOST_ISystem* system) - : m_startSceneName(""), - m_startScene(0), - m_maggie(0), - m_kxStartScene(NULL), - m_exitRequested(0), - m_system(system), - m_mainWindow(0), - m_frameTimer(0), - m_cursor(GHOST_kStandardCursorFirstCursor), - m_engineInitialized(0), - m_engineRunning(0), - m_isEmbedded(false), - m_ketsjiengine(0), - m_kxsystem(0), - m_keyboard(0), - m_mouse(0), - m_canvas(0), - m_rasterizer(0), - m_sceneconverter(0), - m_networkdevice(0), - m_blendermat(0), - m_blenderglslmat(0), - m_pyGlobalDictString(0), - m_pyGlobalDictString_Length(0) -{ - fSystem = system; -} - - - -GPG_Application::~GPG_Application(void) -{ - if (m_pyGlobalDictString) { - delete [] m_pyGlobalDictString; - m_pyGlobalDictString = 0; - m_pyGlobalDictString_Length = 0; - } - - exitEngine(); - fSystem->disposeWindow(m_mainWindow); -} - - - -bool GPG_Application::SetGameEngineData(struct Main* maggie, Scene *scene, GlobalSettings *gs, int argc, char **argv) -{ - bool result = false; - - if (maggie != NULL && scene != NULL) - { -// XXX G.scene = scene; - m_maggie = maggie; - m_startSceneName = scene->id.name+2; - m_startScene = scene; - result = true; - } - - /* Python needs these */ - m_argc= argc; - m_argv= argv; - - /* Global Settings */ - m_globalSettings= gs; - - return result; -} - - -#ifdef WIN32 -#define SCR_SAVE_MOUSE_MOVE_THRESHOLD 15 - -static HWND found_ghost_window_hwnd; -static GHOST_IWindow* ghost_window_to_find; -static WNDPROC ghost_wnd_proc; -static POINT scr_save_mouse_pos; - -static LRESULT CALLBACK screenSaverWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - BOOL close = false; - switch (uMsg) - { - case WM_MOUSEMOVE: - { - POINT pt; - GetCursorPos(&pt); - LONG dx = scr_save_mouse_pos.x - pt.x; - LONG dy = scr_save_mouse_pos.y - pt.y; - if (abs(dx) > SCR_SAVE_MOUSE_MOVE_THRESHOLD - || abs(dy) > SCR_SAVE_MOUSE_MOVE_THRESHOLD) - { - close = true; - } - scr_save_mouse_pos = pt; - break; - } - case WM_LBUTTONDOWN: - case WM_MBUTTONDOWN: - case WM_RBUTTONDOWN: - case WM_KEYDOWN: - close = true; - } - if (close) - PostMessage(hwnd,WM_CLOSE,0,0); - return CallWindowProc(ghost_wnd_proc, hwnd, uMsg, wParam, lParam); -} - -BOOL CALLBACK findGhostWindowHWNDProc(HWND hwnd, LPARAM lParam) -{ - GHOST_IWindow *p = (GHOST_IWindow*) GetWindowLongPtr(hwnd, GWLP_USERDATA); - BOOL ret = true; - if (p == ghost_window_to_find) - { - found_ghost_window_hwnd = hwnd; - ret = false; - } - return ret; -} - -static HWND findGhostWindowHWND(GHOST_IWindow* window) -{ - found_ghost_window_hwnd = NULL; - ghost_window_to_find = window; - EnumWindows(findGhostWindowHWNDProc, NULL); - return found_ghost_window_hwnd; -} - -bool GPG_Application::startScreenSaverPreview( - HWND parentWindow, - const bool stereoVisual, - const int stereoMode, - const GHOST_TUns16 samples) -{ - bool success = false; - - RECT rc; - if (GetWindowRect(parentWindow, &rc)) - { - int windowWidth = rc.right - rc.left; - int windowHeight = rc.bottom - rc.top; - STR_String title = ""; - GHOST_GLSettings glSettings = {0}; - - if (stereoVisual) { - glSettings.flags |= GHOST_glStereoVisual; - } - glSettings.numOfAASamples = samples; - - m_mainWindow = fSystem->createWindow(title, 0, 0, windowWidth, windowHeight, GHOST_kWindowStateMinimized, - GHOST_kDrawingContextTypeOpenGL, glSettings); - if (!m_mainWindow) { - printf("error: could not create main window\n"); - exit(-1); - } - - HWND ghost_hwnd = findGhostWindowHWND(m_mainWindow); - if (!ghost_hwnd) { - printf("error: could find main window\n"); - exit(-1); - } - - SetParent(ghost_hwnd, parentWindow); - LONG_PTR style = GetWindowLongPtr(ghost_hwnd, GWL_STYLE); - LONG_PTR exstyle = GetWindowLongPtr(ghost_hwnd, GWL_EXSTYLE); - - RECT adjrc = { 0, 0, windowWidth, windowHeight }; - AdjustWindowRectEx(&adjrc, style, false, exstyle); - - style = (style & (~(WS_POPUP|WS_OVERLAPPEDWINDOW|WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_THICKFRAME|WS_MINIMIZEBOX|WS_MAXIMIZEBOX|WS_TILEDWINDOW ))) | WS_CHILD; - SetWindowLongPtr(ghost_hwnd, GWL_STYLE, style); - SetWindowPos(ghost_hwnd, NULL, adjrc.left, adjrc.top, 0, 0, SWP_NOZORDER|SWP_NOSIZE|SWP_NOACTIVATE); - - /* Check the size of the client rectangle of the window and resize the window - * so that the client rectangle has the size requested. - */ - m_mainWindow->setClientSize(windowWidth, windowHeight); - - success = initEngine(m_mainWindow, stereoMode); - if (success) { - success = startEngine(); - } - - } - return success; -} - -bool GPG_Application::startScreenSaverFullScreen( - int width, - int height, - int bpp,int frequency, - const bool stereoVisual, - const int stereoMode, - const GHOST_TUns16 samples) -{ - bool ret = startFullScreen(width, height, bpp, frequency, stereoVisual, stereoMode, 0, samples); - if (ret) - { - HWND ghost_hwnd = findGhostWindowHWND(m_mainWindow); - if (ghost_hwnd != NULL) - { - GetCursorPos(&scr_save_mouse_pos); - ghost_wnd_proc = (WNDPROC) GetWindowLongPtr(ghost_hwnd, GWLP_WNDPROC); - SetWindowLongPtr(ghost_hwnd,GWLP_WNDPROC, (uintptr_t) screenSaverWindowProc); - } - } - return ret; -} - -#endif - -bool GPG_Application::startWindow( - STR_String& title, - int windowLeft, - int windowTop, - int windowWidth, - int windowHeight, - const bool stereoVisual, - const int stereoMode, - const int alphaBackground, - const GHOST_TUns16 samples) -{ - GHOST_GLSettings glSettings = {0}; - bool success; - // Create the main window - //STR_String title ("Blender Player - GHOST"); - if (stereoVisual) - glSettings.flags |= GHOST_glStereoVisual; - if (alphaBackground) - glSettings.flags |= GHOST_glAlphaBackground; - glSettings.numOfAASamples = samples; - - m_mainWindow = fSystem->createWindow(title, windowLeft, windowTop, windowWidth, windowHeight, GHOST_kWindowStateNormal, - GHOST_kDrawingContextTypeOpenGL, glSettings); - if (!m_mainWindow) { - printf("error: could not create main window\n"); - exit(-1); - } - - /* Check the size of the client rectangle of the window and resize the window - * so that the client rectangle has the size requested. - */ - m_mainWindow->setClientSize(windowWidth, windowHeight); - m_mainWindow->setCursorVisibility(false); - - success = initEngine(m_mainWindow, stereoMode); - if (success) { - success = startEngine(); - } - return success; -} - -bool GPG_Application::startEmbeddedWindow( - STR_String& title, - const GHOST_TEmbedderWindowID parentWindow, - const bool stereoVisual, - const int stereoMode, - const int alphaBackground, - const GHOST_TUns16 samples) -{ - GHOST_TWindowState state = GHOST_kWindowStateNormal; - GHOST_GLSettings glSettings = {0}; - - if (stereoVisual) - glSettings.flags |= GHOST_glStereoVisual; - if (alphaBackground) - glSettings.flags |= GHOST_glAlphaBackground; - glSettings.numOfAASamples = samples; - - if (parentWindow != 0) - state = GHOST_kWindowStateEmbedded; - m_mainWindow = fSystem->createWindow(title, 0, 0, 0, 0, state, - GHOST_kDrawingContextTypeOpenGL, glSettings, parentWindow); - - if (!m_mainWindow) { - printf("error: could not create main window\n"); - exit(-1); - } - m_isEmbedded = true; - - bool success = initEngine(m_mainWindow, stereoMode); - if (success) { - success = startEngine(); - } - return success; -} - - -bool GPG_Application::startFullScreen( - int width, - int height, - int bpp,int frequency, - const bool stereoVisual, - const int stereoMode, - const int alphaBackground, - const GHOST_TUns16 samples, - bool useDesktop) -{ - bool success; - GHOST_TUns32 sysWidth=0, sysHeight=0; - fSystem->getMainDisplayDimensions(sysWidth, sysHeight); - // Create the main window - GHOST_DisplaySetting setting; - setting.xPixels = (useDesktop) ? sysWidth : width; - setting.yPixels = (useDesktop) ? sysHeight : height; - setting.bpp = bpp; - setting.frequency = frequency; - - fSystem->beginFullScreen(setting, &m_mainWindow, stereoVisual, alphaBackground, samples); - m_mainWindow->setCursorVisibility(false); - /* note that X11 ignores this (it uses a window internally for fullscreen) */ - m_mainWindow->setState(GHOST_kWindowStateFullScreen); - - success = initEngine(m_mainWindow, stereoMode); - if (success) { - success = startEngine(); - } - return success; -} - - - - -bool GPG_Application::StartGameEngine(int stereoMode) -{ - bool success = initEngine(m_mainWindow, stereoMode); - - if (success) - success = startEngine(); - - return success; -} - - - -void GPG_Application::StopGameEngine() -{ - exitEngine(); -} - - - -bool GPG_Application::processEvent(GHOST_IEvent* event) -{ - bool handled = true; - - switch (event->getType()) - { - case GHOST_kEventUnknown: - break; - - case GHOST_kEventButtonDown: - handled = handleButton(event, true); - break; - - case GHOST_kEventButtonUp: - handled = handleButton(event, false); - break; - - case GHOST_kEventWheel: - handled = handleWheel(event); - break; - - case GHOST_kEventCursorMove: - handled = handleCursorMove(event); - break; - - case GHOST_kEventKeyDown: - handleKey(event, true); - break; - - case GHOST_kEventKeyUp: - handleKey(event, false); - break; - - - case GHOST_kEventWindowClose: - case GHOST_kEventQuit: - m_exitRequested = KX_EXIT_REQUEST_OUTSIDE; - break; - - case GHOST_kEventWindowActivate: - handled = false; - break; - case GHOST_kEventWindowDeactivate: - handled = false; - break; - - // The player now runs as often as it can (repsecting vsync and fixedtime). - // This allows the player to break 100fps, but this code is being left here - // as reference. (see EngineNextFrame) - //case GHOST_kEventWindowUpdate: - // { - // GHOST_IWindow* window = event->getWindow(); - // if (!m_system->validWindow(window)) break; - // // Update the state of the game engine - // if (m_kxsystem && !m_exitRequested) - // { - // // Proceed to next frame - // window->activateDrawingContext(); - - // // first check if we want to exit - // m_exitRequested = m_ketsjiengine->GetExitCode(); - // - // // kick the engine - // bool renderFrame = m_ketsjiengine->NextFrame(); - // if (renderFrame) - // { - // // render the frame - // m_ketsjiengine->Render(); - // } - // } - // m_exitString = m_ketsjiengine->GetExitString(); - // } - // break; - // - case GHOST_kEventWindowSize: - { - GHOST_IWindow* window = event->getWindow(); - if (!m_system->validWindow(window)) break; - if (m_canvas) { - GHOST_Rect bnds; - window->getClientBounds(bnds); - m_canvas->Resize(bnds.getWidth(), bnds.getHeight()); - m_ketsjiengine->Resize(); - } - } - break; - - default: - handled = false; - break; - } - return handled; -} - - - -int GPG_Application::getExitRequested(void) -{ - return m_exitRequested; -} - - -GlobalSettings* GPG_Application::getGlobalSettings(void) -{ - return m_ketsjiengine->GetGlobalSettings(); -} - - - -const STR_String& GPG_Application::getExitString(void) -{ - return m_exitString; -} - - - -bool GPG_Application::initEngine(GHOST_IWindow* window, const int stereoMode) -{ - if (!m_engineInitialized) - { - GPU_init(); - - // get and set the preferences - SYS_SystemHandle syshandle = SYS_GetSystem(); - if (!syshandle) - return false; - - // SYS_WriteCommandLineInt(syshandle, "fixedtime", 0); - // SYS_WriteCommandLineInt(syshandle, "vertexarrays",1); - GameData *gm= &m_startScene->gm; - bool properties = (SYS_GetCommandLineInt(syshandle, "show_properties", 0) != 0); - bool profile = (SYS_GetCommandLineInt(syshandle, "show_profile", 0) != 0); - - bool showPhysics = (gm->flag & GAME_SHOW_PHYSICS); - SYS_WriteCommandLineInt(syshandle, "show_physics", showPhysics); - - bool fixed_framerate= (SYS_GetCommandLineInt(syshandle, "fixedtime", (gm->flag & GAME_ENABLE_ALL_FRAMES)) != 0); - bool frameRate = (SYS_GetCommandLineInt(syshandle, "show_framerate", 0) != 0); - bool useLists = false; // (SYS_GetCommandLineInt(syshandle, "displaylists", gm->flag & GAME_DISPLAY_LISTS) != 0) && GPU_display_list_support(); - bool nodepwarnings = (SYS_GetCommandLineInt(syshandle, "ignore_deprecation_warnings", 1) != 0); - bool restrictAnimFPS = (gm->flag & GAME_RESTRICT_ANIM_UPDATES) != 0; - - m_blendermat = (SYS_GetCommandLineInt(syshandle, "blender_material", 1) != 0); - m_blenderglslmat = (SYS_GetCommandLineInt(syshandle, "blender_glsl_material", 1) != 0); - - // create the canvas, rasterizer and rendertools - m_canvas = new GPG_Canvas(window); - if (!m_canvas) - return false; - - if (gm->vsync == VSYNC_ADAPTIVE) - m_canvas->SetSwapInterval(-1); - else - m_canvas->SetSwapInterval((gm->vsync == VSYNC_ON) ? 1 : 0); - - m_canvas->Init(); - if (gm->flag & GAME_SHOW_MOUSE) - m_canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL); - - RAS_STORAGE_TYPE raster_storage = RAS_AUTO_STORAGE; - - if (gm->raster_storage == RAS_STORE_VBO) { - raster_storage = RAS_VBO; - } - else if (gm->raster_storage == RAS_STORE_VA) { - raster_storage = RAS_VA; - } - //Don't use displaylists with VBOs - //If auto starts using VBOs, make sure to check for that here - if (useLists && raster_storage != RAS_VBO) - m_rasterizer = new RAS_ListRasterizer(m_canvas, true, raster_storage); - else - m_rasterizer = new RAS_OpenGLRasterizer(m_canvas, raster_storage); - - /* Stereo parameters - Eye Separation from the UI - stereomode from the command-line/UI */ - m_rasterizer->SetStereoMode((RAS_IRasterizer::StereoMode) stereoMode); - m_rasterizer->SetEyeSeparation(m_startScene->gm.eyeseparation); - - if (!m_rasterizer) - goto initFailed; - - m_rasterizer->PrintHardwareInfo(); - - // create the inputdevices - m_keyboard = new GPG_KeyboardDevice(); - if (!m_keyboard) - goto initFailed; - - m_mouse = new GPC_MouseDevice(); - if (!m_mouse) - goto initFailed; - - // create a networkdevice - m_networkdevice = new NG_LoopBackNetworkDeviceInterface(); - if (!m_networkdevice) - goto initFailed; - - BKE_sound_init(m_maggie); - - // create a ketsjisystem (only needed for timing and stuff) - m_kxsystem = new GPG_System (m_system); - if (!m_kxsystem) - goto initFailed; - - // create the ketsjiengine - m_ketsjiengine = new KX_KetsjiEngine(m_kxsystem); - - // set the devices - m_ketsjiengine->SetKeyboardDevice(m_keyboard); - m_ketsjiengine->SetMouseDevice(m_mouse); - m_ketsjiengine->SetNetworkDevice(m_networkdevice); - m_ketsjiengine->SetCanvas(m_canvas); - m_ketsjiengine->SetRasterizer(m_rasterizer); - - KX_KetsjiEngine::SetExitKey(ConvertKeyCode(gm->exitkey)); -#ifdef WITH_PYTHON - CValue::SetDeprecationWarnings(nodepwarnings); -#else - (void)nodepwarnings; -#endif - - m_ketsjiengine->SetUseFixedTime(fixed_framerate); - m_ketsjiengine->SetTimingDisplay(frameRate, profile, properties); - m_ketsjiengine->SetRestrictAnimationFPS(restrictAnimFPS); - - //set the global settings (carried over if restart/load new files) - m_ketsjiengine->SetGlobalSettings(m_globalSettings); - m_ketsjiengine->SetRender(true); - - m_engineInitialized = true; - } - - return m_engineInitialized; -initFailed: - BKE_sound_exit(); - delete m_kxsystem; - delete m_networkdevice; - delete m_mouse; - delete m_keyboard; - delete m_rasterizer; - delete m_canvas; - m_canvas = NULL; - m_rasterizer = NULL; - m_keyboard = NULL; - m_mouse = NULL; - m_networkdevice = NULL; - m_kxsystem = NULL; - return false; -} - - - -bool GPG_Application::startEngine(void) -{ - if (m_engineRunning) { - return false; - } - - // Temporary hack to disable banner display for NaN approved content. - /* - m_canvas->SetBannerDisplayEnabled(true); - Camera* cam; - cam = (Camera*)scene->camera->data; - if (cam) { - if (((cam->flag) & 48)==48) { - m_canvas->SetBannerDisplayEnabled(false); - } - } - else { - showError(CString("Camera data invalid.")); - return false; - } - */ - - // create a scene converter, create and convert the stratingscene - m_sceneconverter = new KX_BlenderSceneConverter(m_maggie, m_ketsjiengine); - if (m_sceneconverter) - { - STR_String m_kxStartScenename = m_startSceneName.Ptr(); - m_ketsjiengine->SetSceneConverter(m_sceneconverter); - - // if (always_use_expand_framing) - // sceneconverter->SetAlwaysUseExpandFraming(true); - if (m_blendermat) - m_sceneconverter->SetMaterials(true); - if (m_blenderglslmat && (m_globalSettings->matmode == GAME_MAT_GLSL)) - m_sceneconverter->SetGLSLMaterials(true); - if (m_startScene->gm.flag & GAME_NO_MATERIAL_CACHING) - m_sceneconverter->SetCacheMaterials(false); - - m_kxStartScene = new KX_Scene(m_keyboard, - m_mouse, - m_networkdevice, - m_kxStartScenename, - m_startScene, - m_canvas); - -#ifdef WITH_PYTHON - // some python things - PyObject *gameLogic, *gameLogic_keys; - setupGamePython(m_ketsjiengine, m_kxStartScene, m_maggie, NULL, &gameLogic, &gameLogic_keys, m_argc, m_argv); -#endif // WITH_PYTHON - - //initialize Dome Settings - if (m_startScene->gm.stereoflag == STEREO_DOME) - m_ketsjiengine->InitDome(m_startScene->gm.dome.res, m_startScene->gm.dome.mode, m_startScene->gm.dome.angle, m_startScene->gm.dome.resbuf, m_startScene->gm.dome.tilt, m_startScene->gm.dome.warptext); - - // initialize 3D Audio Settings - AUD_Device* device = BKE_sound_get_device(); - AUD_Device_setSpeedOfSound(device, m_startScene->audio.speed_of_sound); - AUD_Device_setDopplerFactor(device, m_startScene->audio.doppler_factor); - AUD_Device_setDistanceModel(device, AUD_DistanceModel(m_startScene->audio.distance_model)); - -#ifdef WITH_PYTHON - // Set the GameLogic.globalDict from marshal'd data, so we can - // load new blend files and keep data in GameLogic.globalDict - loadGamePythonConfig(m_pyGlobalDictString, m_pyGlobalDictString_Length); -#endif - m_sceneconverter->ConvertScene( - m_kxStartScene, - m_rasterizer, - m_canvas); - m_ketsjiengine->AddScene(m_kxStartScene); - - // Create a timer that is used to kick the engine - if (!m_frameTimer) { - m_frameTimer = m_system->installTimer(0, kTimerFreq, frameTimerProc, m_mainWindow); - } - m_rasterizer->Init(); - m_ketsjiengine->StartEngine(true); - m_engineRunning = true; - - // Set the animation playback rate for ipo's and actions - // the framerate below should patch with FPS macro defined in blendef.h - // Could be in StartEngine set the framerate, we need the scene to do this - Scene *scene= m_kxStartScene->GetBlenderScene(); // needed for macro - m_ketsjiengine->SetAnimFrameRate(FPS); - } - - if (!m_engineRunning) - { - stopEngine(); - } - - return m_engineRunning; -} - - -void GPG_Application::stopEngine() -{ -#ifdef WITH_PYTHON - // GameLogic.globalDict gets converted into a buffer, and sorted in - // m_pyGlobalDictString so we can restore after python has stopped - // and started between .blend file loads. - if (m_pyGlobalDictString) { - delete [] m_pyGlobalDictString; - m_pyGlobalDictString = 0; - } - - m_pyGlobalDictString_Length = saveGamePythonConfig(&m_pyGlobalDictString); -#endif - - m_ketsjiengine->StopEngine(); - m_networkdevice->Disconnect(); - - if (m_sceneconverter) { - delete m_sceneconverter; - m_sceneconverter = 0; - } - if (m_system && m_frameTimer) { - m_system->removeTimer(m_frameTimer); - m_frameTimer = 0; - } - - m_engineRunning = false; -} - -void GPG_Application::EngineNextFrame() -{ - // Update the state of the game engine - if (m_kxsystem && !m_exitRequested) - { - // Proceed to next frame - if (m_mainWindow) - m_mainWindow->activateDrawingContext(); - - // first check if we want to exit - m_exitRequested = m_ketsjiengine->GetExitCode(); - - // kick the engine - bool renderFrame = m_ketsjiengine->NextFrame(); - if (renderFrame && m_mainWindow) - { - // render the frame - m_ketsjiengine->Render(); - } - } - m_exitString = m_ketsjiengine->GetExitString(); -} - -void GPG_Application::exitEngine() -{ - // We only want to kill the engine if it has been initialized - if (!m_engineInitialized) - return; - - BKE_sound_exit(); - if (m_ketsjiengine) - { - stopEngine(); - delete m_ketsjiengine; - m_ketsjiengine = 0; - } - if (m_kxsystem) - { - delete m_kxsystem; - m_kxsystem = 0; - } - if (m_networkdevice) - { - delete m_networkdevice; - m_networkdevice = 0; - } - if (m_mouse) - { - delete m_mouse; - m_mouse = 0; - } - if (m_keyboard) - { - delete m_keyboard; - m_keyboard = 0; - } - if (m_rasterizer) - { - delete m_rasterizer; - m_rasterizer = 0; - } - if (m_canvas) - { - delete m_canvas; - m_canvas = 0; - } - - GPU_exit(); - -#ifdef WITH_PYTHON - // Call this after we're sure nothing needs Python anymore (e.g., destructors) - exitGamePlayerPythonScripting(); -#endif - - m_exitRequested = 0; - m_engineInitialized = false; -} - -bool GPG_Application::handleWheel(GHOST_IEvent* event) -{ - bool handled = false; - MT_assert(event); - if (m_mouse) - { - GHOST_TEventDataPtr eventData = ((GHOST_IEvent*)event)->getData(); - GHOST_TEventWheelData* wheelData = static_cast(eventData); - GPC_MouseDevice::TButtonId button; - if (wheelData->z > 0) - button = GPC_MouseDevice::buttonWheelUp; - else - button = GPC_MouseDevice::buttonWheelDown; - m_mouse->ConvertButtonEvent(button, true); - handled = true; - } - return handled; -} - -bool GPG_Application::handleButton(GHOST_IEvent* event, bool isDown) -{ - bool handled = false; - MT_assert(event); - if (m_mouse) - { - GHOST_TEventDataPtr eventData = ((GHOST_IEvent*)event)->getData(); - GHOST_TEventButtonData* buttonData = static_cast(eventData); - GPC_MouseDevice::TButtonId button; - switch (buttonData->button) - { - case GHOST_kButtonMaskMiddle: - button = GPC_MouseDevice::buttonMiddle; - break; - case GHOST_kButtonMaskRight: - button = GPC_MouseDevice::buttonRight; - break; - case GHOST_kButtonMaskLeft: - default: - button = GPC_MouseDevice::buttonLeft; - break; - } - m_mouse->ConvertButtonEvent(button, isDown); - handled = true; - } - return handled; -} - - -bool GPG_Application::handleCursorMove(GHOST_IEvent* event) -{ - bool handled = false; - MT_assert(event); - if (m_mouse && m_mainWindow) - { - GHOST_TEventDataPtr eventData = ((GHOST_IEvent*)event)->getData(); - GHOST_TEventCursorData* cursorData = static_cast(eventData); - GHOST_TInt32 x, y; - m_mainWindow->screenToClient(cursorData->x, cursorData->y, x, y); - m_mouse->ConvertMoveEvent(x, y); - handled = true; - } - return handled; -} - - -bool GPG_Application::handleKey(GHOST_IEvent* event, bool isDown) -{ - bool handled = false; - MT_assert(event); - if (m_keyboard) - { - GHOST_TEventDataPtr eventData = ((GHOST_IEvent*)event)->getData(); - GHOST_TEventKeyData* keyData = static_cast(eventData); - unsigned int unicode = keyData->utf8_buf[0] ? BLI_str_utf8_as_unicode(keyData->utf8_buf) : keyData->ascii; - - if (m_keyboard->ToNative(keyData->key) == KX_KetsjiEngine::GetExitKey() && !m_keyboard->m_hookesc && !m_isEmbedded) { - m_exitRequested = KX_EXIT_REQUEST_OUTSIDE; - } - m_keyboard->ConvertEvent(keyData->key, isDown, unicode); - handled = true; - } - return handled; -} - - - -static void frameTimerProc(GHOST_ITimerTask* task, GHOST_TUns64 time) -{ - GHOST_IWindow* window = (GHOST_IWindow*)task->getUserData(); - if (fSystem->validWindow(window)) { - window->invalidate(); - } -} diff --git a/source/gameengine/GamePlayer/ghost/GPG_Application.h b/source/gameengine/GamePlayer/ghost/GPG_Application.h deleted file mode 100644 index e757cc10e32..00000000000 --- a/source/gameengine/GamePlayer/ghost/GPG_Application.h +++ /dev/null @@ -1,181 +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 GPG_Application.h - * \ingroup player - * \brief GHOST Blender Player application declaration file. - */ - -#include "GHOST_IEventConsumer.h" -#include "STR_String.h" - -#ifdef WIN32 -#include -#endif - -#include "KX_KetsjiEngine.h" - -class KX_KetsjiEngine; -class KX_Scene; -class KX_ISceneConverter; -class NG_LoopBackNetworkDeviceInterface; -class RAS_IRasterizer; -class GHOST_IEvent; -class GHOST_ISystem; -class GHOST_ITimerTask; -class GHOST_IWindow; -class GPC_MouseDevice; -class GPG_Canvas; -class GPG_KeyboardDevice; -class GPG_System; -struct Main; -struct Scene; - -class GPG_Application : public GHOST_IEventConsumer -{ -public: - GPG_Application(GHOST_ISystem* system); - ~GPG_Application(void); - - bool SetGameEngineData(struct Main* maggie, struct Scene* scene, GlobalSettings* gs, int argc, char** argv); - bool startWindow(STR_String& title, - int windowLeft, int windowTop, - int windowWidth, int windowHeight, - const bool stereoVisual, const int stereoMode, const int alphaBackground=0, const GHOST_TUns16 samples=0); - bool startFullScreen(int width, int height, - int bpp, int frequency, - const bool stereoVisual, const int stereoMode, const int alphaBackground = 0, - const GHOST_TUns16 samples=0, bool useDesktop=false); - bool startEmbeddedWindow(STR_String& title, const GHOST_TEmbedderWindowID parent_window, - const bool stereoVisual, const int stereoMode, const int alphaBackground=0, const GHOST_TUns16 samples=0); -#ifdef WIN32 - bool startScreenSaverFullScreen(int width, int height, - int bpp, int frequency, - const bool stereoVisual, const int stereoMode, const GHOST_TUns16 samples=0); - bool startScreenSaverPreview(HWND parentWindow, - const bool stereoVisual, const int stereoMode, const GHOST_TUns16 samples=0); -#endif - - virtual bool processEvent(GHOST_IEvent* event); - int getExitRequested(void); - const STR_String& getExitString(void); - GlobalSettings* getGlobalSettings(void); - - inline KX_Scene *GetStartScene() const - { - return m_kxStartScene; - } - - bool StartGameEngine(int stereoMode); - void StopGameEngine(); - void EngineNextFrame(); - -protected: - bool handleWheel(GHOST_IEvent* event); - bool handleButton(GHOST_IEvent* event, bool isDown); - bool handleCursorMove(GHOST_IEvent* event); - bool handleKey(GHOST_IEvent* event, bool isDown); - - /** - * Initializes the game engine. - */ - bool initEngine(GHOST_IWindow* window, int stereoMode); - - /** - * Starts the game engine. - */ - bool startEngine(void); - - /** - * Stop the game engine. - */ - void stopEngine(void); - - /** - * Shuts the game engine down. - */ - void exitEngine(void); - short m_exitkey; - - /* The game data */ - STR_String m_startSceneName; - struct Scene* m_startScene; - struct Main* m_maggie; - KX_Scene *m_kxStartScene; - - /* Exit state. */ - int m_exitRequested; - STR_String m_exitString; - GlobalSettings* m_globalSettings; - - /* GHOST system abstraction. */ - GHOST_ISystem* m_system; - /* Main window. */ - GHOST_IWindow* m_mainWindow; - /* Timer to advance frames. */ - GHOST_ITimerTask* m_frameTimer; - /* The cursor shape displayed. */ - GHOST_TStandardCursor m_cursor; - - /** Engine construction state. */ - bool m_engineInitialized; - /** Engine state. */ - bool m_engineRunning; - /** Running on embedded window */ - bool m_isEmbedded; - - /** the gameengine itself */ - KX_KetsjiEngine* m_ketsjiengine; - /** The game engine's system abstraction. */ - GPG_System* m_kxsystem; - /** The game engine's keyboard abstraction. */ - GPG_KeyboardDevice* m_keyboard; - /** The game engine's mouse abstraction. */ - GPC_MouseDevice* m_mouse; - /** The game engine's canvas abstraction. */ - GPG_Canvas* m_canvas; - /** the rasterizer */ - RAS_IRasterizer* m_rasterizer; - /** Converts Blender data files. */ - KX_ISceneConverter* m_sceneconverter; - /** Network interface. */ - NG_LoopBackNetworkDeviceInterface* m_networkdevice; - - bool m_blendermat; - bool m_blenderglslmat; - - /* - * GameLogic.globalDict as a string so that loading new blend files can use the same dict. - * Do this because python starts/stops when loading blend files. - */ - char* m_pyGlobalDictString; - int m_pyGlobalDictString_Length; - - /* argc and argv need to be passed on to python */ - int m_argc; - char** m_argv; -}; diff --git a/source/gameengine/GamePlayer/ghost/GPG_Canvas.cpp b/source/gameengine/GamePlayer/ghost/GPG_Canvas.cpp deleted file mode 100644 index 09eb1691dae..00000000000 --- a/source/gameengine/GamePlayer/ghost/GPG_Canvas.cpp +++ /dev/null @@ -1,177 +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/GamePlayer/ghost/GPG_Canvas.cpp - * \ingroup player - */ - - -#include "GPG_Canvas.h" -#include -#include "GHOST_ISystem.h" - -GPG_Canvas::GPG_Canvas(GHOST_IWindow* window) -: GPC_Canvas(0, 0), m_window(window) -{ - if (m_window) - { - GHOST_Rect bnds; - m_window->getClientBounds(bnds); - this->Resize(bnds.getWidth(), bnds.getHeight()); - } -} - - -GPG_Canvas::~GPG_Canvas(void) -{ -} - - -void GPG_Canvas::Init() -{ - if (m_window) - { - m_window->setDrawingContextType(GHOST_kDrawingContextTypeOpenGL); - assert(m_window->getDrawingContextType() == GHOST_kDrawingContextTypeOpenGL); - } -} - -void GPG_Canvas::SetMousePosition(int x, int y) -{ - GHOST_ISystem* system = GHOST_ISystem::getSystem(); - if (system && m_window) - { - GHOST_TInt32 gx = (GHOST_TInt32)x; - GHOST_TInt32 gy = (GHOST_TInt32)y; - GHOST_TInt32 cx; - GHOST_TInt32 cy; - m_window->clientToScreen(gx, gy, cx, cy); - system->setCursorPosition(cx, cy); - } -} - - -void GPG_Canvas::SetMouseState(RAS_MouseState mousestate) -{ - m_mousestate = mousestate; - - if (m_window) - { - switch (mousestate) - { - case MOUSE_INVISIBLE: - m_window->setCursorVisibility(false); - break; - case MOUSE_WAIT: - m_window->setCursorShape(GHOST_kStandardCursorWait); - m_window->setCursorVisibility(true); - break; - case MOUSE_NORMAL: - m_window->setCursorShape(GHOST_kStandardCursorDefault); - m_window->setCursorVisibility(true); - break; - } - } -} - - -void GPG_Canvas::SwapBuffers() -{ - if (m_window) - { - m_window->swapBuffers(); - } -} - -void GPG_Canvas::SetSwapInterval(int interval) -{ - if (m_window) - m_window->setSwapInterval(interval); -} - -bool GPG_Canvas::GetSwapInterval(int& intervalOut) -{ - if (m_window) - return (bool)m_window->getSwapInterval(intervalOut); - - return false; -} - -void GPG_Canvas::GetDisplayDimensions(int &width, int &height) - { - unsigned int uiwidth; - unsigned int uiheight; - - GHOST_ISystem *system = GHOST_ISystem::getSystem(); - system->getMainDisplayDimensions(uiwidth, uiheight); - - width = uiwidth; - height = uiheight; -} - -void GPG_Canvas::ResizeWindow(int width, int height) -{ - if (m_window->getState() == GHOST_kWindowStateFullScreen) - { - GHOST_ISystem* system = GHOST_ISystem::getSystem(); - GHOST_DisplaySetting setting; - setting.xPixels = width; - setting.yPixels = height; - //XXX allow these to be changed or kept from previous state - setting.bpp = 32; - setting.frequency = 60; - - system->updateFullScreen(setting, &m_window); - } - - m_window->setClientSize(width, height); - - Resize(width, height); -} - -void GPG_Canvas::SetFullScreen(bool enable) -{ - if (enable) - m_window->setState(GHOST_kWindowStateFullScreen); - else - m_window->setState(GHOST_kWindowStateNormal); -} - -bool GPG_Canvas::GetFullScreen() -{ - return m_window->getState() == GHOST_kWindowStateFullScreen; -} - -float GPG_Canvas::GetMouseNormalizedX(int x) -{ - return float(x)/this->GetWidth(); -} - -float GPG_Canvas::GetMouseNormalizedY(int y) -{ - return float(y)/this->GetHeight(); -} diff --git a/source/gameengine/GamePlayer/ghost/GPG_Canvas.h b/source/gameengine/GamePlayer/ghost/GPG_Canvas.h deleted file mode 100644 index 18afbf6cd9e..00000000000 --- a/source/gameengine/GamePlayer/ghost/GPG_Canvas.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): none yet. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file GPG_Canvas.h - * \ingroup player - */ - -#ifndef __GPG_CANVAS_H__ -#define __GPG_CANVAS_H__ - -#ifdef WIN32 -#pragma warning (disable:4786) -#endif /* WIN32 */ - -#include "GPC_Canvas.h" - -#include "GHOST_IWindow.h" - - -class GPG_Canvas : public GPC_Canvas -{ -protected: - /** GHOST window. */ - GHOST_IWindow* m_window; - -public: - GPG_Canvas(GHOST_IWindow* window); - virtual ~GPG_Canvas(void); - - virtual void Init(void); - virtual void SetMousePosition(int x, int y); - virtual void SetMouseState(RAS_MouseState mousestate); - virtual void SwapBuffers(); - virtual void SetSwapInterval(int interval); - virtual bool GetSwapInterval(int& intervalOut); - - virtual int GetMouseX(int x) { return x; } - virtual int GetMouseY(int y) { return y; } - virtual float GetMouseNormalizedX(int x); - virtual float GetMouseNormalizedY(int y); - - virtual void GetDisplayDimensions(int &width, int &height); - - virtual void ResizeWindow(int width, int height); - virtual void SetFullScreen(bool enable); - virtual bool GetFullScreen(); - - bool BeginDraw() { return true; } - void EndDraw() {}; -}; - -#endif /* __GPG_CANVAS_H__ */ diff --git a/source/gameengine/GamePlayer/ghost/GPG_KeyboardDevice.cpp b/source/gameengine/GamePlayer/ghost/GPG_KeyboardDevice.cpp deleted file mode 100644 index eefaa3730cf..00000000000 --- a/source/gameengine/GamePlayer/ghost/GPG_KeyboardDevice.cpp +++ /dev/null @@ -1,165 +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 ***** - * GHOST Blender Player keyboard device implementation. - */ - -/** \file gameengine/GamePlayer/ghost/GPG_KeyboardDevice.cpp - * \ingroup player - */ - - -#include "GPG_KeyboardDevice.h" - -GPG_KeyboardDevice::GPG_KeyboardDevice(void) -{ - m_reverseKeyTranslateTable[GHOST_kKeyA ] = KX_AKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyB ] = KX_BKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyC ] = KX_CKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyD ] = KX_DKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyE ] = KX_EKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyF ] = KX_FKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyG ] = KX_GKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyH ] = KX_HKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyI ] = KX_IKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyJ ] = KX_JKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyK ] = KX_KKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyL ] = KX_LKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyM ] = KX_MKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyN ] = KX_NKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyO ] = KX_OKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyP ] = KX_PKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyQ ] = KX_QKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyR ] = KX_RKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyS ] = KX_SKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyT ] = KX_TKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyU ] = KX_UKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyV ] = KX_VKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyW ] = KX_WKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyX ] = KX_XKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyY ] = KX_YKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyZ ] = KX_ZKEY ; - - m_reverseKeyTranslateTable[GHOST_kKey0 ] = KX_ZEROKEY ; - m_reverseKeyTranslateTable[GHOST_kKey1 ] = KX_ONEKEY ; - m_reverseKeyTranslateTable[GHOST_kKey2 ] = KX_TWOKEY ; - m_reverseKeyTranslateTable[GHOST_kKey3 ] = KX_THREEKEY ; - m_reverseKeyTranslateTable[GHOST_kKey4 ] = KX_FOURKEY ; - m_reverseKeyTranslateTable[GHOST_kKey5 ] = KX_FIVEKEY ; - m_reverseKeyTranslateTable[GHOST_kKey6 ] = KX_SIXKEY ; - m_reverseKeyTranslateTable[GHOST_kKey7 ] = KX_SEVENKEY ; - m_reverseKeyTranslateTable[GHOST_kKey8 ] = KX_EIGHTKEY ; - m_reverseKeyTranslateTable[GHOST_kKey9 ] = KX_NINEKEY ; - - // Middle keyboard area keys - m_reverseKeyTranslateTable[GHOST_kKeyPause ] = KX_PAUSEKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyInsert ] = KX_INSERTKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyDelete ] = KX_DELKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyHome ] = KX_HOMEKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyEnd ] = KX_ENDKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyUpPage ] = KX_PAGEUPKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyDownPage ] = KX_PAGEDOWNKEY ; - - // Arrow keys - m_reverseKeyTranslateTable[GHOST_kKeyUpArrow ] = KX_UPARROWKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyDownArrow ] = KX_DOWNARROWKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyLeftArrow ] = KX_LEFTARROWKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyRightArrow ] = KX_RIGHTARROWKEY ; - - // Function keys - m_reverseKeyTranslateTable[GHOST_kKeyF1 ] = KX_F1KEY ; - m_reverseKeyTranslateTable[GHOST_kKeyF2 ] = KX_F2KEY ; - m_reverseKeyTranslateTable[GHOST_kKeyF3 ] = KX_F3KEY ; - m_reverseKeyTranslateTable[GHOST_kKeyF4 ] = KX_F4KEY ; - m_reverseKeyTranslateTable[GHOST_kKeyF5 ] = KX_F5KEY ; - m_reverseKeyTranslateTable[GHOST_kKeyF6 ] = KX_F6KEY ; - m_reverseKeyTranslateTable[GHOST_kKeyF7 ] = KX_F7KEY ; - m_reverseKeyTranslateTable[GHOST_kKeyF8 ] = KX_F8KEY ; - m_reverseKeyTranslateTable[GHOST_kKeyF9 ] = KX_F9KEY ; - m_reverseKeyTranslateTable[GHOST_kKeyF10 ] = KX_F10KEY ; - m_reverseKeyTranslateTable[GHOST_kKeyF11 ] = KX_F11KEY ; - m_reverseKeyTranslateTable[GHOST_kKeyF12 ] = KX_F12KEY ; - m_reverseKeyTranslateTable[GHOST_kKeyF13 ] = KX_F13KEY ; - m_reverseKeyTranslateTable[GHOST_kKeyF14 ] = KX_F14KEY ; - m_reverseKeyTranslateTable[GHOST_kKeyF15 ] = KX_F15KEY ; - m_reverseKeyTranslateTable[GHOST_kKeyF16 ] = KX_F16KEY ; - m_reverseKeyTranslateTable[GHOST_kKeyF17 ] = KX_F17KEY ; - m_reverseKeyTranslateTable[GHOST_kKeyF18 ] = KX_F18KEY ; - m_reverseKeyTranslateTable[GHOST_kKeyF19 ] = KX_F19KEY ; - - - // Numpad keys - m_reverseKeyTranslateTable[GHOST_kKeyNumpad0 ] = KX_PAD0 ; - m_reverseKeyTranslateTable[GHOST_kKeyNumpad1 ] = KX_PAD1 ; - m_reverseKeyTranslateTable[GHOST_kKeyNumpad2 ] = KX_PAD2 ; - m_reverseKeyTranslateTable[GHOST_kKeyNumpad3 ] = KX_PAD3 ; - m_reverseKeyTranslateTable[GHOST_kKeyNumpad4 ] = KX_PAD4 ; - m_reverseKeyTranslateTable[GHOST_kKeyNumpad5 ] = KX_PAD5 ; - m_reverseKeyTranslateTable[GHOST_kKeyNumpad6 ] = KX_PAD6 ; - m_reverseKeyTranslateTable[GHOST_kKeyNumpad7 ] = KX_PAD7 ; - m_reverseKeyTranslateTable[GHOST_kKeyNumpad8 ] = KX_PAD8 ; - m_reverseKeyTranslateTable[GHOST_kKeyNumpad9 ] = KX_PAD9 ; - m_reverseKeyTranslateTable[GHOST_kKeyNumpadAsterisk ] = KX_PADASTERKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyNumpadPlus ] = KX_PADPLUSKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyNumpadPeriod ] = KX_PADPERIOD ; - m_reverseKeyTranslateTable[GHOST_kKeyNumpadMinus ] = KX_PADMINUS ; - m_reverseKeyTranslateTable[GHOST_kKeyNumpadSlash ] = KX_PADSLASHKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyNumpadEnter ] = KX_PADENTER ; - - // Other keys - m_reverseKeyTranslateTable[GHOST_kKeyCapsLock ] = KX_CAPSLOCKKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyEsc ] = KX_ESCKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyTab ] = KX_TABKEY ; - m_reverseKeyTranslateTable[GHOST_kKeySpace ] = KX_SPACEKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyEnter ] = KX_RETKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyBackSpace ] = KX_BACKSPACEKEY ; - m_reverseKeyTranslateTable[GHOST_kKeySemicolon ] = KX_SEMICOLONKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyPeriod ] = KX_PERIODKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyComma ] = KX_COMMAKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyQuote ] = KX_QUOTEKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyAccentGrave ] = KX_ACCENTGRAVEKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyMinus ] = KX_MINUSKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyPlus ] = KX_PLUSKEY ; - m_reverseKeyTranslateTable[GHOST_kKeySlash ] = KX_SLASHKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyBackslash ] = KX_BACKSLASHKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyEqual ] = KX_EQUALKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyLeftBracket ] = KX_LEFTBRACKETKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyRightBracket ] = KX_RIGHTBRACKETKEY ; - - m_reverseKeyTranslateTable[GHOST_kKeyOS ] = KX_OSKEY ; - - // Modifier keys. - m_reverseKeyTranslateTable[GHOST_kKeyLeftControl ] = KX_LEFTCTRLKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyRightControl ] = KX_RIGHTCTRLKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyLeftAlt ] = KX_LEFTALTKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyRightAlt ] = KX_RIGHTALTKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyLeftShift ] = KX_LEFTSHIFTKEY ; - m_reverseKeyTranslateTable[GHOST_kKeyRightShift ] = KX_RIGHTSHIFTKEY ; -} - - -GPG_KeyboardDevice::~GPG_KeyboardDevice(void) -{ -} diff --git a/source/gameengine/GamePlayer/ghost/GPG_KeyboardDevice.h b/source/gameengine/GamePlayer/ghost/GPG_KeyboardDevice.h deleted file mode 100644 index ff8d56db40a..00000000000 --- a/source/gameengine/GamePlayer/ghost/GPG_KeyboardDevice.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 GPG_KeyboardDevice.h - * \ingroup player - * \brief GHOST Blender Player keyboard device. - */ - -#ifndef __GPG_KEYBOARDDEVICE_H__ -#define __GPG_KEYBOARDDEVICE_H__ - -#ifdef WIN32 -#pragma warning (disable:4786) -#endif /* WIN32 */ - -#include "GHOST_Types.h" -#include "GPC_KeyboardDevice.h" - -/** - * GHOST implementation of GPC_KeyboardDevice. - * The contructor fills the keyboard code translation map. - * Base class GPC_KeyboardDevice does the rest. - * \see SCA_IInputDevice - */ -class GPG_KeyboardDevice : public GPC_KeyboardDevice -{ -public: - GPG_KeyboardDevice(void); - virtual ~GPG_KeyboardDevice(void); -}; - -#endif /* __GPG_KEYBOARDDEVICE_H__ */ diff --git a/source/gameengine/GamePlayer/ghost/GPG_System.cpp b/source/gameengine/GamePlayer/ghost/GPG_System.cpp deleted file mode 100644 index 669ab0532d9..00000000000 --- a/source/gameengine/GamePlayer/ghost/GPG_System.cpp +++ /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 ***** - * Blender Player system on GHOST. - */ - -/** \file gameengine/GamePlayer/ghost/GPG_System.cpp - * \ingroup player - */ - - -#include "GPG_System.h" -#include -#include "GHOST_ISystem.h" - -GPG_System::GPG_System(GHOST_ISystem* system) -: m_system(system) -{ - assert(m_system); -} - - -double GPG_System::GetTimeInSeconds() -{ - GHOST_TInt64 millis = (GHOST_TInt64)m_system->getMilliSeconds(); - double time = (double)millis; - time /= 1000.0; - return time; -} - - diff --git a/source/gameengine/GamePlayer/ghost/GPG_System.h b/source/gameengine/GamePlayer/ghost/GPG_System.h deleted file mode 100644 index 1ec7a06d1cf..00000000000 --- a/source/gameengine/GamePlayer/ghost/GPG_System.h +++ /dev/null @@ -1,54 +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 GPG_System.h - * \ingroup player - * \brief Blender Player system on GHOST. - */ - -#ifndef __GPG_SYSTEM_H__ -#define __GPG_SYSTEM_H__ - -#ifdef WIN32 -#pragma warning (disable:4786) // suppress stl-MSVC debug info warning -#endif /* WIN32 */ - -#include "KX_ISystem.h" - -class GHOST_ISystem; - -class GPG_System : public KX_ISystem -{ - GHOST_ISystem* m_system; - -public: - GPG_System(GHOST_ISystem* system); - - virtual double GetTimeInSeconds(); -}; - -#endif /* __GPG_SYSTEM_H__ */ diff --git a/source/gameengine/GamePlayer/ghost/GPG_ghost.cpp b/source/gameengine/GamePlayer/ghost/GPG_ghost.cpp deleted file mode 100644 index 998058193bb..00000000000 --- a/source/gameengine/GamePlayer/ghost/GPG_ghost.cpp +++ /dev/null @@ -1,1228 +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 ***** - * Start up of the Blender Player on GHOST. - */ - -/** \file gameengine/GamePlayer/ghost/GPG_ghost.cpp - * \ingroup player - */ - - -#include -#include - -#ifdef __linux__ -#ifdef __alpha__ -#include -#endif /* __alpha__ */ -#endif /* __linux__ */ - -#include "KX_KetsjiEngine.h" -#include "KX_PythonInit.h" -#include "KX_PythonMain.h" -#include "KX_PyConstraintBinding.h" // for PHY_SetActiveEnvironment - -/********************************** - * Begin Blender include block - **********************************/ -#ifdef __cplusplus -extern "C" -{ -#endif // __cplusplus -#include "MEM_guardedalloc.h" -#include "MEM_CacheLimiterC-Api.h" - -#include "BLI_threads.h" -#include "BLI_mempool.h" -#include "BLI_blenlib.h" - -#include "DNA_scene_types.h" -#include "DNA_userdef_types.h" -#include "DNA_genfile.h" - -#include "BLO_readfile.h" -#include "BLO_runtime.h" - -#include "BKE_appdir.h" -#include "BKE_blender.h" -#include "BKE_global.h" -#include "BKE_icons.h" -#include "BKE_image.h" -#include "BKE_node.h" -#include "BKE_report.h" -#include "BKE_library.h" -#include "BKE_library_remap.h" -#include "BKE_modifier.h" -#include "BKE_material.h" -#include "BKE_text.h" -#include "BKE_sound.h" - -#include "DEG_depsgraph.h" - -#include "IMB_imbuf.h" -#include "IMB_moviecache.h" - -#ifdef __APPLE__ - int GHOST_HACK_getFirstFile(char buf[]); -#endif - -// For BLF -#include "BLF_api.h" -#include "BLT_translation.h" -#include "BLT_lang.h" -extern int datatoc_bfont_ttf_size; -extern char datatoc_bfont_ttf[]; -extern int datatoc_bmonofont_ttf_size; -extern char datatoc_bmonofont_ttf[]; - -#ifdef __cplusplus -} -#endif // __cplusplus - -#include "GPU_draw.h" - -/********************************** - * End Blender include block - **********************************/ - -#include "BL_System.h" -#include "GPG_Application.h" - -#include "GHOST_ISystem.h" -#include "RAS_IRasterizer.h" - -#include "BKE_main.h" - -#include "RNA_define.h" - -#ifdef WIN32 -# include -# if !defined(DEBUG) -# include -# endif // !defined(DEBUG) -# if defined(_MSC_VER) && defined(_M_X64) -# include /* needed for _set_FMA3_enable */ -# endif -# include "utfconv.h" -#endif // WIN32 - -#ifdef WITH_SDL_DYNLOAD -# include "sdlew.h" -#endif - -const int kMinWindowWidth = 100; -const int kMinWindowHeight = 100; - -static void mem_error_cb(const char *errorStr) -{ - fprintf(stderr, "%s", errorStr); - fflush(stderr); -} - -// library.c will only free window managers with a callback function. -// We don't actually use a wmWindowManager, but loading a blendfile -// loads wmWindows, so we need to free those. -static void wm_free(bContext *C, wmWindowManager *wm) -{ - BLI_freelistN(&wm->windows); -} - -#ifdef WIN32 -typedef enum { - SCREEN_SAVER_MODE_NONE = 0, - SCREEN_SAVER_MODE_PREVIEW, - SCREEN_SAVER_MODE_SAVER, - SCREEN_SAVER_MODE_CONFIGURATION, - SCREEN_SAVER_MODE_PASSWORD, -} ScreenSaverMode; - -static ScreenSaverMode scr_saver_mode = SCREEN_SAVER_MODE_NONE; -static HWND scr_saver_hwnd = NULL; - -static BOOL scr_saver_init(int argc, char **argv) -{ - scr_saver_mode = SCREEN_SAVER_MODE_NONE; - scr_saver_hwnd = NULL; - BOOL ret = false; - - int len = ::strlen(argv[0]); - if (len > 4 && !::stricmp(".scr", argv[0] + len - 4)) - { - scr_saver_mode = SCREEN_SAVER_MODE_CONFIGURATION; - ret = true; - if (argc >= 2) - { - if (argc >= 3) - { - scr_saver_hwnd = (HWND) ::atoi(argv[2]); - } - if (!::stricmp("/c", argv[1])) - { - scr_saver_mode = SCREEN_SAVER_MODE_CONFIGURATION; - if (scr_saver_hwnd == NULL) - scr_saver_hwnd = ::GetForegroundWindow(); - } - else if (!::stricmp("/s", argv[1])) - { - scr_saver_mode = SCREEN_SAVER_MODE_SAVER; - } - else if (!::stricmp("/a", argv[1])) - { - scr_saver_mode = SCREEN_SAVER_MODE_PASSWORD; - } - else if (!::stricmp("/p", argv[1]) - || !::stricmp("/l", argv[1])) - { - scr_saver_mode = SCREEN_SAVER_MODE_PREVIEW; - } - } - } - return ret; -} - -#endif /* WIN32 */ - -static void usage(const char* program, bool isBlenderPlayer) -{ - const char * consoleoption; - const char * example_filename = ""; - const char * example_pathname = ""; - -#ifdef _WIN32 - consoleoption = "[-c] "; -#else - consoleoption = ""; -#endif - - if (isBlenderPlayer) { - example_filename = "filename.blend"; -#ifdef _WIN32 - example_pathname = "c:\\"; -#else - example_pathname = "/home/user/"; -#endif - } - printf("\n"); - printf("usage: %s [--options] %s\n\n", program, example_filename); - printf("Available options are: [-w [w h l t]] [-f [fw fh fb ff]] %s[-g gamengineoptions] ", consoleoption); - printf("[-s stereomode] [-m aasamples]\n"); - printf("Optional parameters must be passed in order.\n"); - printf("Default values are set in the blend file.\n\n"); - printf(" -h: Prints this command summary\n\n"); - printf(" -w: display in a window\n"); - printf(" --Optional parameters--\n"); - printf(" w = window width\n"); - printf(" h = window height\n"); - printf(" l = window left coordinate\n"); - printf(" t = window top coordinate\n"); - printf(" Note: To define 'w' or 'h', both must be used."); - printf("Also, to define 'l' or 't', all four parameters must be used.\n"); - printf(" Example: -w or -w 500 300 or -w 500 300 0 0\n\n"); - printf(" -f: start game in fullscreen mode\n"); - printf(" --Optional parameters--\n"); - printf(" fw = fullscreen mode pixel width (use 0 to detect automatically)\n"); - printf(" fh = fullscreen mode pixel height (use 0 to detect automatically)\n"); - printf(" fb = fullscreen mode bits per pixel (default unless set in the blend file: 32)\n"); - printf(" ff = fullscreen mode frequency (default unless set in the blend file: 60)\n"); - printf(" Note: To define 'fw'' or 'fh'', both must be used.\n"); - printf(" Example: -f or -f 1024 768 or -f 0 0 16 or -f 1024 728 16 30\n\n"); - printf(" -s: start player in stereoscopy mode (requires 3D capable hardware)\n"); - printf(" stereomode: nostereo (default unless stereo is set in the blend file)\n"); - printf(" anaglyph (Red-Blue glasses)\n"); - printf(" sidebyside (Left Right)\n"); - printf(" syncdoubling (Above Below)\n"); - printf(" 3dtvtopbottom (Squashed Top-Bottom for passive glasses)\n"); - printf(" interlace (Interlace horizontally)\n"); - printf(" vinterlace (Vertical interlace for autostereo display)\n"); - printf(" hwpageflip (Quad buffered shutter glasses)\n"); - printf(" Example: -s sidebyside or -s vinterlace\n\n"); - printf(" -D: start player in dome mode\n"); - printf(" --Optional parameters--\n"); - printf(" angle = field of view in degrees\n"); - printf(" tilt = tilt angle in degrees\n"); - printf(" warpdata = a file to use for warping the image (absolute path)\n"); - printf(" mode: fisheye (Fisheye)\n"); - printf(" truncatedfront (Front-Truncated)\n"); - printf(" truncatedrear (Rear-Truncated)\n"); - printf(" cubemap (Cube Map)\n"); - printf(" sphericalpanoramic (Spherical Panoramic)\n"); - printf(" Example: -D or -D mode cubemap\n\n"); - printf(" -m: maximum anti-aliasing (eg. 2,4,8,16)\n\n"); - printf(" -i: parent window's ID\n\n"); -#ifdef _WIN32 - printf(" -c: keep console window open\n\n"); -#endif - printf(" -d: turn debugging on\n\n"); - printf(" -g: game engine options:\n\n"); - printf(" Name Default Description\n"); - printf(" ------------------------------------------------------------------------\n"); - printf(" fixedtime 0 \"Enable all frames\"\n"); - printf(" nomipmap 0 Disable mipmaps\n"); - printf(" show_framerate 0 Show the frame rate\n"); - printf(" show_properties 0 Show debug properties\n"); - printf(" show_profile 0 Show profiling information\n"); - printf(" blender_material 0 Enable material settings\n"); - printf(" ignore_deprecation_warnings 1 Ignore deprecation warnings\n"); - printf("\n"); - printf(" - : all arguments after this are ignored, allowing python to access them from sys.argv\n"); - printf("\n"); - printf("example: %s -w 320 200 10 10 -g noaudio %s%s\n", program, example_pathname, example_filename); - printf("example: %s -g show_framerate = 0 %s%s\n", program, example_pathname, example_filename); - printf("example: %s -i 232421 -m 16 %s%s\n\n", program, example_pathname, example_filename); -} - -static void get_filename(int argc, char **argv, char *filename) -{ -#ifdef __APPLE__ - /* On Mac we park the game file (called game.blend) in the application bundle. - * The executable is located in the bundle as well. - * Therefore, we can locate the game relative to the executable. - */ - int srclen = ::strlen(argv[0]); - int len = 0; - char *gamefile = NULL; - - filename[0] = '\0'; - - if (argc > 1) { - if (BLI_exists(argv[argc-1])) { - BLI_strncpy(filename, argv[argc-1], FILE_MAX); - } - if (::strncmp(argv[argc-1], "-psn_", 5)==0) { - static char firstfilebuf[512]; - if (GHOST_HACK_getFirstFile(firstfilebuf)) { - BLI_strncpy(filename, firstfilebuf, FILE_MAX); - } - } - } - - srclen -= ::strlen("MacOS/blenderplayer"); - if (srclen > 0) { - len = srclen + ::strlen("Resources/game.blend"); - gamefile = new char [len + 1]; - ::strcpy(gamefile, argv[0]); - ::strcpy(gamefile + srclen, "Resources/game.blend"); - //::printf("looking for file: %s\n", filename); - - if (BLI_exists(gamefile)) - BLI_strncpy(filename, gamefile, FILE_MAX); - - delete [] gamefile; - } - -#else - filename[0] = '\0'; - - if (argc > 1) - BLI_strncpy(filename, argv[argc-1], FILE_MAX); -#endif // !_APPLE -} - -static BlendFileData *load_game_data(const char *progname, char *filename = NULL, char *relativename = NULL) -{ - ReportList reports; - BlendFileData *bfd = NULL; - - BKE_reports_init(&reports, RPT_STORE); - - /* try to load ourself, will only work if we are a runtime */ - if (BLO_is_a_runtime(progname)) { - bfd= BLO_read_runtime(progname, &reports); - if (bfd) { - bfd->type= BLENFILETYPE_RUNTIME; - BLI_strncpy(bfd->main->name, progname, sizeof(bfd->main->name)); - } - } else { - bfd= BLO_read_from_file(progname, &reports, BLO_READ_SKIP_NONE); - } - - if (!bfd && filename) { - bfd = load_game_data(filename); - if (!bfd) { - printf("Loading %s failed: ", filename); - BKE_reports_print(&reports, RPT_ERROR); - } - } - - BKE_reports_clear(&reports); - - return bfd; -} - -static bool GPG_NextFrame(GHOST_ISystem* system, GPG_Application *app, int &exitcode, STR_String &exitstring, GlobalSettings *gs) -{ - bool run = true; - system->processEvents(false); - system->dispatchEvents(); - app->EngineNextFrame(); - if ((exitcode = app->getExitRequested())) { - run = false; - exitstring = app->getExitString(); - *gs = *app->getGlobalSettings(); - } - return run; -} - -struct GPG_NextFrameState { - GHOST_ISystem* system; - GPG_Application *app; - GlobalSettings *gs; -} gpg_nextframestate; - -static int GPG_PyNextFrame(void *state0) -{ - GPG_NextFrameState *state = (GPG_NextFrameState *) state0; - int exitcode; - STR_String exitstring; - bool run = GPG_NextFrame(state->system, state->app, exitcode, exitstring, state->gs); - if (run) return 0; - else { - if (exitcode) - fprintf(stderr, "Exit code %d: %s\n", exitcode, exitstring.ReadPtr()); - return 1; - } -} - -int main( - int argc, -#ifdef WIN32 - char **UNUSED(argv_c) -#else - char **argv -#endif - ) -{ - int i; - int argc_py_clamped= argc; /* use this so python args can be added after ' - ' */ - bool error = false; - SYS_SystemHandle syshandle = SYS_GetSystem(); - bool fullScreen = false; - bool fullScreenParFound = false; - bool windowParFound = false; -#ifdef WIN32 - bool closeConsole = true; -#endif - RAS_IRasterizer::StereoMode stereomode = RAS_IRasterizer::RAS_STEREO_NOSTEREO; - bool stereoWindow = false; - bool stereoParFound = false; - int stereoFlag = STEREO_NOSTEREO; - int domeFov = -1; - int domeTilt = -200; - int domeMode = 0; - char* domeWarp = NULL; - Text *domeText = NULL; - int windowLeft = 100; - int windowTop = 100; - int windowWidth = 640; - int windowHeight = 480; - GHOST_TUns32 fullScreenWidth = 0; - GHOST_TUns32 fullScreenHeight= 0; - int fullScreenBpp = 32; - int fullScreenFrequency = 60; - GHOST_TEmbedderWindowID parentWindow = 0; - bool isBlenderPlayer = false; //true when lauching from blender or command line. false for bundled player - int validArguments=0; - bool samplesParFound = false; - GHOST_TUns16 aasamples = 0; - int alphaBackground = 0; - -#ifdef WIN32 - char **argv; - int argv_num; - - /* We delay loading of openmp so we can set the policy here. */ -# if defined(_MSC_VER) - _putenv_s("OMP_WAIT_POLICY", "PASSIVE"); -# endif - - /* FMA3 support in the 2013 CRT is broken on Vista and Windows 7 RTM (fixed in SP1). Just disable it. */ -# if defined(_MSC_VER) && defined(_M_X64) - _set_FMA3_enable(0); -# endif - - /* Win32 Unicode Args */ - /* NOTE: cannot use guardedalloc malloc here, as it's not yet initialized - * (it depends on the args passed in, which is what we're getting here!) - */ - { - wchar_t **argv_16 = CommandLineToArgvW(GetCommandLineW(), &argc); - argv = (char**)malloc(argc * sizeof(char *)); - for (argv_num = 0; argv_num < argc; argv_num++) { - argv[argv_num] = alloc_utf_8_from_16(argv_16[argv_num], 0); - } - LocalFree(argv_16); - } -#endif /* WIN32 */ - -#ifdef __linux__ -#ifdef __alpha__ - signal (SIGFPE, SIG_IGN); -#endif /* __alpha__ */ -#endif /* __linux__ */ - -#ifdef WITH_SDL_DYNLOAD - sdlewInit(); -#endif - - BKE_appdir_program_path_init(argv[0]); - BKE_tempdir_init(NULL); - - // We don't use threads directly in the BGE, but we need to call this so things like - // freeing up GPU_Textures works correctly. - BLI_threadapi_init(); - - DNA_sdna_current_init(); - - RNA_init(); - - init_nodesystem(); - - BKE_blender_globals_init(); - - // We load our own G.main, so free the one that BKE_blender_globals_init() gives us - BKE_main_free(G.main); - G.main = NULL; - - MEM_CacheLimiter_set_disabled(true); - IMB_init(); - BKE_images_init(); - BKE_modifier_init(); - DEG_register_node_types(); - -#ifdef WITH_FFMPEG - IMB_ffmpeg_init(); -#endif - - // Setup builtin font for BLF (mostly copied from creator.c, wm_init_exit.c and interface_style.c) - BLF_init(); - BLT_lang_init(); - BLT_lang_set(""); - - BLF_load_mem("default", (unsigned char*)datatoc_bfont_ttf, datatoc_bfont_ttf_size); - if (blf_mono_font == -1) - blf_mono_font = BLF_load_mem_unique("monospace", (unsigned char*)datatoc_bmonofont_ttf, datatoc_bmonofont_ttf_size); - - // Parse command line options -#if defined(DEBUG) - printf("argv[0] = '%s'\n", argv[0]); -#endif - -#ifdef WIN32 - if (scr_saver_init(argc, argv)) - { - switch (scr_saver_mode) - { - case SCREEN_SAVER_MODE_CONFIGURATION: - MessageBox(scr_saver_hwnd, "This screen saver has no options that you can set", "Screen Saver", MB_OK); - break; - case SCREEN_SAVER_MODE_PASSWORD: - /* This is W95 only, which we currently do not support. - * Fall-back to normal screen saver behavior in that case... */ - case SCREEN_SAVER_MODE_SAVER: - fullScreen = true; - fullScreenParFound = true; - break; - - case SCREEN_SAVER_MODE_PREVIEW: - /* This will actually be handled somewhere below... */ - break; - } - } -#endif - // XXX add the ability to change this values to the command line parsing. - U.mixbufsize = 2048; - U.audiodevice = 2; - U.audiorate = 44100; - U.audioformat = 0x24; - U.audiochannels = 2; - - // XXX this one too - U.anisotropic_filter = 2; - // enable fast mipmap generation - U.use_gpu_mipmap = 1; - - BKE_sound_init_once(); - - // Initialize a default material for meshes without materials. - init_def_material(); - - BKE_library_callback_free_window_manager_set(wm_free); - - /* if running blenderplayer the last argument can't be parsed since it has to be the filename. else it is bundled */ - isBlenderPlayer = !BLO_is_a_runtime(argv[0]); - if (isBlenderPlayer) - validArguments = argc - 1; - else - validArguments = argc; - - - /* Parsing command line arguments (can be set from WM_OT_blenderplayer_start) */ -#if defined(DEBUG) - printf("Parsing command line arguments...\n"); - printf("Num of arguments is: %i\n", validArguments-1); //-1 because i starts at 1 -#endif - - for (i = 1; (i < validArguments) && !error -#ifdef WIN32 - && scr_saver_mode == SCREEN_SAVER_MODE_NONE -#endif - ;) - - { -#if defined(DEBUG) - printf("argv[%d] = '%s'\n", i, argv[i]); -#endif - if (argv[i][0] == '-') - { - /* ignore all args after " - ", allow python to have own args */ - if (argv[i][1]=='\0') { - argc_py_clamped= i; - break; - } - - switch (argv[i][1]) - { - case 'g': //game engine options (show_framerate, fixedtime, etc) - { - i++; - if (i <= validArguments) - { - char* paramname = argv[i]; - // Check for single value versus assignment - if (i+1 <= validArguments && (*(argv[i+1]) == '=')) - { - i++; - if (i + 1 <= validArguments) - { - i++; - // Assignment - SYS_WriteCommandLineInt(syshandle, paramname, atoi(argv[i])); - SYS_WriteCommandLineFloat(syshandle, paramname, atof(argv[i])); - SYS_WriteCommandLineString(syshandle, paramname, argv[i]); -#if defined(DEBUG) - printf("%s = '%s'\n", paramname, argv[i]); -#endif - i++; - } - else - { - error = true; - printf("error: argument assignment %s without value.\n", paramname); - } - } - else - { -// SYS_WriteCommandLineInt(syshandle, argv[i++], 1); - } - } - break; - } - case 'd': //debug on - { - i++; - G.debug |= G_DEBUG; - MEM_set_memory_debug(); -#ifndef NDEBUG - BLI_mempool_set_memory_debug(); -#endif - break; - } - case 'f': //fullscreen mode - { - i++; - fullScreen = true; - fullScreenParFound = true; - if ((i + 2) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-') - { - fullScreenWidth = atoi(argv[i++]); - fullScreenHeight = atoi(argv[i++]); - if ((i + 1) <= validArguments && argv[i][0] != '-') - { - fullScreenBpp = atoi(argv[i++]); - if ((i + 1) <= validArguments && argv[i][0] != '-') - fullScreenFrequency = atoi(argv[i++]); - } - } - else if ((i + 1) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-') - { - error = true; - printf("error: to define fullscreen width or height, both options must be used.\n"); - } - break; - } - case 'w': //display in a window - { - i++; - fullScreen = false; - windowParFound = true; - - // Parse window position and size options - if ((i + 2) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-') - { - windowWidth = atoi(argv[i++]); - windowHeight = atoi(argv[i++]); - - if ((i + 2) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-') - { - windowLeft = atoi(argv[i++]); - windowTop = atoi(argv[i++]); - } - else if ((i + 1) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-') - { - error = true; - printf("error: to define the window left or right coordinates, both options must be used.\n"); - } - } - else if ((i + 1) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-') - { - error = true; - printf("error: to define the window's width or height, both options must be used.\n"); - } - break; - } - case 'h': //display help - { - usage(argv[0], isBlenderPlayer); - return 0; - break; - } - case 'i': //parent window ID - { - i++; - if ( (i + 1) <= validArguments ) - parentWindow = (GHOST_TEmbedderWindowID)atoll(argv[i++]); - else { - error = true; - printf("error: too few options for parent window argument.\n"); - } -#if defined(DEBUG) - printf("XWindows ID = %d\n", parentWindow); -#endif // defined(DEBUG) - break; - } - case 'm': //maximum anti-aliasing (eg. 2,4,8,16) - { - i++; - samplesParFound = true; - if ((i+1) <= validArguments ) - aasamples = atoi(argv[i++]); - else - { - error = true; - printf("error: No argument supplied for -m"); - } - break; - } - case 'c': //keep console (windows only) - { - i++; -#ifdef WIN32 - closeConsole = false; -#endif - break; - } - case 's': //stereo mode - { - i++; - if ((i + 1) <= validArguments) - { - stereoParFound = true; - stereoFlag = STEREO_ENABLED; - - if (!strcmp(argv[i], "nostereo")) // may not be redundant if the file has different setting - { - stereomode = RAS_IRasterizer::RAS_STEREO_NOSTEREO; - stereoFlag = STEREO_NOSTEREO; - } - - // only the hardware pageflip method needs a stereo window - else if (!strcmp(argv[i], "hwpageflip")) { - stereomode = RAS_IRasterizer::RAS_STEREO_QUADBUFFERED; - stereoWindow = true; - } - else if (!strcmp(argv[i], "syncdoubling")) - stereomode = RAS_IRasterizer::RAS_STEREO_ABOVEBELOW; - - else if (!strcmp(argv[i], "3dtvtopbottom")) - stereomode = RAS_IRasterizer::RAS_STEREO_3DTVTOPBOTTOM; - - else if (!strcmp(argv[i], "anaglyph")) - stereomode = RAS_IRasterizer::RAS_STEREO_ANAGLYPH; - - else if (!strcmp(argv[i], "sidebyside")) - stereomode = RAS_IRasterizer::RAS_STEREO_SIDEBYSIDE; - - else if (!strcmp(argv[i], "interlace")) - stereomode = RAS_IRasterizer::RAS_STEREO_INTERLACED; - - else if (!strcmp(argv[i], "vinterlace")) - stereomode = RAS_IRasterizer::RAS_STEREO_VINTERLACE; - -#if 0 -// // future stuff -// else if (!strcmp(argv[i], "stencil") -// stereomode = RAS_STEREO_STENCIL; -#endif - else - { - error = true; - printf("error: stereomode '%s' unrecognized.\n", argv[i]); - } - - i++; - } - else - { - error = true; - printf("error: too few options for stereo argument.\n"); - } - break; - } - case 'D': //dome mode - { - stereoFlag = STEREO_DOME; - stereomode = RAS_IRasterizer::RAS_STEREO_DOME; - i++; - if ((i + 1) <= validArguments) - { - if (!strcmp(argv[i], "angle")) { - i++; - domeFov = atoi(argv[i++]); - } - if (!strcmp(argv[i], "tilt")) { - i++; - domeTilt = atoi(argv[i++]); - } - if (!strcmp(argv[i], "warpdata")) { - i++; - domeWarp = argv[i++]; - } - if (!strcmp(argv[i], "mode")) { - i++; - if (!strcmp(argv[i], "fisheye")) - domeMode = DOME_FISHEYE; - - else if (!strcmp(argv[i], "truncatedfront")) - domeMode = DOME_TRUNCATED_FRONT; - - else if (!strcmp(argv[i], "truncatedrear")) - domeMode = DOME_TRUNCATED_REAR; - - else if (!strcmp(argv[i], "cubemap")) - domeMode = DOME_ENVMAP; - - else if (!strcmp(argv[i], "sphericalpanoramic")) - domeMode = DOME_PANORAM_SPH; - - else - printf("error: %s is not a valid dome mode.\n", argv[i]); - } - i++; - } - break; - } - case 'a': // allow window to blend with display background - { - i++; - alphaBackground = 1; - break; - } - default: //not recognized - { - printf("Unknown argument: %s\n", argv[i++]); - break; - } - } - } - else - { - i++; - } - } - - if ((windowWidth < kMinWindowWidth) || (windowHeight < kMinWindowHeight)) - { - error = true; - printf("error: window size too small.\n"); - } - - if (error ) - { - usage(argv[0], isBlenderPlayer); - return 0; - } - -#ifdef WIN32 - if (scr_saver_mode != SCREEN_SAVER_MODE_CONFIGURATION) -#endif - { - // Create the system - if (GHOST_ISystem::createSystem() == GHOST_kSuccess) { - GHOST_ISystem* system = GHOST_ISystem::getSystem(); - assertd(system); - - if (!fullScreenWidth || !fullScreenHeight) - system->getMainDisplayDimensions(fullScreenWidth, fullScreenHeight); - // process first batch of events. If the user - // drops a file on top off the blenderplayer icon, we - // receive an event with the filename - - system->processEvents(0); - - // this bracket is needed for app (see below) to get out - // of scope before GHOST_ISystem::disposeSystem() is called. - { - int exitcode = KX_EXIT_REQUEST_NO_REQUEST; - STR_String exitstring = ""; - GPG_Application app(system); - bool firstTimeRunning = true; - char filename[FILE_MAX]; - char pathname[FILE_MAX]; - char *titlename; - - get_filename(argc_py_clamped, argv, filename); - if (filename[0]) - BLI_path_cwd(filename, sizeof(filename)); - - - // fill the GlobalSettings with the first scene files - // those may change during the game and persist after using Game Actuator - GlobalSettings gs; - - do { - // Read the Blender file - BlendFileData *bfd; - - // if we got an exitcode 3 (KX_EXIT_REQUEST_START_OTHER_GAME) load a different file - if (exitcode == KX_EXIT_REQUEST_START_OTHER_GAME) - { - char basedpath[FILE_MAX]; - - // base the actuator filename relative to the last file - BLI_strncpy(basedpath, exitstring.Ptr(), sizeof(basedpath)); - BLI_path_abs(basedpath, pathname); - - bfd = load_game_data(basedpath); - - if (!bfd) { - // just add "//" in front of it - char temppath[FILE_MAX] = "//"; - BLI_strncpy(temppath + 2, basedpath, FILE_MAX - 2); - - BLI_path_abs(temppath, pathname); - bfd = load_game_data(temppath); - } - } - else { - bfd = load_game_data(BKE_appdir_program_path(), filename[0]? filename: NULL); - } - -#if defined(DEBUG) - printf("Game data loaded from %s\n", filename); -#endif - - if (!bfd) { - usage(argv[0], isBlenderPlayer); - error = true; - exitcode = KX_EXIT_REQUEST_QUIT_GAME; - } - else { - /* Setting options according to the blend file if not overriden in the command line */ -#ifdef WIN32 -#if !defined(DEBUG) - if (closeConsole) { - system->toggleConsole(0); // Close a console window - } -#endif // !defined(DEBUG) -#endif // WIN32 - Main *maggie = bfd->main; - Scene *scene = bfd->curscene; - G.main = maggie; - - if (firstTimeRunning) { - G.fileflags = bfd->fileflags; - - gs.matmode= scene->gm.matmode; - gs.glslflag= scene->gm.flag; - } - - //Seg Fault; icon.c gIcons == 0 - BKE_icons_init(1); - - titlename = maggie->name; - - // Check whether the game should be displayed full-screen - if ((!fullScreenParFound) && (!windowParFound)) { - // Only use file settings when command line did not override - if ((scene->gm.playerflag & GAME_PLAYER_FULLSCREEN)) { - //printf("fullscreen option found in Blender file\n"); - fullScreen = true; - fullScreenWidth= scene->gm.xplay; - fullScreenHeight= scene->gm.yplay; - fullScreenFrequency= scene->gm.freqplay; - fullScreenBpp = scene->gm.depth; - } - else - { - fullScreen = false; - windowWidth = scene->gm.xplay; - windowHeight = scene->gm.yplay; - } - } - - - // Check whether the game should be displayed in stereo (dome included) - if (!stereoParFound) { - // Only use file settings when command line did not override - if (scene->gm.stereoflag == STEREO_ENABLED) { - stereomode = (RAS_IRasterizer::StereoMode) scene->gm.stereomode; - if (stereomode == RAS_IRasterizer::RAS_STEREO_QUADBUFFERED) - stereoWindow = true; - } - } - else { - scene->gm.stereoflag = STEREO_ENABLED; - } - - if (!samplesParFound) - aasamples = scene->gm.aasamples; - - // Dome specific settings - if (stereoFlag == STEREO_DOME) { - stereomode = RAS_IRasterizer::RAS_STEREO_DOME; - scene->gm.stereoflag = STEREO_DOME; - if (domeFov > 89) - scene->gm.dome.angle = domeFov; - if (domeTilt > -180) - scene->gm.dome.tilt = domeTilt; - if (domeMode > 0) - scene->gm.dome.mode = domeMode; - if (domeWarp) { - //XXX to do: convert relative to absolute path - domeText= BKE_text_load(G.main, domeWarp, ""); - if (!domeText) - printf("error: invalid warpdata text file - %s\n", domeWarp); - else - scene->gm.dome.warptext = domeText; - } - } - - // GPG_Application app (system, maggie, startscenename); - app.SetGameEngineData(maggie, scene, &gs, argc, argv); /* this argc cant be argc_py_clamped, since python uses it */ - BLI_strncpy(pathname, maggie->name, sizeof(pathname)); - if (G.main != maggie) { - BLI_strncpy(G.main->name, maggie->name, sizeof(G.main->name)); - } -#ifdef WITH_PYTHON - setGamePythonPath(G.main->name); -#endif - if (firstTimeRunning) { - firstTimeRunning = false; - - if (fullScreen) { -#ifdef WIN32 - if (scr_saver_mode == SCREEN_SAVER_MODE_SAVER) - { - app.startScreenSaverFullScreen(fullScreenWidth, fullScreenHeight, fullScreenBpp, fullScreenFrequency, - stereoWindow, stereomode, aasamples); - } - else -#endif - { - app.startFullScreen(fullScreenWidth, fullScreenHeight, fullScreenBpp, fullScreenFrequency, - stereoWindow, stereomode, alphaBackground, aasamples, (scene->gm.playerflag & GAME_PLAYER_DESKTOP_RESOLUTION)); - } - } - else - { -#ifdef __APPLE__ - // on Mac's we'll show the executable name instead of the 'game.blend' name - char tempname[1024], *appstring; - ::strcpy(tempname, titlename); - - appstring = strstr(tempname, ".app/"); - if (appstring) { - appstring[2] = 0; - titlename = &tempname[0]; - } -#endif - // Strip the path so that we have the name of the game file - STR_String path = titlename; -#ifndef WIN32 - vector parts = path.Explode('/'); -#else // WIN32 - vector parts = path.Explode('\\'); -#endif // WIN32 - STR_String title; - if (parts.size()) { - title = parts[parts.size()-1]; - parts = title.Explode('.'); - if (parts.size() > 1) - { - title = parts[0]; - } - } - else { - title = "blenderplayer"; - } -#ifdef WIN32 - if (scr_saver_mode == SCREEN_SAVER_MODE_PREVIEW) - { - app.startScreenSaverPreview(scr_saver_hwnd, stereoWindow, stereomode, aasamples); - } - else -#endif - { - if (parentWindow != 0) - app.startEmbeddedWindow(title, parentWindow, stereoWindow, stereomode, aasamples); - else - app.startWindow(title, windowLeft, windowTop, windowWidth, windowHeight, - stereoWindow, stereomode, alphaBackground, aasamples); - - if (SYS_GetCommandLineInt(syshandle, "nomipmap", 0)) { - GPU_set_mipmap(0); - } - - GPU_set_anisotropic(U.anisotropic_filter); - GPU_set_gpu_mipmapping(U.use_gpu_mipmap); - } - } - } - else { - app.StartGameEngine(stereomode); - exitcode = KX_EXIT_REQUEST_NO_REQUEST; - } - - // Add the application as event consumer - system->addEventConsumer(&app); - - // Enter main loop - bool run = true; - char *python_main = NULL; - pynextframestate.state = NULL; - pynextframestate.func = NULL; -#ifdef WITH_PYTHON - python_main = KX_GetPythonMain(scene); -#endif // WITH_PYTHON - if (python_main) { - char *python_code = KX_GetPythonCode(maggie, python_main); - if (python_code) { -#ifdef WITH_PYTHON - // Set python environement variable. - KX_Scene *startscene = app.GetStartScene(); - KX_SetActiveScene(startscene); - PHY_SetActiveEnvironment(startscene->GetPhysicsEnvironment()); - - gpg_nextframestate.system = system; - gpg_nextframestate.app = &app; - gpg_nextframestate.gs = &gs; - pynextframestate.state = &gpg_nextframestate; - pynextframestate.func = &GPG_PyNextFrame; - - printf("Yielding control to Python script '%s'...\n", python_main); - PyRun_SimpleString(python_code); - printf("Exit Python script '%s'\n", python_main); -#endif // WITH_PYTHON - MEM_freeN(python_code); - } - else { - fprintf(stderr, "ERROR: cannot yield control to Python: no Python text data-block named '%s'\n", python_main); - } - } - else { - while (run) { - run = GPG_NextFrame(system, &app, exitcode, exitstring, &gs); - } - } - app.StopGameEngine(); - - /* 'app' is freed automatic when out of scope. - * removal is needed else the system will free an already freed value */ - system->removeEventConsumer(&app); - - BLO_blendfiledata_free(bfd); - /* G.main == bfd->main, it gets referenced in free_nodesystem so we can't have a dangling pointer */ - G.main = NULL; - if (python_main) MEM_freeN(python_main); - } - } while (exitcode == KX_EXIT_REQUEST_RESTART_GAME || exitcode == KX_EXIT_REQUEST_START_OTHER_GAME); - } - - // Seg Fault; icon.c gIcons == 0 - BKE_icons_free(); - - // Dispose the system - GHOST_ISystem::disposeSystem(); - } - else { - error = true; - printf("error: couldn't create a system.\n"); - } - } - - /* refer to WM_exit_ext() and BKE_blender_free(), - * these are not called in the player but we need to match some of there behavior here, - * if the order of function calls or blenders state isn't matching that of blender proper, - * we may get troubles later on */ - - free_nodesystem(); - - // Cleanup - RNA_exit(); - BLF_exit(); - -#ifdef WITH_INTERNATIONAL - BLF_free_unifont(); - BLF_free_unifont_mono(); - BLT_lang_free(); -#endif - - IMB_exit(); - BKE_images_exit(); - DEG_free_node_types(); - IMB_moviecache_destruct(); - - SYS_DeleteSystem(syshandle); - - int totblock= MEM_get_memory_blocks_in_use(); - if (totblock!=0) { - printf("Error Totblock: %d\n",totblock); - MEM_set_error_callback(mem_error_cb); - MEM_printmemlist(); - } - - BKE_tempdir_session_purge(); - -#ifdef WIN32 - while (argv_num) { - free(argv[--argv_num]); - } - free(argv); - argv = NULL; -#endif - - return error ? -1 : 0; -} 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__ */ diff --git a/source/gameengine/Network/CMakeLists.txt b/source/gameengine/Network/CMakeLists.txt deleted file mode 100644 index 019fc3e6032..00000000000 --- a/source/gameengine/Network/CMakeLists.txt +++ /dev/null @@ -1,48 +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 - . - ../../../intern/container - ../../../intern/string - ../../blender/blenlib -) - -set(INC_SYS - ../../../intern/moto/include -) - -set(SRC - NG_NetworkMessage.cpp - NG_NetworkObject.cpp - NG_NetworkScene.cpp - - NG_NetworkDeviceInterface.h - NG_NetworkMessage.h - NG_NetworkObject.h - NG_NetworkScene.h -) - -blender_add_lib(ge_logic_ngnetwork "${SRC}" "${INC}" "${INC_SYS}") diff --git a/source/gameengine/Network/LoopBackNetwork/CMakeLists.txt b/source/gameengine/Network/LoopBackNetwork/CMakeLists.txt deleted file mode 100644 index 75877575614..00000000000 --- a/source/gameengine/Network/LoopBackNetwork/CMakeLists.txt +++ /dev/null @@ -1,43 +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 - . - .. - ../../../../intern/container - ../../../../intern/string -) - -set(INC_SYS - -) - -set(SRC - NG_LoopBackNetworkDeviceInterface.cpp - - NG_LoopBackNetworkDeviceInterface.h -) - -blender_add_lib(ge_logic_loopbacknetwork "${SRC}" "${INC}" "${INC_SYS}") diff --git a/source/gameengine/Network/LoopBackNetwork/NG_LoopBackNetworkDeviceInterface.cpp b/source/gameengine/Network/LoopBackNetwork/NG_LoopBackNetworkDeviceInterface.cpp deleted file mode 100644 index c57bd304ca2..00000000000 --- a/source/gameengine/Network/LoopBackNetwork/NG_LoopBackNetworkDeviceInterface.cpp +++ /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 ***** - * LoopbackNetworkDeviceInterface derived from NG_NetworkDeviceInterface - */ - -/** \file gameengine/Network/LoopBackNetwork/NG_LoopBackNetworkDeviceInterface.cpp - * \ingroup bgenetlb - */ - - -#include "NG_LoopBackNetworkDeviceInterface.h" -#include "NG_NetworkMessage.h" - -using namespace std; - -// temporary debugging printf's -#ifdef NAN_NET_DEBUG - #include -#endif - -NG_LoopBackNetworkDeviceInterface::NG_LoopBackNetworkDeviceInterface() -{ - m_currentQueue=0; - Online(); // LoopBackdevices are 'online' immediately -} - -NG_LoopBackNetworkDeviceInterface::~NG_LoopBackNetworkDeviceInterface() -{ -} - -// perhaps this should go to the shared/common implementation too -void NG_LoopBackNetworkDeviceInterface::NextFrame() -{ - // Release reference to the messages while emptying the queue - while (m_messages[m_currentQueue].size() > 0) { -#ifdef NAN_NET_DEBUG - printf("NG_LBNDI::NextFrame %d '%s'\n", m_currentQueue, m_messages[m_currentQueue][0]->GetSubject().ReadPtr()); -#endif - // Should do assert(m_events[0]); - m_messages[m_currentQueue][0]->Release(); - m_messages[m_currentQueue].pop_front(); - } - //m_messages[m_currentQueue].clear(); - - m_currentQueue=1-m_currentQueue; -} - -void NG_LoopBackNetworkDeviceInterface::SendNetworkMessage(NG_NetworkMessage* nwmsg) -{ -#ifdef NAN_NET_DEBUG - printf("NG_LBNDI::SendNetworkMessage %d, '%s'->'%s' '%s' '%s'\n", - 1-m_currentQueue, - nwmsg->GetDestinationName().ReadPtr(), - nwmsg->GetSenderName().ReadPtr(), - nwmsg->GetSubject().ReadPtr(), - nwmsg->GetMessageText().ReadPtr()); -#endif - int backqueue = 1-m_currentQueue; - - nwmsg->AddRef(); - m_messages[backqueue].push_back(nwmsg); -} - -vector NG_LoopBackNetworkDeviceInterface::RetrieveNetworkMessages() -{ - vector messages; - - std::deque::iterator mesit=m_messages[m_currentQueue].begin(); - for (; !(mesit == m_messages[m_currentQueue].end()); ++mesit) - { - - // We don't increase the reference count for these messages. We - // are passing a vector of messages in the interface and not - // explicitily storing the messgaes for long term usage - - messages.push_back(*mesit); - -#ifdef NAN_NET_DEBUG - printf("NG_LBNDI::RetrieveNetworkMessages %d '%s'->'%s' '%s' '%s'\n", - m_currentQueue, - (*mesit)->GetDestinationName().ReadPtr(), - (*mesit)->GetSenderName().ReadPtr(), - (*mesit)->GetSubject().ReadPtr(), - (*mesit)->GetMessageText().ReadPtr()); -#endif - } - return messages; -} - diff --git a/source/gameengine/Network/LoopBackNetwork/NG_LoopBackNetworkDeviceInterface.h b/source/gameengine/Network/LoopBackNetwork/NG_LoopBackNetworkDeviceInterface.h deleted file mode 100644 index 8bbb1e91e35..00000000000 --- a/source/gameengine/Network/LoopBackNetwork/NG_LoopBackNetworkDeviceInterface.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 NG_LoopBackNetworkDeviceInterface.h - * \ingroup bgenetlb - * \brief LoopbackNetworkDeviceInterface derived from NG_NetworkDeviceInterface - */ -#ifndef __NG_LOOPBACKNETWORKDEVICEINTERFACE_H__ -#define __NG_LOOPBACKNETWORKDEVICEINTERFACE_H__ - -#include -#include "NG_NetworkDeviceInterface.h" - -class NG_LoopBackNetworkDeviceInterface : public NG_NetworkDeviceInterface -{ - std::deque m_messages[2]; - int m_currentQueue; - -public: - NG_LoopBackNetworkDeviceInterface(); - virtual ~NG_LoopBackNetworkDeviceInterface(); - - /** - * Clear message buffer - */ - virtual void NextFrame(); - - bool Connect(char *address, unsigned int port, char *password, - unsigned int localport, unsigned int timeout) - { - return true; - } - bool Disconnect(void) {return true;} - - virtual void SendNetworkMessage(class NG_NetworkMessage* msg); - virtual std::vector RetrieveNetworkMessages(); -}; - -#endif /* __NG_LOOPBACKNETWORKDEVICEINTERFACE_H__ */ diff --git a/source/gameengine/Network/NG_NetworkDeviceInterface.h b/source/gameengine/Network/NG_NetworkDeviceInterface.h deleted file mode 100644 index 7fcf799db31..00000000000 --- a/source/gameengine/Network/NG_NetworkDeviceInterface.h +++ /dev/null @@ -1,82 +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 NG_NetworkDeviceInterface.h - * \ingroup bgenet - * \brief Functions like (de)initialize network, get library version - * To be derived by loopback and network libraries - */ - -#ifndef __NG_NETWORKDEVICEINTERFACE_H__ -#define __NG_NETWORKDEVICEINTERFACE_H__ - -#include "NG_NetworkMessage.h" -#include - -class NG_NetworkDeviceInterface -{ -private: - // candidates for shared/common implementation class - bool m_online; -public: - NG_NetworkDeviceInterface() {} - virtual ~NG_NetworkDeviceInterface() {} - - virtual void NextFrame()=0; - - /** - * Mark network connection online - */ - void Online(void) { m_online = true; } - /** - * Mark network connection offline - */ - void Offline(void) { m_online = false; } - /** - * Is the network connection established ? - */ - bool IsOnline(void) { return m_online; } - - virtual bool Connect(char *address, unsigned int port, char *password, - unsigned int localport, unsigned int timeout)=0; - virtual bool Disconnect(void)=0; - - virtual void SendNetworkMessage(NG_NetworkMessage* msg)=0; - /** - * read NG_NetworkMessage from library buffer, may be - * irrelevant for loopbackdevices - */ - - virtual std::vector RetrieveNetworkMessages()=0; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:NG_NetworkDeviceInterface") -#endif -}; - -#endif /* __NG_NETWORKDEVICEINTERFACE_H__ */ diff --git a/source/gameengine/Network/NG_NetworkMessage.cpp b/source/gameengine/Network/NG_NetworkMessage.cpp deleted file mode 100644 index 23ae2529b7a..00000000000 --- a/source/gameengine/Network/NG_NetworkMessage.cpp +++ /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 ***** - * generic Network Message implementation - */ - -/** \file gameengine/Network/NG_NetworkMessage.cpp - * \ingroup bgenet - */ - -#include "NG_NetworkMessage.h" -#include - -int NG_NetworkMessage::s_nextID = 3; // just some number to start with - -NG_NetworkMessage::NG_NetworkMessage( - const STR_String& to, - const STR_String& from, - const STR_String& subject, - const STR_String& body) : - m_uniqueMessageID(s_nextID++), - m_refcount(1), - m_to(to), - m_from(from), - m_subject(subject), - m_message(body) -{ -} - -NG_NetworkMessage::~NG_NetworkMessage() -{ - assert(m_refcount==0); -} diff --git a/source/gameengine/Network/NG_NetworkMessage.h b/source/gameengine/Network/NG_NetworkMessage.h deleted file mode 100644 index 6ed266557fc..00000000000 --- a/source/gameengine/Network/NG_NetworkMessage.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 NG_NetworkMessage.h - * \ingroup bgenet - * \brief generic Network Message class - */ -#ifndef __NG_NETWORKMESSAGE_H__ -#define __NG_NETWORKMESSAGE_H__ - -#include "STR_HashedString.h" - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -class NG_NetworkMessage -{ - static int s_nextID; - int m_uniqueMessageID; // intern counting MessageID - unsigned int m_ClientId; - int m_refcount; - - STR_String m_to; // receiver - STR_String m_from; // sender - STR_String m_subject; // empty or propName - STR_String m_message; // message or propValue - -protected: - ~NG_NetworkMessage(); - -public: - NG_NetworkMessage( - const STR_String& to, - const STR_String& from, - const STR_String& subject, - const STR_String& body); - - void AddRef() { - m_refcount++; - } - - // This is not nice code you should'nt need to resort to - // delete this. - void Release() - { - if (! --m_refcount) - { - delete this; - } - } - - /** - * set the content of this message - */ - void SetMessageText(const STR_String& msgtext) { - m_message = msgtext; - } - - /** - * get the (read-only) To part of this message - */ - const STR_String& GetDestinationName() { return m_to; } - - /** - * get the (read-only) From part of this message - */ - const STR_String& GetSenderName() { return m_from; } - - /** - * get the (read-only) Subject part of this message - */ - const STR_String& GetSubject() { return m_subject; } - - /** - * get the (read-only) Body part of this message - */ - const STR_String& GetMessageText() { -//cout << "GetMessageText " << m_message << "\n"; - return m_message; - } - const STR_String& GetMessageText() const { -//cout << "GetMessageText " << m_message << "\n"; - return m_message; - } - - /** - * Set the NetworkMessage sender identifier - */ - void SetSender(unsigned int ClientId) { - m_ClientId = ClientId; - } - - /** - * Get the NetworkMessage sender identifier - */ - unsigned int GetSender(void) { - return m_ClientId; - } - - /** - * get the unique Network Message ID - */ - int GetMessageID() { - return m_uniqueMessageID; - } - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:NG_NetworkMessage") -#endif -}; - -#endif /* __NG_NETWORKMESSAGE_H__ */ diff --git a/source/gameengine/Network/NG_NetworkObject.cpp b/source/gameengine/Network/NG_NetworkObject.cpp deleted file mode 100644 index 5cd42a2e45a..00000000000 --- a/source/gameengine/Network/NG_NetworkObject.cpp +++ /dev/null @@ -1,46 +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 ***** - * NetworkGame_NetworkObject generic Network Object implementation - */ - -/** \file gameengine/Network/NG_NetworkObject.cpp - * \ingroup bgenet - */ - -#include "NG_NetworkObject.h" - -NG_NetworkObject::NG_NetworkObject() -{ -} - -NG_NetworkObject::~NG_NetworkObject() -{ -} - -const STR_String& NG_NetworkObject::GetName() -{ - return m_name; -} diff --git a/source/gameengine/Network/NG_NetworkObject.h b/source/gameengine/Network/NG_NetworkObject.h deleted file mode 100644 index 54459cad55d..00000000000 --- a/source/gameengine/Network/NG_NetworkObject.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 NG_NetworkObject.h - * \ingroup bgenet - * \brief generic Network Object class - */ -#ifndef __NG_NETWORKOBJECT_H__ -#define __NG_NETWORKOBJECT_H__ - -#include "STR_String.h" - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -class NG_NetworkObject -{ - STR_String m_name; -public: - NG_NetworkObject(); - ~NG_NetworkObject(); - const STR_String& GetName(); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:NG_NetworkObject") -#endif -}; - -#endif /* __NG_NETWORKOBJECT_H__ */ diff --git a/source/gameengine/Network/NG_NetworkScene.cpp b/source/gameengine/Network/NG_NetworkScene.cpp deleted file mode 100644 index 3dbfb53d03d..00000000000 --- a/source/gameengine/Network/NG_NetworkScene.cpp +++ /dev/null @@ -1,272 +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 ***** - * NetworkSceneManagement generic implementation - */ - -/** \file gameengine/Network/NG_NetworkScene.cpp - * \ingroup bgenet - */ - -#include -#include -#include - -#include "NG_NetworkScene.h" -#include "NG_NetworkDeviceInterface.h" -#include "NG_NetworkMessage.h" -#include "NG_NetworkObject.h" - -NG_NetworkScene::NG_NetworkScene(NG_NetworkDeviceInterface* nic) -{ - m_networkdevice = nic; -} - -NG_NetworkScene::~NG_NetworkScene() -{ - ClearAllMessageMaps(); -} - -/** - * progress one frame, handle all network traffic - */ -void NG_NetworkScene::proceed(double curtime) -{ - if (!m_networkdevice) return; - if (!m_networkdevice->IsOnline()) return; - - ClearAllMessageMaps(); - - // read all NetworkMessages from the device - vector messages = - m_networkdevice->RetrieveNetworkMessages(); - - vector::iterator mesit = messages.begin(); - for (; !(mesit == messages.end()); mesit++) { - NG_NetworkMessage* message = (*mesit); - vector* tmplist=NULL; - - vector** tmplistptr = - m_messagesByDestinationName[message->GetDestinationName()]; - // if there is already a vector of messages, append, else create - // a new vector and insert into map - if (!tmplistptr) { - tmplist = new vector; - m_messagesByDestinationName.insert(message->GetDestinationName(), - tmplist); - } else { - tmplist = *tmplistptr; - } - message->AddRef(); - tmplist->push_back(message); - tmplist = NULL; - - tmplistptr = m_messagesBySenderName[message->GetSenderName()]; - // if there is already a vector of messages, append, else create - // a new vector and insert into map - if (!tmplistptr) { - tmplist = new vector; - m_messagesBySenderName.insert(message->GetSenderName(), tmplist); - } else { - tmplist = *tmplistptr; - } - message->AddRef(); - tmplist->push_back(message); - tmplist = NULL; - - tmplistptr = m_messagesBySubject[message->GetSubject()]; - // if there is already a vector of messages, append, else create - // a new vector and insert into map - if (!tmplistptr) { - tmplist = new vector; - m_messagesBySubject.insert(message->GetSubject(), tmplist); - } else { - tmplist = *tmplistptr; - } - message->AddRef(); - tmplist->push_back(message); - tmplist = NULL; - } -} - -/** - * add a network object to the network scene - */ -void NG_NetworkScene::AddObject(NG_NetworkObject* object) -{ - if (! m_networkdevice->IsOnline()) return; - - const STR_String& name = object->GetName(); - m_networkObjects.insert(name, object); -} - -/** - * remove a network object from the network scene - */ -void NG_NetworkScene::RemoveObject(NG_NetworkObject* object) -{ - if (! m_networkdevice->IsOnline()) return; - - const STR_String& name = object->GetName(); - m_networkObjects.remove(name); -} - -/** - * remove all network scene objects at once - */ -void NG_NetworkScene::RemoveAllObjects() -{ - m_networkObjects.clear(); -} - -/** - * get a single network object given its name - */ -NG_NetworkObject* NG_NetworkScene::FindNetworkObject(const STR_String& objname) -{ - NG_NetworkObject *nwobj = NULL; - if (! m_networkdevice->IsOnline()) return nwobj; - - NG_NetworkObject **nwobjptr = m_networkObjects[objname]; - if (nwobjptr) { - nwobj = *nwobjptr; - } - - return nwobj; -} - -bool NG_NetworkScene::ConstraintsAreValid( - const STR_String& from, - const STR_String& subject, - NG_NetworkMessage* message) -{ - vector** fromlistptr = m_messagesBySenderName[from]; - vector** subjectlistptr = m_messagesBySubject[subject]; - - vector* fromlist = (fromlistptr ? *fromlistptr : NULL); - vector* subjectlist = (subjectlistptr ? *subjectlistptr : NULL); - - return ( - ( from.IsEmpty() || (!fromlist ? false : (!(std::find(fromlist->begin(), fromlist->end(), message) == fromlist->end()))) - ) && - ( subject.IsEmpty() || (!subjectlist ? false : (!(std::find(subjectlist->begin(), subjectlist->end(), message) == subjectlist->end()))) - )); -} - -vector NG_NetworkScene::FindMessages( - const STR_String& to, - const STR_String& from, - const STR_String& subject, - bool spamallowed) -{ - vector foundmessages; - bool notfound = false; - - // broad phase - notfound = ((to.IsEmpty() || spamallowed) ? notfound : m_messagesByDestinationName[to] == NULL); - if (!notfound) - notfound = (from.IsEmpty() ? notfound : m_messagesBySenderName[from] == NULL); - if (!notfound) - notfound = (subject.IsEmpty() ? notfound : m_messagesBySubject[subject] == NULL); - if (notfound) { - // it's definitely NOT in the scene, so stop looking - } else { // narrow phase - // possibly it's there, but maybe not (false hit) - if (to.IsEmpty()) { - // take all messages, and check other fields - MT_assert(!"objectnames that are empty are not valid, so make it a hobby project :)\n"); - } else { - //todo: find intersection of messages (that are in other 2 maps) - vector** tolistptr = m_messagesByDestinationName[to]; - if (tolistptr) { - vector* tolist = *tolistptr; - vector::iterator listit; - for (listit=tolist->begin();!(listit==tolist->end());listit++) { - NG_NetworkMessage* message = *listit; - if (ConstraintsAreValid(from, subject, message)) { - message->AddRef(); - foundmessages.push_back(message); - } - } - } - // TODO find intersection of messages (that are in other 2 maps) - if (spamallowed) { - tolistptr = m_messagesByDestinationName[""]; - if (tolistptr) { - vector* tolist = *tolistptr; - vector::iterator listit; - for (listit=tolist->begin();!(listit==tolist->end());listit++) { - NG_NetworkMessage* message = *listit; - if (ConstraintsAreValid(from, subject, message)) { - message->AddRef(); - foundmessages.push_back(message); - } - } - } - } - } - } - return foundmessages; -} - -void NG_NetworkScene::SendMessage( - const STR_String& to, - const STR_String& from, - const STR_String& subject, - const STR_String& message) -{ - NG_NetworkMessage* msg = new NG_NetworkMessage(to, from, subject, message); - m_networkdevice->SendNetworkMessage(msg); - msg->Release(); -} - -void NG_NetworkScene::ClearAllMessageMaps(void) -{ - ClearMessageMap(m_messagesByDestinationName); - ClearMessageMap(m_messagesBySenderName); - ClearMessageMap(m_messagesBySubject); -} - -void NG_NetworkScene::ClearMessageMap(TMessageMap& map) -{ - // Release the messages in the map - for (int i = 0; i < map.size(); i++) { - vector* msglist; - msglist = *(map.at(i)); - - // Iterate through the current vector and release all it's messages - vector::iterator msgit; - for (msgit = msglist->begin(); msgit != msglist->end(); msgit++) { - (*msgit)->Release(); - } - - // Delete the actual vector - delete (msglist); - } - - // Empty the map - map.clear(); -} - diff --git a/source/gameengine/Network/NG_NetworkScene.h b/source/gameengine/Network/NG_NetworkScene.h deleted file mode 100644 index e6233852ee2..00000000000 --- a/source/gameengine/Network/NG_NetworkScene.h +++ /dev/null @@ -1,118 +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 NG_NetworkScene.h - * \ingroup bgenet - * \brief NetworkSceneManagement generic class - */ -#ifndef __NG_NETWORKSCENE_H__ -#define __NG_NETWORKSCENE_H__ - -#include "CTR_Map.h" -#include "STR_HashedString.h" -#include - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -//MSVC defines SendMessage as a win api function, even though we aren't using it -#ifdef SendMessage -# undef SendMessage -#endif - -using namespace std; - -class NG_NetworkDeviceInterface; - -class NG_NetworkScene -{ - class NG_NetworkDeviceInterface *m_networkdevice; - CTR_Map m_networkObjects; - - // CTR_Maps used as a 'Bloom' filter - typedef CTR_Map* > TMessageMap; - TMessageMap m_messagesByDestinationName; - TMessageMap m_messagesBySenderName; - TMessageMap m_messagesBySubject; - -public: - NG_NetworkScene(NG_NetworkDeviceInterface *nic); - ~NG_NetworkScene(); - - /** - * progress one frame, handle all network traffic - */ - void proceed(double curtime); - - /** - * add a networkobject to the scene - */ - void AddObject(NG_NetworkObject* object); - - /** - * remove a networkobject to the scene - */ - void RemoveObject(NG_NetworkObject* object); - - /** - * remove all objects at once - */ - void RemoveAllObjects(); - - /** - * send a message (ascii text) over the network - */ - void SendMessage(const STR_String& to,const STR_String& from,const STR_String& subject,const STR_String& message); - - /** - * find an object by name - */ - NG_NetworkObject* FindNetworkObject(const STR_String& objname); - - bool ConstraintsAreValid(const STR_String& from,const STR_String& subject,class NG_NetworkMessage* message); - vector FindMessages(const STR_String& to,const STR_String& from,const STR_String& subject,bool spamallowed); - -protected: - /** - * Releases messages in message map members. - */ - void ClearAllMessageMaps(void); - - /** - * Releases messages for the given message map. - * \param map Message map with messages. - */ - void ClearMessageMap(TMessageMap& map); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:NG_NetworkScene") -#endif -}; - -#endif /* __NG_NETWORKSCENE_H__ */ diff --git a/source/gameengine/Physics/Bullet/CMakeLists.txt b/source/gameengine/Physics/Bullet/CMakeLists.txt deleted file mode 100644 index 8b00f1b47fa..00000000000 --- a/source/gameengine/Physics/Bullet/CMakeLists.txt +++ /dev/null @@ -1,73 +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 ***** - -# since this includes bullet we get errors from the headers too -remove_strict_flags() - -set(INC - . - ../common - ../../Converter - ../../Expressions - ../../GameLogic - ../../Ketsji - ../../Rasterizer - ../../SceneGraph - ../../../blender/blenkernel - ../../../blender/blenlib - ../../../blender/gpu - ../../../blender/makesdna - ../../../../intern/container - ../../../../intern/guardedalloc - ../../../../intern/glew-mx - ../../../../intern/string -) - -set(INC_SYS - ../../../../intern/moto/include - ${GLEW_INCLUDE_PATH} - ${PYTHON_INCLUDE_DIRS} -) - -set(SRC - CcdPhysicsEnvironment.cpp - CcdPhysicsController.cpp - CcdGraphicController.cpp - - CcdGraphicController.h - CcdPhysicsController.h - CcdPhysicsEnvironment.h -) - -if(WITH_BULLET) - list(APPEND INC_SYS - ${BULLET_INCLUDE_DIRS} - ) - add_definitions(-DWITH_BULLET) -endif() - -add_definitions(${GL_DEFINITIONS}) - -blender_add_lib(ge_phys_bullet "${SRC}" "${INC}" "${INC_SYS}") diff --git a/source/gameengine/Physics/Bullet/CcdGraphicController.cpp b/source/gameengine/Physics/Bullet/CcdGraphicController.cpp deleted file mode 100644 index 470a5431843..00000000000 --- a/source/gameengine/Physics/Bullet/CcdGraphicController.cpp +++ /dev/null @@ -1,152 +0,0 @@ -/** \file gameengine/Physics/Bullet/CcdGraphicController.cpp - * \ingroup physbullet - */ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#include "CcdPhysicsEnvironment.h" -#include "CcdGraphicController.h" -#include "btBulletDynamicsCommon.h" -#include "MT_Point3.h" - - -CcdGraphicController::CcdGraphicController (CcdPhysicsEnvironment* phyEnv, PHY_IMotionState* motionState) : - m_localAabbMin(0.f, 0.f, 0.f), - m_localAabbMax(0.f, 0.f, 0.f), - m_motionState(motionState), - m_phyEnv(phyEnv), - m_handle(NULL), - m_newClientInfo(NULL) -{ -} - -CcdGraphicController::~CcdGraphicController() -{ - if (m_phyEnv) - m_phyEnv->RemoveCcdGraphicController(this); - - if (m_motionState) - delete m_motionState; -} - -void CcdGraphicController::SetLocalAabb(const btVector3& aabbMin,const btVector3& aabbMax) -{ - m_localAabbMin = aabbMin; - m_localAabbMax = aabbMax; - SetGraphicTransform(); -} - -void CcdGraphicController::SetLocalAabb(const MT_Point3& aabbMin,const MT_Point3& aabbMax) -{ - m_localAabbMin.setValue(aabbMin[0],aabbMin[1],aabbMin[2]); - m_localAabbMax.setValue(aabbMax[0],aabbMax[1],aabbMax[2]); - SetGraphicTransform(); -} - -void CcdGraphicController::SetLocalAabb(const MT_Vector3& aabbMin,const MT_Vector3& aabbMax) -{ - m_localAabbMin.setValue(aabbMin[0],aabbMin[1],aabbMin[2]); - m_localAabbMax.setValue(aabbMax[0],aabbMax[1],aabbMax[2]); - SetGraphicTransform(); -} - -void CcdGraphicController::SetLocalAabb(const float* aabbMin,const float* aabbMax) -{ - m_localAabbMin.setValue(aabbMin[0],aabbMin[1],aabbMin[2]); - m_localAabbMax.setValue(aabbMax[0],aabbMax[1],aabbMax[2]); - SetGraphicTransform(); -} - -void CcdGraphicController::GetAabb(btVector3& aabbMin, btVector3& aabbMax) -{ - btVector3 pos; - btVector3 scale; - float ori[12]; - m_motionState->GetWorldPosition(pos.m_floats[0],pos.m_floats[1],pos.m_floats[2]); - m_motionState->GetWorldScaling(scale.m_floats[0],scale.m_floats[1],scale.m_floats[2]); - m_motionState->GetWorldOrientation(ori); - btMatrix3x3 rot(ori[0], ori[4], ori[8], - ori[1], ori[5], ori[9], - ori[2], ori[6], ori[10]); - - btVector3 localAabbMin = m_localAabbMin; - btVector3 localAabbMax = m_localAabbMax; - btVector3 tmpAabbMin = m_localAabbMin * scale; - btVector3 tmpAabbMax = m_localAabbMax * scale; - - localAabbMin[0] = (scale.getX() >= 0.0f) ? tmpAabbMin[0] : tmpAabbMax[0]; - localAabbMin[1] = (scale.getY() >= 0.0f) ? tmpAabbMin[1] : tmpAabbMax[1]; - localAabbMin[2] = (scale.getZ() >= 0.0f) ? tmpAabbMin[2] : tmpAabbMax[2]; - localAabbMax[0] = (scale.getX() <= 0.0f) ? tmpAabbMin[0] : tmpAabbMax[0]; - localAabbMax[1] = (scale.getY() <= 0.0f) ? tmpAabbMin[1] : tmpAabbMax[1]; - localAabbMax[2] = (scale.getZ() <= 0.0f) ? tmpAabbMin[2] : tmpAabbMax[2]; - - btVector3 localHalfExtents = btScalar(0.5f)*(localAabbMax-localAabbMin); - btVector3 localCenter = btScalar(0.5f)*(localAabbMax+localAabbMin); - - btMatrix3x3 abs_b = rot.absolute(); - btVector3 center = rot*localCenter + pos; - btVector3 extent = abs_b*localHalfExtents; - aabbMin = center - extent; - aabbMax = center + extent; -} - -bool CcdGraphicController::SetGraphicTransform() -{ - if (!m_handle) - return false; - btVector3 aabbMin; - btVector3 aabbMax; - GetAabb(aabbMin, aabbMax); - // update Aabb in broadphase - m_phyEnv->GetCullingTree()->setAabb(m_handle,aabbMin,aabbMax,NULL); - return true; -} - -PHY_IGraphicController* CcdGraphicController::GetReplica(class PHY_IMotionState* motionState) -{ - CcdGraphicController* replica = new CcdGraphicController(*this); - replica->m_motionState = motionState; - replica->m_newClientInfo = NULL; - replica->m_handle = NULL; - // don't add the graphic controller now: work around a bug in Bullet with rescaling, - // (the scale of the controller is not yet defined). - //m_phyEnv->addCcdGraphicController(replica); - return replica; -} - -void CcdGraphicController::SetPhysicsEnvironment(class PHY_IPhysicsEnvironment* env) -{ - CcdPhysicsEnvironment* phyEnv = static_cast(env); - /* Updates the m_phyEnv's m_cullingTree & m_cullingCache */ - if (GetBroadphaseHandle()) { - /* insert into the new physics scene */ - Activate(false); - m_phyEnv= phyEnv; - Activate(true); - } - else { - m_phyEnv= phyEnv; - } -} - -void CcdGraphicController::Activate(bool active) -{ - if (active) - m_phyEnv->AddCcdGraphicController(this); - else - m_phyEnv->RemoveCcdGraphicController(this); - -} diff --git a/source/gameengine/Physics/Bullet/CcdGraphicController.h b/source/gameengine/Physics/Bullet/CcdGraphicController.h deleted file mode 100644 index e76ad86301e..00000000000 --- a/source/gameengine/Physics/Bullet/CcdGraphicController.h +++ /dev/null @@ -1,90 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -/** \file CcdGraphicController.h - * \ingroup physbullet - */ - - -#ifndef __CCDGRAPHICCONTROLLER_H__ -#define __CCDGRAPHICCONTROLLER_H__ - -#include "PHY_IGraphicController.h" - -#include "btBulletDynamicsCommon.h" -#include "LinearMath/btTransform.h" - -#include "PHY_IMotionState.h" -#include "MT_Point3.h" - -class CcdPhysicsEnvironment; -class btCollisionObject; - -///CcdGraphicController is a graphic object that supports view frustrum culling and occlusion -class CcdGraphicController : public PHY_IGraphicController -{ -public: - CcdGraphicController(CcdPhysicsEnvironment* phyEnv, PHY_IMotionState* motionState); - - virtual ~CcdGraphicController(); - - void SetLocalAabb(const btVector3& aabbMin,const btVector3& aabbMax); - void SetLocalAabb(const MT_Point3& aabbMin,const MT_Point3& aabbMax); - virtual void SetLocalAabb(const MT_Vector3& aabbMin,const MT_Vector3& aabbMax); - virtual void SetLocalAabb(const float aabbMin[3],const float aabbMax[3]); - - PHY_IMotionState* GetMotionState() { return m_motionState; } - void GetAabb(btVector3& aabbMin, btVector3& aabbMax); - - virtual void SetBroadphaseHandle(btBroadphaseProxy* handle) { m_handle = handle; } - virtual btBroadphaseProxy* GetBroadphaseHandle() { return m_handle; } - - virtual void SetPhysicsEnvironment(class PHY_IPhysicsEnvironment* env); - - //////////////////////////////////// - // PHY_IGraphicController interface - //////////////////////////////////// - - /** - * Updates the Aabb based on the motion state - */ - virtual bool SetGraphicTransform(); - /** - * Add/remove to environment - */ - virtual void Activate(bool active); - - // client info for culling - virtual void* GetNewClientInfo() { return m_newClientInfo; } - virtual void SetNewClientInfo(void* clientinfo) { m_newClientInfo = clientinfo; } - virtual PHY_IGraphicController* GetReplica(class PHY_IMotionState* motionstate); - -private: - // unscaled aabb corner - btVector3 m_localAabbMin; - btVector3 m_localAabbMax; - - PHY_IMotionState* m_motionState; - CcdPhysicsEnvironment* m_phyEnv; - btBroadphaseProxy* m_handle; - void* m_newClientInfo; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:CcdGraphicController") -#endif -}; - -#endif /* BULLET2_PHYSICSCONTROLLER_H */ diff --git a/source/gameengine/Physics/Bullet/CcdPhysicsController.cpp b/source/gameengine/Physics/Bullet/CcdPhysicsController.cpp deleted file mode 100644 index b3cee944880..00000000000 --- a/source/gameengine/Physics/Bullet/CcdPhysicsController.cpp +++ /dev/null @@ -1,2668 +0,0 @@ -/** \file gameengine/Physics/Bullet/CcdPhysicsController.cpp - * \ingroup physbullet - */ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef WIN32 -#include -#endif - -#include "CcdPhysicsController.h" -#include "btBulletDynamicsCommon.h" -#include "BulletCollision/CollisionDispatch/btGhostObject.h" -#include "BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.h" -#include "BulletCollision/CollisionShapes/btTriangleIndexVertexArray.h" - -#include "PHY_IMotionState.h" -#include "CcdPhysicsEnvironment.h" -#include "RAS_MeshObject.h" -#include "RAS_Polygon.h" -#include "RAS_Deformer.h" -#include "KX_GameObject.h" - -#include "BulletSoftBody/btSoftBody.h" -#include "BulletSoftBody/btSoftBodyInternals.h" -#include "BulletSoftBody/btSoftBodyHelpers.h" -#include "LinearMath/btConvexHull.h" -#include "BulletCollision/Gimpact/btGImpactShape.h" - -#include "BulletSoftBody/btSoftRigidDynamicsWorld.h" - -#include "DNA_mesh_types.h" -#include "DNA_meshdata_types.h" - -extern "C"{ - #include "BLI_utildefines.h" - #include "BKE_cdderivedmesh.h" -} - - -class BP_Proxy; - -///todo: fill all the empty CcdPhysicsController methods, hook them up to the btRigidBody class - -//'temporarily' global variables -//float gDeactivationTime = 2.f; -//bool gDisableDeactivation = false; -extern float gDeactivationTime; -extern bool gDisableDeactivation; - - -float gLinearSleepingTreshold; -float gAngularSleepingTreshold; - -BlenderBulletCharacterController::BlenderBulletCharacterController(btMotionState *motionState, btPairCachingGhostObject *ghost, btConvexShape* shape, float stepHeight) - : btKinematicCharacterController(ghost,shape,stepHeight,2), - m_motionState(motionState), - m_jumps(0), - m_maxJumps(1) -{ -} - -void BlenderBulletCharacterController::updateAction(btCollisionWorld *collisionWorld, btScalar dt) -{ - if (onGround()) - m_jumps = 0; - - btKinematicCharacterController::updateAction(collisionWorld,dt); - m_motionState->setWorldTransform(getGhostObject()->getWorldTransform()); -} - -unsigned char BlenderBulletCharacterController::getMaxJumps() const -{ - return m_maxJumps; -} - -void BlenderBulletCharacterController::setMaxJumps(unsigned char maxJumps) -{ - m_maxJumps = maxJumps; -} - -unsigned char BlenderBulletCharacterController::getJumpCount() const -{ - return m_jumps; -} - -bool BlenderBulletCharacterController::canJump() const -{ - return (onGround() && m_maxJumps > 0) || m_jumps < m_maxJumps; -} - -void BlenderBulletCharacterController::jump() -{ - if (!canJump()) - return; - - m_verticalVelocity = m_jumpSpeed; - m_wasJumping = true; - m_jumps++; -} - -const btVector3& BlenderBulletCharacterController::getWalkDirection() -{ - return m_walkDirection; -} - -bool CleanPairCallback::processOverlap(btBroadphasePair &pair) -{ - if ((pair.m_pProxy0 == m_cleanProxy) || (pair.m_pProxy1 == m_cleanProxy)) { - m_pairCache->cleanOverlappingPair(pair, m_dispatcher); - CcdPhysicsController *ctrl0 = (CcdPhysicsController*)(((btCollisionObject*)pair.m_pProxy0->m_clientObject)->getUserPointer()); - CcdPhysicsController *ctrl1 = (CcdPhysicsController*)(((btCollisionObject*)pair.m_pProxy1->m_clientObject)->getUserPointer()); - ctrl0->GetCollisionObject()->activate(false); - ctrl1->GetCollisionObject()->activate(false); - } - return false; -} - -CcdPhysicsController::CcdPhysicsController (const CcdConstructionInfo& ci) -:m_cci(ci) -{ - m_prototypeTransformInitialized = false; - m_softbodyMappingDone = false; - m_collisionDelay = 0; - m_newClientInfo = 0; - m_registerCount = 0; - m_softBodyTransformInitialized = false; - m_parentCtrl = 0; - // copy pointers locally to allow smart release - m_MotionState = ci.m_MotionState; - m_collisionShape = ci.m_collisionShape; - // apply scaling before creating rigid body - m_collisionShape->setLocalScaling(m_cci.m_scaling); - if (m_cci.m_mass) - m_collisionShape->calculateLocalInertia(m_cci.m_mass, m_cci.m_localInertiaTensor); - // shape info is shared, increment ref count - m_shapeInfo = ci.m_shapeInfo; - if (m_shapeInfo) - m_shapeInfo->AddRef(); - - m_bulletChildShape = NULL; - - m_bulletMotionState = 0; - m_characterController = 0; - m_savedCollisionFlags = 0; - m_savedCollisionFilterGroup = 0; - m_savedCollisionFilterMask = 0; - m_savedMass = 0.0f; - m_savedDyna = false; - m_suspended = false; - - CreateRigidbody(); -} - -void CcdPhysicsController::addCcdConstraintRef(btTypedConstraint* c) -{ - int index = m_ccdConstraintRefs.findLinearSearch(c); - if (index == m_ccdConstraintRefs.size()) - m_ccdConstraintRefs.push_back(c); -} - -void CcdPhysicsController::removeCcdConstraintRef(btTypedConstraint* c) -{ - m_ccdConstraintRefs.remove(c); -} - -btTypedConstraint* CcdPhysicsController::getCcdConstraintRef(int index) -{ - return m_ccdConstraintRefs[index]; -} - -int CcdPhysicsController::getNumCcdConstraintRefs() const -{ - return m_ccdConstraintRefs.size(); -} - -btTransform& CcdPhysicsController::GetTransformFromMotionState(PHY_IMotionState* motionState) -{ - static btTransform trans; - btVector3 tmp; - motionState->GetWorldPosition(tmp.m_floats[0], tmp.m_floats[1], tmp.m_floats[2]); - trans.setOrigin(tmp); - - float ori[12]; - motionState->GetWorldOrientation(ori); - trans.getBasis().setFromOpenGLSubMatrix(ori); - //btQuaternion orn; - //motionState->getWorldOrientation(orn[0],orn[1],orn[2],orn[3]); - //trans.setRotation(orn); - return trans; - -} - -class BlenderBulletMotionState : public btMotionState -{ - PHY_IMotionState* m_blenderMotionState; - -public: - - BlenderBulletMotionState(PHY_IMotionState* bms) - :m_blenderMotionState(bms) - { - - } - - void getWorldTransform(btTransform& worldTrans ) const - { - btVector3 pos; - float ori[12]; - - m_blenderMotionState->GetWorldPosition(pos.m_floats[0],pos.m_floats[1],pos.m_floats[2]); - m_blenderMotionState->GetWorldOrientation(ori); - worldTrans.setOrigin(pos); - worldTrans.getBasis().setFromOpenGLSubMatrix(ori); - } - - void setWorldTransform(const btTransform& worldTrans) - { - m_blenderMotionState->SetWorldPosition(worldTrans.getOrigin().getX(),worldTrans.getOrigin().getY(),worldTrans.getOrigin().getZ()); - btQuaternion rotQuat = worldTrans.getRotation(); - m_blenderMotionState->SetWorldOrientation(rotQuat[0],rotQuat[1],rotQuat[2],rotQuat[3]); - m_blenderMotionState->CalculateWorldTransformations(); - } - -}; - -btRigidBody* CcdPhysicsController::GetRigidBody() -{ - return btRigidBody::upcast(m_object); -} -const btRigidBody* CcdPhysicsController::GetRigidBody() const -{ - return btRigidBody::upcast(m_object); -} - -btCollisionObject* CcdPhysicsController::GetCollisionObject() -{ - return m_object; -} -btSoftBody* CcdPhysicsController::GetSoftBody() -{ - return btSoftBody::upcast(m_object); -} -btKinematicCharacterController* CcdPhysicsController::GetCharacterController() -{ - return m_characterController; -} - -#include "BulletSoftBody/btSoftBodyHelpers.h" - - -bool CcdPhysicsController::CreateSoftbody() -{ - int shapeType = m_cci.m_collisionShape ? m_cci.m_collisionShape->getShapeType() : 0; - - //disable soft body until first sneak preview is ready - if (!m_cci.m_bSoft || !m_cci.m_collisionShape || - ((shapeType != CONVEX_HULL_SHAPE_PROXYTYPE)&& - (shapeType != TRIANGLE_MESH_SHAPE_PROXYTYPE) && - (shapeType != SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE))) - { - return false; - } - - btRigidBody::btRigidBodyConstructionInfo rbci(m_cci.m_mass,m_bulletMotionState,m_collisionShape,m_cci.m_localInertiaTensor * m_cci.m_inertiaFactor); - rbci.m_linearDamping = m_cci.m_linearDamping; - rbci.m_angularDamping = m_cci.m_angularDamping; - rbci.m_friction = m_cci.m_friction; - rbci.m_restitution = m_cci.m_restitution; - - btVector3 p(0.0f,0.0f,0.0f);// = getOrigin(); - //btSoftBody* psb=btSoftBodyHelpers::CreateRope(worldInfo, btVector3(-10,0,i*0.25),btVector3(10,0,i*0.25), 16,1+2); - btSoftBody* psb = 0; - btSoftBodyWorldInfo& worldInfo = m_cci.m_physicsEnv->GetDynamicsWorld()->getWorldInfo(); - - if (m_cci.m_collisionShape->getShapeType() == CONVEX_HULL_SHAPE_PROXYTYPE) { - btConvexHullShape* convexHull = (btConvexHullShape* )m_cci.m_collisionShape; - { - int nvertices = convexHull->getNumPoints(); - const btVector3* vertices = convexHull->getPoints(); - - HullDesc hdsc(QF_TRIANGLES,nvertices,vertices); - HullResult hres; - HullLibrary hlib; /*??*/ - hdsc.mMaxVertices=nvertices; - hlib.CreateConvexHull(hdsc,hres); - - psb = new btSoftBody(&worldInfo, (int)hres.mNumOutputVertices, - &hres.m_OutputVertices[0], 0); - for (int i = 0; i < (int)hres.mNumFaces; ++i) { - const unsigned int idx[3] = {hres.m_Indices[i * 3 + 0], - hres.m_Indices[i * 3 + 1], - hres.m_Indices[i * 3 + 2]}; - if (idx[0] < idx[1]) psb->appendLink(idx[0], idx[1]); - if (idx[1] < idx[2]) psb->appendLink(idx[1], idx[2]); - if (idx[2] < idx[0]) psb->appendLink(idx[2], idx[0]); - psb->appendFace(idx[0], idx[1], idx[2]); - } - hlib.ReleaseResult(hres); - } - } - else { - int numtris = 0; - if (m_cci.m_collisionShape->getShapeType() ==SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE) - { - btScaledBvhTriangleMeshShape* scaledtrimeshshape = (btScaledBvhTriangleMeshShape*) m_cci.m_collisionShape; - btBvhTriangleMeshShape* trimeshshape = scaledtrimeshshape->getChildShape(); - - ///only deal with meshes that have 1 sub part/component, for now - if (trimeshshape->getMeshInterface()->getNumSubParts()==1) - { - unsigned char* vertexBase; - btScalar* scaledVertexBase; - btVector3 localScaling; - PHY_ScalarType vertexType; - int numverts; - int vertexstride; - unsigned char* indexbase; - int indexstride; - PHY_ScalarType indexType; - trimeshshape->getMeshInterface()->getLockedVertexIndexBase(&vertexBase,numverts,vertexType,vertexstride,&indexbase,indexstride,numtris,indexType); - localScaling = scaledtrimeshshape->getLocalScaling(); - scaledVertexBase = new btScalar[numverts*3]; - for (int i=0; igetMeshInterface()->getNumSubParts()==1) - { - unsigned char* vertexBase; - PHY_ScalarType vertexType; - int numverts; - int vertexstride; - unsigned char* indexbase; - int indexstride; - PHY_ScalarType indexType; - trimeshshape->getMeshInterface()->getLockedVertexIndexBase(&vertexBase,numverts,vertexType,vertexstride,&indexbase,indexstride,numtris,indexType); - - psb = btSoftBodyHelpers::CreateFromTriMesh(worldInfo,(const btScalar*)vertexBase,(const int*)indexbase,numtris,false); - } - } - // store face tag so that we can find our original face when doing ray casting - btSoftBody::Face* ft; - int i; - for (i=0, ft=&psb->m_faces[0]; im_tag = (void*)((uintptr_t)(i+1)); - } - } - if (m_cci.m_margin > 0.f) - { - psb->getCollisionShape()->setMargin(m_cci.m_margin); - psb->updateBounds(); - } - m_object = psb; - - //btSoftBody::Material* pm=psb->appendMaterial(); - btSoftBody::Material* pm=psb->m_materials[0]; - pm->m_kLST = m_cci.m_soft_linStiff; - pm->m_kAST = m_cci.m_soft_angStiff; - pm->m_kVST = m_cci.m_soft_volume; - psb->m_cfg.collisions = 0; - - if (m_cci.m_soft_collisionflags & CCD_BSB_COL_CL_RS) - { - psb->m_cfg.collisions += btSoftBody::fCollision::CL_RS; - } else - { - psb->m_cfg.collisions += btSoftBody::fCollision::SDF_RS; - } - if (m_cci.m_soft_collisionflags & CCD_BSB_COL_CL_SS) - { - psb->m_cfg.collisions += btSoftBody::fCollision::CL_SS; - } else - { - psb->m_cfg.collisions += btSoftBody::fCollision::VF_SS; - } - - - psb->m_cfg.kSRHR_CL = m_cci.m_soft_kSRHR_CL; /* Soft vs rigid hardness [0,1] (cluster only) */ - psb->m_cfg.kSKHR_CL = m_cci.m_soft_kSKHR_CL; /* Soft vs kinetic hardness [0,1] (cluster only) */ - psb->m_cfg.kSSHR_CL = m_cci.m_soft_kSSHR_CL; /* Soft vs soft hardness [0,1] (cluster only) */ - psb->m_cfg.kSR_SPLT_CL = m_cci.m_soft_kSR_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */ - - psb->m_cfg.kSK_SPLT_CL = m_cci.m_soft_kSK_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */ - psb->m_cfg.kSS_SPLT_CL = m_cci.m_soft_kSS_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */ - psb->m_cfg.kVCF = m_cci.m_soft_kVCF; /* Velocities correction factor (Baumgarte) */ - psb->m_cfg.kDP = m_cci.m_soft_kDP; /* Damping coefficient [0,1] */ - - psb->m_cfg.kDG = m_cci.m_soft_kDG; /* Drag coefficient [0,+inf] */ - psb->m_cfg.kLF = m_cci.m_soft_kLF; /* Lift coefficient [0,+inf] */ - psb->m_cfg.kPR = m_cci.m_soft_kPR; /* Pressure coefficient [-inf,+inf] */ - psb->m_cfg.kVC = m_cci.m_soft_kVC; /* Volume conversation coefficient [0,+inf] */ - - psb->m_cfg.kDF = m_cci.m_soft_kDF; /* Dynamic friction coefficient [0,1] */ - psb->m_cfg.kMT = m_cci.m_soft_kMT; /* Pose matching coefficient [0,1] */ - psb->m_cfg.kCHR = m_cci.m_soft_kCHR; /* Rigid contacts hardness [0,1] */ - psb->m_cfg.kKHR = m_cci.m_soft_kKHR; /* Kinetic contacts hardness [0,1] */ - - psb->m_cfg.kSHR = m_cci.m_soft_kSHR; /* Soft contacts hardness [0,1] */ - psb->m_cfg.kAHR = m_cci.m_soft_kAHR; /* Anchors hardness [0,1] */ - - if (m_cci.m_gamesoftFlag & CCD_BSB_BENDING_CONSTRAINTS)//OB_SB_GOAL) - { - psb->generateBendingConstraints(2,pm); - } - - psb->m_cfg.piterations = m_cci.m_soft_piterations; - psb->m_cfg.viterations = m_cci.m_soft_viterations; - psb->m_cfg.diterations = m_cci.m_soft_diterations; - psb->m_cfg.citerations = m_cci.m_soft_citerations; - - if (m_cci.m_gamesoftFlag & CCD_BSB_SHAPE_MATCHING)//OB_SB_GOAL) - { - psb->setPose(false,true);// - } else - { - psb->setPose(true,false); - } - - psb->randomizeConstraints(); - - if (m_cci.m_soft_collisionflags & (CCD_BSB_COL_CL_RS+CCD_BSB_COL_CL_SS)) - { - psb->generateClusters(m_cci.m_soft_numclusteriterations); - } - - psb->setTotalMass(m_cci.m_mass); - - psb->setCollisionFlags(0); - - ///create a mapping between graphics mesh vertices and soft body vertices - { - RAS_MeshObject* rasMesh= GetShapeInfo()->GetMesh(); - - if (rasMesh && !m_softbodyMappingDone) - { - //printf("apply\n"); - RAS_MeshSlot::iterator it; - RAS_MeshMaterial *mmat; - RAS_MeshSlot *slot; - size_t i; - - //for each material - for (int m=0;mNumMaterials();m++) - { - mmat = rasMesh->GetMeshMaterial(m); - - slot = mmat->m_baseslot; - for (slot->begin(it); !slot->end(it); slot->next(it)) - { - int index = 0; - for (i=it.startvertex; isetSoftBodyIndex(0); - btScalar maxDistSqr = 1e30; - btSoftBody::tNodeArray& nodes(psb->m_nodes); - btVector3 xyz = btVector3(vertex->getXYZ()[0],vertex->getXYZ()[1],vertex->getXYZ()[2]); - for (int n=0;nsetSoftBodyIndex(n); - } - } - } - } - } - } - } - m_softbodyMappingDone = true; - - btTransform startTrans; - rbci.m_motionState->getWorldTransform(startTrans); - - m_MotionState->SetWorldPosition(startTrans.getOrigin().getX(),startTrans.getOrigin().getY(),startTrans.getOrigin().getZ()); - m_MotionState->SetWorldOrientation(0,0,0,1); - - if (!m_prototypeTransformInitialized) - { - m_prototypeTransformInitialized = true; - m_softBodyTransformInitialized = true; - psb->transform(startTrans); - } - m_object->setCollisionFlags(m_object->getCollisionFlags() | m_cci.m_collisionFlags); - if (m_cci.m_do_anisotropic) - m_object->setAnisotropicFriction(m_cci.m_anisotropicFriction); - return true; -} - -bool CcdPhysicsController::CreateCharacterController() -{ - if (!m_cci.m_bCharacter) - return false; - - m_object = new btPairCachingGhostObject(); - m_object->setCollisionShape(m_collisionShape); - m_object->setCollisionFlags(btCollisionObject::CF_CHARACTER_OBJECT); - - btTransform trans; - m_bulletMotionState->getWorldTransform(trans); - m_object->setWorldTransform(trans); - - m_characterController = new BlenderBulletCharacterController(m_bulletMotionState,(btPairCachingGhostObject*)m_object,(btConvexShape*)m_collisionShape,m_cci.m_stepHeight); - - m_characterController->setJumpSpeed(m_cci.m_jumpSpeed); - m_characterController->setFallSpeed(m_cci.m_fallSpeed); - m_characterController->setMaxJumps(m_cci.m_maxJumps); - - return true; -} - -void CcdPhysicsController::CreateRigidbody() -{ - - //btTransform trans = GetTransformFromMotionState(m_MotionState); - m_bulletMotionState = new BlenderBulletMotionState(m_MotionState); - - ///either create a btCollisionObject, btRigidBody or btSoftBody - if (CreateSoftbody() || CreateCharacterController()) - // soft body created, done - return; - - //create a rgid collision object - btRigidBody::btRigidBodyConstructionInfo rbci(m_cci.m_mass,m_bulletMotionState,m_collisionShape,m_cci.m_localInertiaTensor * m_cci.m_inertiaFactor); - rbci.m_linearDamping = m_cci.m_linearDamping; - rbci.m_angularDamping = m_cci.m_angularDamping; - rbci.m_friction = m_cci.m_friction; - rbci.m_restitution = m_cci.m_restitution; - m_object = new btRigidBody(rbci); - - // - // init the rigidbody properly - // - - //setMassProps this also sets collisionFlags - //convert collision flags! - //special case: a near/radar sensor controller should not be defined static or it will - //generate loads of static-static collision messages on the console - if (m_cci.m_bSensor) - { - // reset the flags that have been set so far - GetCollisionObject()->setCollisionFlags(0); - // sensor must never go to sleep: they need to detect continously - GetCollisionObject()->setActivationState(DISABLE_DEACTIVATION); - } - GetCollisionObject()->setCollisionFlags(m_object->getCollisionFlags() | m_cci.m_collisionFlags); - btRigidBody* body = GetRigidBody(); - - if (body) - { - body->setGravity( m_cci.m_gravity); - body->setDamping(m_cci.m_linearDamping, m_cci.m_angularDamping); - - if (!m_cci.m_bRigid) - { - body->setAngularFactor(0.f); - } - // use bullet's default contact processing theshold, blender's old default of 1 is too small here. - // if there's really a need to change this, it should be exposed in the ui first. -// body->setContactProcessingThreshold(m_cci.m_contactProcessingThreshold); - body->setSleepingThresholds(gLinearSleepingTreshold, gAngularSleepingTreshold); - - } - if (m_object && m_cci.m_do_anisotropic) - { - m_object->setAnisotropicFriction(m_cci.m_anisotropicFriction); - } - -} - -static void DeleteBulletShape(btCollisionShape* shape, bool free) -{ - if (shape->getShapeType() == SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE) { - /* If we use Bullet scaled shape (btScaledBvhTriangleMeshShape) we have to - * free the child of the unscaled shape (btTriangleMeshShape) here. - */ - btTriangleMeshShape *meshShape = ((btScaledBvhTriangleMeshShape *)shape)->getChildShape(); - if (meshShape) - delete meshShape; - } - if (free) { - delete shape; - } -} - -bool CcdPhysicsController::DeleteControllerShape( ) -{ - if (m_collisionShape) - { - // collision shape is always unique to the controller, can delete it here - if (m_collisionShape->isCompound()) - { - // bullet does not delete the child shape, must do it here - btCompoundShape* compoundShape = (btCompoundShape*)m_collisionShape; - int numChild = compoundShape->getNumChildShapes(); - for (int i=numChild-1 ; i >= 0; i--) - { - btCollisionShape* childShape = compoundShape->getChildShape(i); - DeleteBulletShape(childShape, true); - } - } - DeleteBulletShape(m_collisionShape, true); - - return true; - } - - return false; -} - -bool CcdPhysicsController::ReplaceControllerShape(btCollisionShape *newShape) -{ - if (m_collisionShape) - DeleteControllerShape(); - - // If newShape is NULL it means to create a new Bullet shape. - if (!newShape) - newShape = m_shapeInfo->CreateBulletShape(m_cci.m_margin, m_cci.m_bGimpact, !m_cci.m_bSoft); - - m_object->setCollisionShape(newShape); - m_collisionShape = newShape; - m_cci.m_collisionShape = newShape; - - btSoftBody *softBody = GetSoftBody(); - if (softBody) { - btSoftRigidDynamicsWorld *world = GetPhysicsEnvironment()->GetDynamicsWorld(); - // remove the old softBody - world->removeSoftBody(softBody); - - // soft body must be recreated - delete m_object; - m_object = NULL; - // force complete reinitialization - m_softbodyMappingDone = false; - m_prototypeTransformInitialized = false; - m_softBodyTransformInitialized = false; - - CreateSoftbody(); - assert(m_object); - - btSoftBody *newSoftBody = GetSoftBody(); - // set the user - newSoftBody->setUserPointer(this); - // add the new softbody - world->addSoftBody(newSoftBody); - } - - return true; -} - -CcdPhysicsController::~CcdPhysicsController() -{ - //will be reference counted, due to sharing - if (m_cci.m_physicsEnv) - m_cci.m_physicsEnv->RemoveCcdPhysicsController(this); - - if (m_MotionState) - delete m_MotionState; - if (m_bulletMotionState) - delete m_bulletMotionState; - if (m_characterController) - delete m_characterController; - delete m_object; - - DeleteControllerShape(); - - if (m_shapeInfo) - { - m_shapeInfo->Release(); - } -} - -void CcdPhysicsController::SimulationTick(float timestep) -{ - btRigidBody *body = GetRigidBody(); - if (!body || body->isStaticObject()) - return; - - // Clamp linear velocity - if (m_cci.m_clamp_vel_max > 0.0f || m_cci.m_clamp_vel_min > 0.0f) { - const btVector3 &linvel = body->getLinearVelocity(); - btScalar len = linvel.length(); - - if (m_cci.m_clamp_vel_max > 0.0f && len > m_cci.m_clamp_vel_max) - body->setLinearVelocity(linvel * (m_cci.m_clamp_vel_max / len)); - else if (m_cci.m_clamp_vel_min > 0.0f && !btFuzzyZero(len) && len < m_cci.m_clamp_vel_min) - body->setLinearVelocity(linvel * (m_cci.m_clamp_vel_min / len)); - } - - // Clamp angular velocity - if (m_cci.m_clamp_angvel_max > 0.0f || m_cci.m_clamp_angvel_min > 0.0f) { - const btVector3 &angvel = body->getAngularVelocity(); - btScalar len = angvel.length(); - - if (m_cci.m_clamp_angvel_max > 0.0f && len > m_cci.m_clamp_angvel_max) - body->setAngularVelocity(angvel * (m_cci.m_clamp_angvel_max / len)); - else if (m_cci.m_clamp_angvel_min > 0.0f && !btFuzzyZero(len) && len < m_cci.m_clamp_angvel_min) - body->setAngularVelocity(angvel * (m_cci.m_clamp_angvel_min / len)); - } -} - - -/** - * SynchronizeMotionStates ynchronizes dynas, kinematic and deformable entities (and do 'late binding') - */ -bool CcdPhysicsController::SynchronizeMotionStates(float time) -{ - //sync non-static to motionstate, and static from motionstate (todo: add kinematic etc.) - - btSoftBody* sb = GetSoftBody(); - if (sb) - { - if (sb->m_pose.m_bframe) - { - btVector3 worldPos = sb->m_pose.m_com; - btQuaternion worldquat; - btMatrix3x3 trs = sb->m_pose.m_rot*sb->m_pose.m_scl; - trs.getRotation(worldquat); - m_MotionState->SetWorldPosition(worldPos[0],worldPos[1],worldPos[2]); - m_MotionState->SetWorldOrientation(worldquat[0],worldquat[1],worldquat[2],worldquat[3]); - } - else - { - btVector3 aabbMin,aabbMax; - sb->getAabb(aabbMin,aabbMax); - btVector3 worldPos = (aabbMax+aabbMin)*0.5f; - m_MotionState->SetWorldPosition(worldPos[0],worldPos[1],worldPos[2]); - } - m_MotionState->CalculateWorldTransformations(); - return true; - } - - btRigidBody* body = GetRigidBody(); - - if (body && !body->isStaticObject()) - { - const btTransform& xform = body->getCenterOfMassTransform(); - const btMatrix3x3& worldOri = xform.getBasis(); - const btVector3& worldPos = xform.getOrigin(); - float ori[12]; - worldOri.getOpenGLSubMatrix(ori); - m_MotionState->SetWorldOrientation(ori); - m_MotionState->SetWorldPosition(worldPos[0],worldPos[1],worldPos[2]); - m_MotionState->CalculateWorldTransformations(); - - float scale[3]; - m_MotionState->GetWorldScaling(scale[0],scale[1],scale[2]); - btVector3 scaling(scale[0],scale[1],scale[2]); - GetCollisionShape()->setLocalScaling(scaling); - } else - { - btVector3 worldPos; - btQuaternion worldquat; - -/* m_MotionState->getWorldPosition(worldPos[0],worldPos[1],worldPos[2]); - m_MotionState->getWorldOrientation(worldquat[0],worldquat[1],worldquat[2],worldquat[3]); - btTransform oldTrans = m_body->getCenterOfMassTransform(); - btTransform newTrans(worldquat,worldPos); - - SetCenterOfMassTransform(newTrans); - //need to keep track of previous position for friction effects... - - m_MotionState->calculateWorldTransformations(); -*/ - float scale[3]; - m_MotionState->GetWorldScaling(scale[0],scale[1],scale[2]); - btVector3 scaling(scale[0],scale[1],scale[2]); - GetCollisionShape()->setLocalScaling(scaling); - } - return true; - -} - - /** - * WriteMotionStateToDynamics synchronizes dynas, kinematic and deformable entities (and do 'late binding') - */ - -void CcdPhysicsController::WriteMotionStateToDynamics(bool nondynaonly) -{ - btTransform& xform = CcdPhysicsController::GetTransformFromMotionState(m_MotionState); - SetCenterOfMassTransform(xform); -} - -void CcdPhysicsController::WriteDynamicsToMotionState() -{ -} - // controller replication -void CcdPhysicsController::PostProcessReplica(class PHY_IMotionState* motionstate,class PHY_IPhysicsController* parentctrl) -{ - SetParentCtrl((CcdPhysicsController*)parentctrl); - m_softBodyTransformInitialized=false; - m_MotionState = motionstate; - m_registerCount = 0; - m_collisionShape = NULL; - - // Clear all old constraints. - m_ccdConstraintRefs.clear(); - - // always create a new shape to avoid scaling bug - if (m_shapeInfo) - { - m_shapeInfo->AddRef(); - m_collisionShape = m_shapeInfo->CreateBulletShape(m_cci.m_margin, m_cci.m_bGimpact, !m_cci.m_bSoft); - - if (m_collisionShape) - { - // new shape has no scaling, apply initial scaling - //m_collisionShape->setMargin(m_cci.m_margin); - m_collisionShape->setLocalScaling(m_cci.m_scaling); - - if (m_cci.m_mass) - m_collisionShape->calculateLocalInertia(m_cci.m_mass, m_cci.m_localInertiaTensor); - } - } - - // load some characterists that are not - btRigidBody* oldbody = GetRigidBody(); - m_object = 0; - CreateRigidbody(); - btRigidBody* body = GetRigidBody(); - if (body) - { - if (m_cci.m_mass) - { - body->setMassProps(m_cci.m_mass, m_cci.m_localInertiaTensor * m_cci.m_inertiaFactor); - } - - if (oldbody) - { - body->setLinearFactor(oldbody->getLinearFactor()); - body->setAngularFactor(oldbody->getAngularFactor()); - if (oldbody->getActivationState() == DISABLE_DEACTIVATION) - body->setActivationState(DISABLE_DEACTIVATION); - } - } - // sensor object are added when needed - if (!m_cci.m_bSensor) - m_cci.m_physicsEnv->AddCcdPhysicsController(this); - - -} - -void CcdPhysicsController::SetPhysicsEnvironment(class PHY_IPhysicsEnvironment *env) -{ - // can safely assume CCD environment - CcdPhysicsEnvironment *physicsEnv = static_cast(env); - - if (m_cci.m_physicsEnv != physicsEnv) - { - // since the environment is changing, we must also move the controler to the - // new environment. Note that we don't handle sensor explicitly: this - // function can be called on sensor but only when they are not registered - if (m_cci.m_physicsEnv->RemoveCcdPhysicsController(this)) - { - physicsEnv->AddCcdPhysicsController(this); - - // Set the object to be active so it can at least by evaluated once. - // This fixes issues with static objects not having their physics meshes - // in the right spot when lib loading. - this->GetCollisionObject()->setActivationState(ACTIVE_TAG); - } - m_cci.m_physicsEnv = physicsEnv; - } -} - -void CcdPhysicsController::SetCenterOfMassTransform(btTransform& xform) -{ - btRigidBody* body = GetRigidBody(); - if (body) - { - body->setCenterOfMassTransform(xform); - } else - { - //either collision object or soft body? - if (GetSoftBody()) - { - - } else - { - - if (m_object->isStaticOrKinematicObject()) - { - m_object->setInterpolationWorldTransform(m_object->getWorldTransform()); - } else - { - m_object->setInterpolationWorldTransform(xform); - } - m_object->setWorldTransform(xform); - } - } -} - - // kinematic methods -void CcdPhysicsController::RelativeTranslate(const MT_Vector3& dlocin,bool local) -{ - if (m_object) - { - m_object->activate(true); - if (m_object->isStaticObject()) - { - if (!m_cci.m_bSensor) - m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT); - // kinematic object should not set the transform, it disturbs the velocity interpolation - return; - } - - btVector3 dloc(dlocin.x(), dlocin.y(), dlocin.z()); - btTransform xform = m_object->getWorldTransform(); - - if (local) - dloc = xform.getBasis()*dloc; - - xform.setOrigin(xform.getOrigin() + dloc); - SetCenterOfMassTransform(xform); - } - -} - -void CcdPhysicsController::RelativeRotate(const MT_Matrix3x3& rotval,bool local) -{ - if (m_object) - { - m_object->activate(true); - if (m_object->isStaticObject()) - { - if (!m_cci.m_bSensor) - m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT); - // kinematic object should not set the transform, it disturbs the velocity interpolation - return; - } - - btMatrix3x3 drotmat(rotval[0].x(), rotval[0].y(), rotval[0].z(), - rotval[1].x(), rotval[1].y(), rotval[1].z(), - rotval[2].x(), rotval[2].y(), rotval[2].z()); - - - btMatrix3x3 currentOrn; - GetWorldOrientation(currentOrn); - - btTransform xform = m_object->getWorldTransform(); - - xform.setBasis(xform.getBasis()*(local ? - drotmat : (currentOrn.inverse() * drotmat * currentOrn))); - - SetCenterOfMassTransform(xform); - } -} - - -void CcdPhysicsController::GetWorldOrientation(btMatrix3x3& mat) -{ - float ori[12]; - m_MotionState->GetWorldOrientation(ori); - mat.setFromOpenGLSubMatrix(ori); -} - -MT_Matrix3x3 CcdPhysicsController::GetOrientation() -{ - btMatrix3x3 orn = m_object->getWorldTransform().getBasis(); - return MT_Matrix3x3(orn[0][0], orn[0][1], orn[0][2], orn[1][0], orn[1][1], orn[1][2], orn[2][0], orn[2][1], orn[2][2]); -} - -void CcdPhysicsController::SetOrientation(const MT_Matrix3x3& orn) -{ - btMatrix3x3 btmat(orn[0][0], orn[0][1], orn[0][2], orn[1][0], orn[1][1], orn[1][2], orn[2][0], orn[2][1], orn[2][2]); - SetWorldOrientation(btmat); -} - -void CcdPhysicsController::SetWorldOrientation(const btMatrix3x3& orn) -{ - if (m_object) - { - m_object->activate(true); - if (m_object->isStaticObject() && !m_cci.m_bSensor) - { - m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT); - } - // not required - //m_MotionState->setWorldOrientation(quatImag0,quatImag1,quatImag2,quatReal); - btTransform xform = m_object->getWorldTransform(); - xform.setBasis(orn); - SetCenterOfMassTransform(xform); - // not required - //m_bulletMotionState->setWorldTransform(xform); - //only once! - if (!m_softBodyTransformInitialized && GetSoftBody()) - { - m_softbodyStartTrans.setBasis(orn); - xform.setOrigin(m_softbodyStartTrans.getOrigin()); - GetSoftBody()->transform(xform); - m_softBodyTransformInitialized = true; - } - - } - -} - -void CcdPhysicsController::SetPosition(const MT_Vector3& pos) -{ - if (m_object) - { - m_object->activate(true); - if (m_object->isStaticObject()) - { - if (!m_cci.m_bSensor) - m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT); - // kinematic object should not set the transform, it disturbs the velocity interpolation - return; - } - // not required, this function is only used to update the physic controller - //m_MotionState->setWorldPosition(posX,posY,posZ); - btTransform xform = m_object->getWorldTransform(); - xform.setOrigin(btVector3(pos.x(), pos.y(), pos.z())); - SetCenterOfMassTransform(xform); - if (!m_softBodyTransformInitialized) - m_softbodyStartTrans.setOrigin(xform.getOrigin()); - // not required - //m_bulletMotionState->setWorldTransform(xform); - } -} - -void CcdPhysicsController::ForceWorldTransform(const btMatrix3x3& mat, const btVector3& pos) -{ - if (m_object) - { - btTransform& xform = m_object->getWorldTransform(); - xform.setBasis(mat); - xform.setOrigin(pos); - } -} - - -void CcdPhysicsController::ResolveCombinedVelocities(float linvelX,float linvelY,float linvelZ,float angVelX,float angVelY,float angVelZ) -{ -} - -void CcdPhysicsController::RefreshCollisions() -{ - // the object is in an inactive layer so it's useless to update it and can cause problems - if (!GetPhysicsEnvironment()->IsActiveCcdPhysicsController(this)) - return; - - btSoftRigidDynamicsWorld *dw = GetPhysicsEnvironment()->GetDynamicsWorld(); - btBroadphaseProxy *proxy = m_object->getBroadphaseHandle(); - btDispatcher *dispatcher = dw->getDispatcher(); - btOverlappingPairCache *pairCache = dw->getPairCache(); - - CleanPairCallback cleanPairs(proxy, pairCache, dispatcher); - pairCache->processAllOverlappingPairs(&cleanPairs, dispatcher); - - // Forcibly recreate the physics object - btBroadphaseProxy* handle = m_object->getBroadphaseHandle(); - GetPhysicsEnvironment()->UpdateCcdPhysicsController(this, GetMass(), m_object->getCollisionFlags(), handle->m_collisionFilterGroup, handle->m_collisionFilterMask); -} - -void CcdPhysicsController::SuspendDynamics(bool ghost) -{ - btRigidBody *body = GetRigidBody(); - if (body && !m_suspended && !GetConstructionInfo().m_bSensor && GetPhysicsEnvironment()->IsActiveCcdPhysicsController(this)) - { - btBroadphaseProxy* handle = body->getBroadphaseHandle(); - - m_savedCollisionFlags = body->getCollisionFlags(); - m_savedMass = GetMass(); - m_savedDyna = m_cci.m_bDyna; - m_savedCollisionFilterGroup = handle->m_collisionFilterGroup; - m_savedCollisionFilterMask = handle->m_collisionFilterMask; - m_suspended = true; - GetPhysicsEnvironment()->UpdateCcdPhysicsController(this, - 0.0f, - btCollisionObject::CF_STATIC_OBJECT|((ghost)?btCollisionObject::CF_NO_CONTACT_RESPONSE:(m_savedCollisionFlags&btCollisionObject::CF_NO_CONTACT_RESPONSE)), - btBroadphaseProxy::StaticFilter, - btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::StaticFilter); - m_cci.m_bDyna = false; - } -} - -void CcdPhysicsController::RestoreDynamics() -{ - btRigidBody *body = GetRigidBody(); - if (body && m_suspended && GetPhysicsEnvironment()->IsActiveCcdPhysicsController(this)) - { - // before make sure any position change that was done in this logic frame are accounted for - SetTransform(); - GetPhysicsEnvironment()->UpdateCcdPhysicsController(this, - m_savedMass, - m_savedCollisionFlags, - m_savedCollisionFilterGroup, - m_savedCollisionFilterMask); - body->activate(); - m_cci.m_bDyna = m_savedDyna; - m_suspended = false; - } -} - -void CcdPhysicsController::GetPosition(MT_Vector3& pos) const -{ - const btTransform& xform = m_object->getWorldTransform(); - pos[0] = xform.getOrigin().x(); - pos[1] = xform.getOrigin().y(); - pos[2] = xform.getOrigin().z(); -} - -void CcdPhysicsController::SetScaling(const MT_Vector3& scale) -{ - if (!btFuzzyZero(m_cci.m_scaling.x()-scale.x()) || - !btFuzzyZero(m_cci.m_scaling.y()-scale.y()) || - !btFuzzyZero(m_cci.m_scaling.z()-scale.z())) - { - m_cci.m_scaling = btVector3(scale.x(),scale.y(),scale.z()); - - if (m_object && m_object->getCollisionShape()) - { - m_object->activate(true); // without this, sleeping objects scale wont be applied in bullet if python changes the scale - Campbell. - m_object->getCollisionShape()->setLocalScaling(m_cci.m_scaling); - - //printf("no inertia recalc for fixed objects with mass=0\n"); - btRigidBody* body = GetRigidBody(); - if (body && m_cci.m_mass) - { - body->getCollisionShape()->calculateLocalInertia(m_cci.m_mass, m_cci.m_localInertiaTensor); - body->setMassProps(m_cci.m_mass, m_cci.m_localInertiaTensor * m_cci.m_inertiaFactor); - } - - } - } -} - -void CcdPhysicsController::SetTransform() -{ - btVector3 pos; - btVector3 scale; - float ori[12]; - m_MotionState->GetWorldPosition(pos.m_floats[0],pos.m_floats[1],pos.m_floats[2]); - m_MotionState->GetWorldScaling(scale.m_floats[0],scale.m_floats[1],scale.m_floats[2]); - m_MotionState->GetWorldOrientation(ori); - btMatrix3x3 rot(ori[0], ori[4], ori[8], - ori[1], ori[5], ori[9], - ori[2], ori[6], ori[10]); - ForceWorldTransform(rot, pos); - - if (!IsDynamic() && !GetConstructionInfo().m_bSensor && !GetCharacterController()) - { - btCollisionObject* object = GetRigidBody(); - object->setActivationState(ACTIVE_TAG); - object->setCollisionFlags(object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT); - } -} - -MT_Scalar CcdPhysicsController::GetMass() -{ - if (GetSoftBody()) - return GetSoftBody()->getTotalMass(); - - MT_Scalar invmass = 0.f; - if (GetRigidBody()) - invmass = GetRigidBody()->getInvMass(); - if (invmass) - return 1.f/invmass; - return 0.f; - -} - -void CcdPhysicsController::SetMass(MT_Scalar newmass) -{ - btRigidBody *body = GetRigidBody(); - if (body && !m_suspended && newmass>MT_EPSILON && GetMass()>MT_EPSILON) - { - btBroadphaseProxy* handle = body->getBroadphaseHandle(); - GetPhysicsEnvironment()->UpdateCcdPhysicsController(this, - newmass, - body->getCollisionFlags(), - handle->m_collisionFilterGroup, - handle->m_collisionFilterMask); - } -} - - // physics methods -void CcdPhysicsController::ApplyTorque(const MT_Vector3& torquein,bool local) -{ - btVector3 torque(torquein.x(),torquein.y(),torquein.z()); - btTransform xform = m_object->getWorldTransform(); - - - if (m_object && torque.length2() > (SIMD_EPSILON*SIMD_EPSILON)) - { - btRigidBody* body = GetRigidBody(); - m_object->activate(); - if (m_object->isStaticObject()) - { - if (!m_cci.m_bSensor) - m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT); - return; - } - if (local) - { - torque = xform.getBasis()*torque; - } - if (body) - { - if (m_cci.m_bRigid) - { - body->applyTorque(torque); - } - else - { - //workaround for incompatibility between 'DYNAMIC' game object, and angular factor - //a DYNAMIC object has some inconsistency: it has no angular effect due to collisions, but still has torque - const btVector3 angFac = body->getAngularFactor(); - btVector3 tmpFac(1,1,1); - body->setAngularFactor(tmpFac); - body->applyTorque(torque); - body->setAngularFactor(angFac); - } - } - } -} - -void CcdPhysicsController::ApplyForce(const MT_Vector3& forcein,bool local) -{ - btVector3 force(forcein.x(),forcein.y(),forcein.z()); - - - if (m_object && force.length2() > (SIMD_EPSILON*SIMD_EPSILON)) - { - m_object->activate(); - if (m_object->isStaticObject()) - { - if (!m_cci.m_bSensor) - m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT); - return; - } - btTransform xform = m_object->getWorldTransform(); - - if (local) - { - force = xform.getBasis()*force; - } - btRigidBody* body = GetRigidBody(); - if (body) - body->applyCentralForce(force); - btSoftBody* soft = GetSoftBody(); - if (soft) - { - // the force is applied on each node, must reduce it in the same extend - if (soft->m_nodes.size() > 0) - force /= soft->m_nodes.size(); - soft->addForce(force); - } - } -} -void CcdPhysicsController::SetAngularVelocity(const MT_Vector3& ang_vel,bool local) -{ - btVector3 angvel(ang_vel.x(),ang_vel.y(),ang_vel.z()); - - /* Refuse tiny tiny velocities, as they might cause instabilities. */ - float vel_squared = angvel.length2(); - if (vel_squared > 0 && vel_squared <= (SIMD_EPSILON*SIMD_EPSILON)) - angvel = btVector3(0, 0, 0); - - if (m_object) - { - m_object->activate(true); - if (m_object->isStaticObject()) - { - if (!m_cci.m_bSensor) - m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT); - return; - } - btTransform xform = m_object->getWorldTransform(); - if (local) - { - angvel = xform.getBasis()*angvel; - } - btRigidBody* body = GetRigidBody(); - if (body) - body->setAngularVelocity(angvel); - } - -} -void CcdPhysicsController::SetLinearVelocity(const MT_Vector3& lin_vel,bool local) -{ - btVector3 linVel(lin_vel.x(),lin_vel.y(),lin_vel.z()); - - /* Refuse tiny tiny velocities, as they might cause instabilities. */ - float vel_squared = linVel.length2(); - if (vel_squared > 0 && vel_squared <= (SIMD_EPSILON*SIMD_EPSILON)) - linVel = btVector3(0, 0, 0); - - if (m_object) - { - m_object->activate(true); - if (m_object->isStaticObject()) - { - if (!m_cci.m_bSensor) - m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT); - return; - } - - btSoftBody* soft = GetSoftBody(); - if (soft) - { - if (local) - { - linVel = m_softbodyStartTrans.getBasis()*linVel; - } - soft->setVelocity(linVel); - } else - { - btTransform xform = m_object->getWorldTransform(); - if (local) - { - linVel = xform.getBasis()*linVel; - } - btRigidBody* body = GetRigidBody(); - if (body) - body->setLinearVelocity(linVel); - } - } -} -void CcdPhysicsController::ApplyImpulse(const MT_Point3& attach, const MT_Vector3& impulsein, bool local) -{ - btVector3 pos; - btVector3 impulse(impulsein.x(), impulsein.y(), impulsein.z()); - - if (m_object && impulse.length2() > (SIMD_EPSILON*SIMD_EPSILON)) - { - m_object->activate(); - if (m_object->isStaticObject()) - { - if (!m_cci.m_bSensor) - m_object->setCollisionFlags(m_object->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT); - return; - } - - btTransform xform = m_object->getWorldTransform(); - - if (local) - { - pos = btVector3(attach.x(), attach.y(), attach.z()); - impulse = xform.getBasis() * impulse; - } - else { - /* If the point of impulse application is not equal to the object position - * then an angular momentum is generated in the object*/ - pos = btVector3(attach.x()-xform.getOrigin().x(), attach.y()-xform.getOrigin().y(), attach.z()-xform.getOrigin().z()); - } - - btRigidBody* body = GetRigidBody(); - if (body) - body->applyImpulse(impulse,pos); - - } - -} - -void CcdPhysicsController::Jump() -{ - if (m_object && m_characterController) - m_characterController->jump(); -} - -void CcdPhysicsController::SetActive(bool active) -{ -} - -float CcdPhysicsController::GetLinearDamping() const -{ - const btRigidBody* body = GetRigidBody(); - if (body) - return body->getLinearDamping(); - return 0; -} - -float CcdPhysicsController::GetAngularDamping() const -{ - const btRigidBody* body = GetRigidBody(); - if (body) - return body->getAngularDamping(); - return 0; -} - -void CcdPhysicsController::SetLinearDamping(float damping) -{ - SetDamping(damping, GetAngularDamping()); -} - -void CcdPhysicsController::SetAngularDamping(float damping) -{ - SetDamping(GetLinearDamping(), damping); -} - -void CcdPhysicsController::SetDamping(float linear, float angular) -{ - btRigidBody* body = GetRigidBody(); - if (!body) return; - - body->setDamping(linear, angular); -} - - - // reading out information from physics -MT_Vector3 CcdPhysicsController::GetLinearVelocity() -{ - btRigidBody* body = GetRigidBody(); - if (body) - { - const btVector3& linvel = body->getLinearVelocity(); - return MT_Vector3(linvel.x(), linvel.y(), linvel.z()); - } - - return MT_Vector3(0.f, 0.f, 0.f); -} - -MT_Vector3 CcdPhysicsController::GetAngularVelocity() -{ - btRigidBody* body = GetRigidBody(); - if (body) - { - const btVector3& angvel= body->getAngularVelocity(); - return MT_Vector3(angvel.x(), angvel.y(), angvel.z()); - } - - return MT_Vector3(0.f, 0.f, 0.f); -} - -MT_Vector3 CcdPhysicsController::GetVelocity(const MT_Point3 &posin) -{ - btVector3 pos(posin.x(), posin.y(), posin.z()); - btRigidBody* body = GetRigidBody(); - if (body) - { - btVector3 linvel = body->getVelocityInLocalPoint(pos); - return MT_Vector3(linvel.x(), linvel.y(), linvel.z()); - } - - return MT_Vector3(0.f, 0.f, 0.f); -} - -MT_Vector3 CcdPhysicsController::GetLocalInertia() -{ - MT_Vector3 inertia(0.f, 0.f, 0.f); - btVector3 inv_inertia; - if (GetRigidBody()) { - inv_inertia = GetRigidBody()->getInvInertiaDiagLocal(); - if (!btFuzzyZero(inv_inertia.getX()) && - !btFuzzyZero(inv_inertia.getY()) && - !btFuzzyZero(inv_inertia.getZ())) - inertia = MT_Vector3(1.f/inv_inertia.getX(), 1.f/inv_inertia.getY(), 1.f/inv_inertia.getZ()); - } - return inertia; -} - - // dyna's that are rigidbody are free in orientation, dyna's with non-rigidbody are restricted -void CcdPhysicsController::SetRigidBody(bool rigid) -{ - btRigidBody* body = GetRigidBody(); - if (body) - { - m_cci.m_bRigid = rigid; - if (!rigid) { - body->setAngularFactor(0.f); - body->setAngularVelocity(btVector3(0.f, 0.f, 0.f)); - } - else - body->setAngularFactor(m_cci.m_angularFactor); - } -} - - // clientinfo for raycasts for example -void* CcdPhysicsController::GetNewClientInfo() -{ - return m_newClientInfo; -} -void CcdPhysicsController::SetNewClientInfo(void* clientinfo) -{ - m_newClientInfo = clientinfo; - - if (m_cci.m_bSensor) - { - // use a different callback function for sensor object, - // bullet will not synchronize, we must do it explicitly - SG_Callbacks& callbacks = KX_GameObject::GetClientObject((KX_ClientObjectInfo*)clientinfo)->GetSGNode()->GetCallBackFunctions(); - callbacks.m_updatefunc = KX_GameObject::SynchronizeTransformFunc; - } -} - - -void CcdPhysicsController::UpdateDeactivation(float timeStep) -{ - btRigidBody* body = GetRigidBody(); - if (body) - { - body->updateDeactivation( timeStep); - } -} - -bool CcdPhysicsController::WantsSleeping() -{ - btRigidBody* body = GetRigidBody(); - if (body) - { - return body->wantsSleeping(); - } - //check it out - return true; -} -/* This function dynamically adds the collision shape of another controller to - * the current controller shape provided it is a compound shape. - * The idea is that dynamic parenting on a compound object will dynamically extend the shape - */ -void CcdPhysicsController::AddCompoundChild(PHY_IPhysicsController* child) -{ - if (child == NULL || !IsCompound()) - return; - // other controller must be a bullet controller too - // verify that body and shape exist and match - CcdPhysicsController* childCtrl = dynamic_cast(child); - btRigidBody* rootBody = GetRigidBody(); - btRigidBody* childBody = childCtrl->GetRigidBody(); - if (!rootBody || !childBody) - return; - const btCollisionShape* rootShape = rootBody->getCollisionShape(); - const btCollisionShape* childShape = childBody->getCollisionShape(); - if (!rootShape || - !childShape || - rootShape->getShapeType() != COMPOUND_SHAPE_PROXYTYPE) - return; - btCompoundShape* compoundShape = (btCompoundShape*)rootShape; - // compute relative transformation between parent and child - btTransform rootTrans; - btTransform childTrans; - rootBody->getMotionState()->getWorldTransform(rootTrans); - childBody->getMotionState()->getWorldTransform(childTrans); - btVector3 rootScale = rootShape->getLocalScaling(); - rootScale[0] = 1.0f/rootScale[0]; - rootScale[1] = 1.0f/rootScale[1]; - rootScale[2] = 1.0f/rootScale[2]; - // relative scale = child_scale/parent_scale - btVector3 relativeScale = childShape->getLocalScaling()*rootScale; - btMatrix3x3 rootRotInverse = rootTrans.getBasis().transpose(); - // relative pos = parent_rot^-1 * ((parent_pos-child_pos)/parent_scale) - btVector3 relativePos = rootRotInverse*((childTrans.getOrigin()-rootTrans.getOrigin())*rootScale); - // relative rot = parent_rot^-1 * child_rot - btMatrix3x3 relativeRot = rootRotInverse*childTrans.getBasis(); - // create a proxy shape info to store the transformation - CcdShapeConstructionInfo* proxyShapeInfo = new CcdShapeConstructionInfo(); - // store the transformation to this object shapeinfo - proxyShapeInfo->m_childTrans.setOrigin(relativePos); - proxyShapeInfo->m_childTrans.setBasis(relativeRot); - proxyShapeInfo->m_childScale.setValue(relativeScale[0], relativeScale[1], relativeScale[2]); - // we will need this to make sure that we remove the right proxy later when unparenting - proxyShapeInfo->m_userData = childCtrl; - proxyShapeInfo->SetProxy(childCtrl->GetShapeInfo()->AddRef()); - // add to parent compound shapeinfo (increments ref count) - GetShapeInfo()->AddShape(proxyShapeInfo); - // create new bullet collision shape from the object shapeinfo and set scaling - btCollisionShape* newChildShape = proxyShapeInfo->CreateBulletShape(childCtrl->GetMargin(), childCtrl->GetConstructionInfo().m_bGimpact, true); - newChildShape->setLocalScaling(relativeScale); - // add bullet collision shape to parent compound collision shape - compoundShape->addChildShape(proxyShapeInfo->m_childTrans,newChildShape); - // proxyShapeInfo is not needed anymore, release it - proxyShapeInfo->Release(); - // remember we created this shape - childCtrl->m_bulletChildShape = newChildShape; - // recompute inertia of parent - if (!rootBody->isStaticOrKinematicObject()) - { - btVector3 localInertia; - float mass = 1.f/rootBody->getInvMass(); - compoundShape->calculateLocalInertia(mass,localInertia); - rootBody->setMassProps(mass,localInertia); - } - // must update the broadphase cache, - GetPhysicsEnvironment()->RefreshCcdPhysicsController(this); - // remove the children - GetPhysicsEnvironment()->RemoveCcdPhysicsController(childCtrl); -} - -/* Reverse function of the above, it will remove a shape from a compound shape - * provided that the former was added to the later using AddCompoundChild() - */ -void CcdPhysicsController::RemoveCompoundChild(PHY_IPhysicsController* child) -{ - if (child == NULL || !IsCompound()) - return; - // other controller must be a bullet controller too - // verify that body and shape exist and match - CcdPhysicsController* childCtrl = dynamic_cast(child); - btRigidBody* rootBody = GetRigidBody(); - btRigidBody* childBody = childCtrl->GetRigidBody(); - if (!rootBody || !childBody) - return; - const btCollisionShape* rootShape = rootBody->getCollisionShape(); - if (!rootShape || - rootShape->getShapeType() != COMPOUND_SHAPE_PROXYTYPE) - return; - btCompoundShape* compoundShape = (btCompoundShape*)rootShape; - // retrieve the shapeInfo - CcdShapeConstructionInfo* childShapeInfo = childCtrl->GetShapeInfo(); - CcdShapeConstructionInfo* rootShapeInfo = GetShapeInfo(); - // and verify that the child is part of the parent - int i = rootShapeInfo->FindChildShape(childShapeInfo, childCtrl); - if (i < 0) - return; - rootShapeInfo->RemoveChildShape(i); - if (childCtrl->m_bulletChildShape) - { - int numChildren = compoundShape->getNumChildShapes(); - for (i=0; igetChildShape(i) == childCtrl->m_bulletChildShape) - { - compoundShape->removeChildShapeByIndex(i); - compoundShape->recalculateLocalAabb(); - break; - } - } - delete childCtrl->m_bulletChildShape; - childCtrl->m_bulletChildShape = NULL; - } - // recompute inertia of parent - if (!rootBody->isStaticOrKinematicObject()) - { - btVector3 localInertia; - float mass = 1.f/rootBody->getInvMass(); - compoundShape->calculateLocalInertia(mass,localInertia); - rootBody->setMassProps(mass,localInertia); - } - // must update the broadphase cache, - GetPhysicsEnvironment()->RefreshCcdPhysicsController(this); - // reactivate the children - GetPhysicsEnvironment()->AddCcdPhysicsController(childCtrl); -} - -PHY_IPhysicsController* CcdPhysicsController::GetReplica() -{ - CcdPhysicsController* replica = new CcdPhysicsController(*this); - return replica; -} - -// Keeping this separate for now, maybe we can combine it with GetReplica()... -PHY_IPhysicsController* CcdPhysicsController::GetReplicaForSensors() -{ - // This is used only to replicate Near and Radar sensor controllers - // The replication of object physics controller is done in KX_BulletPhysicsController::GetReplica() - CcdConstructionInfo cinfo = m_cci; - if (m_shapeInfo) - { - // This situation does not normally happen - cinfo.m_collisionShape = m_shapeInfo->CreateBulletShape(m_cci.m_margin, m_cci.m_bGimpact, !m_cci.m_bSoft); - } - else if (m_collisionShape) - { - switch (m_collisionShape->getShapeType()) - { - case SPHERE_SHAPE_PROXYTYPE: - { - btSphereShape* orgShape = (btSphereShape*)m_collisionShape; - cinfo.m_collisionShape = new btSphereShape(*orgShape); - break; - } - - case CONE_SHAPE_PROXYTYPE: - { - btConeShape* orgShape = (btConeShape*)m_collisionShape; - cinfo.m_collisionShape = new btConeShape(*orgShape); - break; - } - - default: - { - return 0; - } - } - } - - cinfo.m_MotionState = new DefaultMotionState(); - cinfo.m_shapeInfo = m_shapeInfo; - - CcdPhysicsController* replica = new CcdPhysicsController(cinfo); - return replica; -} - -/* Refresh the physics object from either an object or a mesh. - * from_gameobj and from_meshobj can be NULL - * - * when setting the mesh, the following vars get priority - * 1) from_meshobj - creates the phys mesh from RAS_MeshObject - * 2) from_gameobj - creates the phys mesh from the DerivedMesh where possible, else the RAS_MeshObject - * 3) this - update the phys mesh from DerivedMesh or RAS_MeshObject - * - * Most of the logic behind this is in m_shapeInfo->UpdateMesh(...) - */ -bool CcdPhysicsController::ReinstancePhysicsShape(KX_GameObject *from_gameobj, RAS_MeshObject *from_meshobj) -{ - if (m_shapeInfo->m_shapeType != PHY_SHAPE_MESH) - return false; - - if (!from_gameobj && !from_meshobj) - from_gameobj = KX_GameObject::GetClientObject((KX_ClientObjectInfo*)GetNewClientInfo()); - - /* updates the arrays used for making the new bullet mesh */ - m_shapeInfo->UpdateMesh(from_gameobj, from_meshobj); - - /* create the new bullet mesh */ - GetPhysicsEnvironment()->UpdateCcdPhysicsControllerShape(m_shapeInfo); - - return true; -} - -void CcdPhysicsController::ReplicateConstraints(KX_GameObject *replica, std::vector constobj) -{ - if (replica->GetConstraints().size() == 0 || !replica->GetPhysicsController()) - return; - - PHY_IPhysicsEnvironment *physEnv = GetPhysicsEnvironment(); - - vector constraints = replica->GetConstraints(); - vector::iterator consit; - - /* Object could have some constraints, iterate over all of theme to ensure that every constraint is recreated. */ - for (consit = constraints.begin(); consit != constraints.end(); ++consit) { - /* Try to find the constraint targets in the list of group objects. */ - bRigidBodyJointConstraint *dat = (*consit); - vector::iterator memit; - for (memit = constobj.begin(); memit != constobj.end(); ++memit) { - KX_GameObject *member = (*memit); - /* If the group member is the actual target for the constraint. */ - if (dat->tar->id.name + 2 == member->GetName() && member->GetPhysicsController()) - physEnv->SetupObjectConstraints(replica, member, dat); - } - } - -} - -/////////////////////////////////////////////////////////// -///A small utility class, DefaultMotionState -/// -/////////////////////////////////////////////////////////// - -DefaultMotionState::DefaultMotionState() -{ - m_worldTransform.setIdentity(); - m_localScaling.setValue(1.f,1.f,1.f); -} - - -DefaultMotionState::~DefaultMotionState() -{ - -} - -void DefaultMotionState::GetWorldPosition(float& posX,float& posY,float& posZ) -{ - posX = m_worldTransform.getOrigin().x(); - posY = m_worldTransform.getOrigin().y(); - posZ = m_worldTransform.getOrigin().z(); -} - -void DefaultMotionState::GetWorldScaling(float& scaleX,float& scaleY,float& scaleZ) -{ - scaleX = m_localScaling.getX(); - scaleY = m_localScaling.getY(); - scaleZ = m_localScaling.getZ(); -} - -void DefaultMotionState::GetWorldOrientation(float& quatIma0,float& quatIma1,float& quatIma2,float& quatReal) -{ - btQuaternion quat = m_worldTransform.getRotation(); - quatIma0 = quat.x(); - quatIma1 = quat.y(); - quatIma2 = quat.z(); - quatReal = quat[3]; -} - -void DefaultMotionState::GetWorldOrientation(float* ori) -{ - m_worldTransform.getBasis().getOpenGLSubMatrix(ori); -} - -void DefaultMotionState::SetWorldOrientation(const float* ori) -{ - m_worldTransform.getBasis().setFromOpenGLSubMatrix(ori); -} -void DefaultMotionState::SetWorldPosition(float posX,float posY,float posZ) -{ - btVector3 pos(posX,posY,posZ); - m_worldTransform.setOrigin( pos ); -} - -void DefaultMotionState::SetWorldOrientation(float quatIma0,float quatIma1,float quatIma2,float quatReal) -{ - btQuaternion orn(quatIma0,quatIma1,quatIma2,quatReal); - m_worldTransform.setRotation( orn ); -} - -void DefaultMotionState::CalculateWorldTransformations() -{ - -} - -// Shape constructor -std::map CcdShapeConstructionInfo::m_meshShapeMap; - -CcdShapeConstructionInfo* CcdShapeConstructionInfo::FindMesh(RAS_MeshObject* mesh, struct DerivedMesh* dm, bool polytope) -{ - if (polytope || dm) - // not yet supported - return NULL; - - std::map::const_iterator mit = m_meshShapeMap.find(mesh); - if (mit != m_meshShapeMap.end()) - return mit->second; - return NULL; -} - -bool CcdShapeConstructionInfo::SetMesh(RAS_MeshObject *meshobj, DerivedMesh *dm, bool polytope) -{ - int numpolys, numverts; - - // assume no shape information - // no support for dynamic change of shape yet - assert(IsUnused()); - m_shapeType = PHY_SHAPE_NONE; - m_meshObject = NULL; - bool free_dm = false; - - // No mesh object or mesh has no polys - if (!meshobj || !meshobj->HasColliderPolygon()) { - m_vertexArray.clear(); - m_polygonIndexArray.clear(); - m_triFaceArray.clear(); - m_triFaceUVcoArray.clear(); - return false; - } - - if (!dm) { - free_dm = true; - dm = CDDM_from_mesh(meshobj->GetMesh()); - } - - // Some meshes with modifiers returns 0 polys, call DM_ensure_tessface avoid this. - DM_ensure_tessface(dm); - - MVert *mvert = dm->getVertArray(dm); - MFace *mface = dm->getTessFaceArray(dm); - numpolys = dm->getNumTessFaces(dm); - numverts = dm->getNumVerts(dm); - MTFace *tface = (MTFace *)dm->getTessFaceDataArray(dm, CD_MTFACE); - - /* double lookup */ - const int *index_mf_to_mpoly = (const int *)dm->getTessFaceDataArray(dm, CD_ORIGINDEX); - const int *index_mp_to_orig = (const int *)dm->getPolyDataArray(dm, CD_ORIGINDEX); - if (!index_mf_to_mpoly) { - index_mp_to_orig = NULL; - } - - m_shapeType = (polytope) ? PHY_SHAPE_POLYTOPE : PHY_SHAPE_MESH; - - /* Convert blender geometry into bullet mesh, need these vars for mapping */ - std::vector vert_tag_array(numverts, false); - unsigned int tot_bt_verts = 0; - - if (polytope) { - // Tag verts we're using - for (int p2 = 0; p2 < numpolys; p2++) { - MFace *mf = &mface[p2]; - const int origi = index_mf_to_mpoly ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, p2) : p2; - RAS_Polygon *poly = (origi != ORIGINDEX_NONE) ? meshobj->GetPolygon(origi) : NULL; - - // only add polygons that have the collision flag set - if (poly && poly->IsCollider()) { - if (!vert_tag_array[mf->v1]) { - vert_tag_array[mf->v1] = true; - tot_bt_verts++; - } - if (!vert_tag_array[mf->v2]) { - vert_tag_array[mf->v2] = true; - tot_bt_verts++; - } - if (!vert_tag_array[mf->v3]) { - vert_tag_array[mf->v3] = true; - tot_bt_verts++; - } - if (mf->v4 && !vert_tag_array[mf->v4]) { - vert_tag_array[mf->v4] = true; - tot_bt_verts++; - } - } - } - - /* Can happen with ngons */ - if (!tot_bt_verts) { - goto cleanup_empty_mesh; - } - - m_vertexArray.resize(tot_bt_verts * 3); - - btScalar *bt = &m_vertexArray[0]; - - for (int p2 = 0; p2 < numpolys; p2++) { - MFace *mf = &mface[p2]; - const int origi = index_mf_to_mpoly ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, p2) : p2; - RAS_Polygon *poly = (origi != ORIGINDEX_NONE) ? meshobj->GetPolygon(origi) : NULL; - - // only add polygons that have the collisionflag set - if (poly->IsCollider()) { - if (vert_tag_array[mf->v1]) { - const float *vtx = mvert[mf->v1].co; - vert_tag_array[mf->v1] = false; - *bt++ = vtx[0]; - *bt++ = vtx[1]; - *bt++ = vtx[2]; - } - if (vert_tag_array[mf->v2]) { - const float *vtx = mvert[mf->v2].co; - vert_tag_array[mf->v2] = false; - *bt++ = vtx[0]; - *bt++ = vtx[1]; - *bt++ = vtx[2]; - } - if (vert_tag_array[mf->v3]) { - const float *vtx = mvert[mf->v3].co; - vert_tag_array[mf->v3] = false; - *bt++ = vtx[0]; - *bt++ = vtx[1]; - *bt++ = vtx[2]; - } - if (mf->v4 && vert_tag_array[mf->v4]) { - const float *vtx = mvert[mf->v4].co; - vert_tag_array[mf->v4] = false; - *bt++ = vtx[0]; - *bt++ = vtx[1]; - *bt++ = vtx[2]; - } - } - } - } - else { - unsigned int tot_bt_tris = 0; - std::vector vert_remap_array(numverts, 0); - - // Tag verts we're using - for (int p2 = 0; p2 < numpolys; p2++) { - MFace *mf = &mface[p2]; - const int origi = index_mf_to_mpoly ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, p2) : p2; - RAS_Polygon *poly = (origi != ORIGINDEX_NONE) ? meshobj->GetPolygon(origi) : NULL; - - // only add polygons that have the collision flag set - if (poly && poly->IsCollider()) { - if (!vert_tag_array[mf->v1]) { - vert_tag_array[mf->v1] = true; - vert_remap_array[mf->v1] = tot_bt_verts; - tot_bt_verts++; - } - if (!vert_tag_array[mf->v2]) { - vert_tag_array[mf->v2] = true; - vert_remap_array[mf->v2] = tot_bt_verts; - tot_bt_verts++; - } - if (!vert_tag_array[mf->v3]) { - vert_tag_array[mf->v3] = true; - vert_remap_array[mf->v3] = tot_bt_verts; - tot_bt_verts++; - } - if (mf->v4 && !vert_tag_array[mf->v4]) { - vert_tag_array[mf->v4] = true; - vert_remap_array[mf->v4] = tot_bt_verts; - tot_bt_verts++; - } - tot_bt_tris += (mf->v4 ? 2 : 1); /* a quad or a tri */ - } - } - - /* Can happen with ngons */ - if (!tot_bt_verts) { - goto cleanup_empty_mesh; - } - - m_vertexArray.resize(tot_bt_verts * 3); - m_polygonIndexArray.resize(tot_bt_tris); - m_triFaceArray.resize(tot_bt_tris * 3); - btScalar *bt = &m_vertexArray[0]; - int *poly_index_pt = &m_polygonIndexArray[0]; - int *tri_pt = &m_triFaceArray[0]; - - UVco *uv_pt = NULL; - if (tface) { - m_triFaceUVcoArray.resize(tot_bt_tris * 3); - uv_pt = &m_triFaceUVcoArray[0]; - } - else - m_triFaceUVcoArray.clear(); - - for (int p2 = 0; p2 < numpolys; p2++) { - MFace *mf = &mface[p2]; - MTFace *tf = (tface) ? &tface[p2] : NULL; - const int origi = index_mf_to_mpoly ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, p2) : p2; - RAS_Polygon *poly = (origi != ORIGINDEX_NONE) ? meshobj->GetPolygon(origi) : NULL; - - // only add polygons that have the collisionflag set - if (poly && poly->IsCollider()) { - MVert *v1 = &mvert[mf->v1]; - MVert *v2 = &mvert[mf->v2]; - MVert *v3 = &mvert[mf->v3]; - - // the face indices - tri_pt[0] = vert_remap_array[mf->v1]; - tri_pt[1] = vert_remap_array[mf->v2]; - tri_pt[2] = vert_remap_array[mf->v3]; - tri_pt = tri_pt + 3; - if (tf) { - uv_pt[0].uv[0] = tf->uv[0][0]; - uv_pt[0].uv[1] = tf->uv[0][1]; - uv_pt[1].uv[0] = tf->uv[1][0]; - uv_pt[1].uv[1] = tf->uv[1][1]; - uv_pt[2].uv[0] = tf->uv[2][0]; - uv_pt[2].uv[1] = tf->uv[2][1]; - uv_pt += 3; - } - - // m_polygonIndexArray - *poly_index_pt = origi; - poly_index_pt++; - - // the vertex location - if (vert_tag_array[mf->v1]) { /* *** v1 *** */ - vert_tag_array[mf->v1] = false; - *bt++ = v1->co[0]; - *bt++ = v1->co[1]; - *bt++ = v1->co[2]; - } - if (vert_tag_array[mf->v2]) { /* *** v2 *** */ - vert_tag_array[mf->v2] = false; - *bt++ = v2->co[0]; - *bt++ = v2->co[1]; - *bt++ = v2->co[2]; - } - if (vert_tag_array[mf->v3]) { /* *** v3 *** */ - vert_tag_array[mf->v3] = false; - *bt++ = v3->co[0]; - *bt++ = v3->co[1]; - *bt++ = v3->co[2]; - } - - if (mf->v4) - { - MVert *v4 = &mvert[mf->v4]; - - tri_pt[0] = vert_remap_array[mf->v1]; - tri_pt[1] = vert_remap_array[mf->v3]; - tri_pt[2] = vert_remap_array[mf->v4]; - tri_pt = tri_pt + 3; - if (tf) - { - uv_pt[0].uv[0] = tf->uv[0][0]; - uv_pt[0].uv[1] = tf->uv[0][1]; - uv_pt[1].uv[0] = tf->uv[2][0]; - uv_pt[1].uv[1] = tf->uv[2][1]; - uv_pt[2].uv[0] = tf->uv[3][0]; - uv_pt[2].uv[1] = tf->uv[3][1]; - uv_pt += 3; - } - - // m_polygonIndexArray - *poly_index_pt = origi; - poly_index_pt++; - - // the vertex location - if (vert_tag_array[mf->v4]) { /* *** v4 *** */ - vert_tag_array[mf->v4] = false; - *bt++ = v4->co[0]; - *bt++ = v4->co[1]; - *bt++ = v4->co[2]; - } - } - } - } - - - /* If this ever gets confusing, print out an OBJ file for debugging */ -#if 0 - printf("# vert count %d\n", m_vertexArray.size()); - for (i = 0; i < m_vertexArray.size(); i += 1) { - printf("v %.6f %.6f %.6f\n", m_vertexArray[i].x(), m_vertexArray[i].y(), m_vertexArray[i].z()); - } - - printf("# face count %d\n", m_triFaceArray.size()); - for (i = 0; i < m_triFaceArray.size(); i += 3) { - printf("f %d %d %d\n", m_triFaceArray[i] + 1, m_triFaceArray[i + 1] + 1, m_triFaceArray[i + 2] + 1); - } -#endif - - } - -#if 0 - if (validpolys == false) - { - // should not happen - m_shapeType = PHY_SHAPE_NONE; - return false; - } -#endif - - m_meshObject = meshobj; - if (free_dm) { - dm->release(dm); - dm = NULL; - } - - // sharing only on static mesh at present, if you change that, you must also change in FindMesh - if (!polytope && !dm) { - // triangle shape can be shared, store the mesh object in the map - m_meshShapeMap.insert(std::pair(meshobj, this)); - } - return true; - - -cleanup_empty_mesh: - m_shapeType = PHY_SHAPE_NONE; - m_meshObject = NULL; - m_vertexArray.clear(); - m_polygonIndexArray.clear(); - m_triFaceArray.clear(); - m_triFaceUVcoArray.clear(); - if (free_dm) { - dm->release(dm); - } - return false; -} - -#include - -/* Updates the arrays used by CreateBulletShape(), - * take care that recalcLocalAabb() runs after CreateBulletShape is called. - * */ -bool CcdShapeConstructionInfo::UpdateMesh(class KX_GameObject *gameobj, class RAS_MeshObject *meshobj) -{ - int numpolys; - int numverts; - - unsigned int tot_bt_tris = 0; - unsigned int tot_bt_verts = 0; - - int i, j; - int v_orig; - - /* Use for looping over verts in a face as a try or 2 tris */ - const int quad_verts[7] = {0, 1, 2, 0, 2, 3, -1}; - const int tri_verts[4] = {0, 1, 2, -1}; - const int *fv_pt; - - if (!gameobj && !meshobj) - return false; - - if (m_shapeType != PHY_SHAPE_MESH) - return false; - - RAS_Deformer *deformer = gameobj ? gameobj->GetDeformer() : NULL; - DerivedMesh *dm = NULL; - - if (deformer) - dm = deformer->GetPhysicsMesh(); - - /* get the mesh from the object if not defined */ - if (!meshobj) { - /* modifier mesh */ - if (dm) - meshobj = deformer->GetRasMesh(); - - /* game object first mesh */ - if (!meshobj) { - if (gameobj->GetMeshCount() > 0) { - meshobj = gameobj->GetMesh(0); - } - } - } - - if (dm && deformer->GetRasMesh() == meshobj) { - /* - * Derived Mesh Update - * - * */ - - MVert *mvert = dm->getVertArray(dm); - MFace *mface = dm->getTessFaceArray(dm); - numpolys = dm->getNumTessFaces(dm); - numverts = dm->getNumVerts(dm); - - /* double lookup */ - const int *index_mf_to_mpoly = (const int *)dm->getTessFaceDataArray(dm, CD_ORIGINDEX); - const int *index_mp_to_orig = (const int *)dm->getPolyDataArray(dm, CD_ORIGINDEX); - if (!index_mf_to_mpoly) { - index_mp_to_orig = NULL; - } - - MFace *mf; - MVert *mv; - - if (CustomData_has_layer(&dm->faceData, CD_MTFACE)) { - MTFace *tface = (MTFace *)dm->getTessFaceDataArray(dm, CD_MTFACE); - MTFace *tf; - - std::vector vert_tag_array(numverts, false); - std::vector vert_remap_array(numverts, 0); - - for (mf = mface, tf = tface, i = 0; i < numpolys; mf++, tf++, i++) { - // 2.8x TODO: use GEMAT_NOPHYSICS. - // if (tf->mode & TF_DYNAMIC) - { - int flen; - - if (mf->v4) { - tot_bt_tris += 2; - flen = 4; - } - else { - tot_bt_tris++; - flen = 3; - } - - for (j = 0; j < flen; j++) { - v_orig = (*(&mf->v1 + j)); - - if (!vert_tag_array[v_orig]) { - vert_tag_array[v_orig] = true; - vert_remap_array[v_orig] = tot_bt_verts; - tot_bt_verts++; - } - } - } - } - - m_vertexArray.resize(tot_bt_verts * 3); - btScalar *bt = &m_vertexArray[0]; - - m_triFaceArray.resize(tot_bt_tris * 3); - int *tri_pt = &m_triFaceArray[0]; - - m_triFaceUVcoArray.resize(tot_bt_tris * 3); - UVco *uv_pt = &m_triFaceUVcoArray[0]; - - m_polygonIndexArray.resize(tot_bt_tris); - int *poly_index_pt = &m_polygonIndexArray[0]; - - for (mf = mface, tf = tface, i = 0; i < numpolys; mf++, tf++, i++) { - // 2.8x TODO: use GEMAT_NOPHYSICS. - // if (tf->mode & TF_DYNAMIC) - { - int origi = index_mf_to_mpoly ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, i) : i; - - if (mf->v4) { - fv_pt = quad_verts; - *poly_index_pt++ = origi; - *poly_index_pt++ = origi; - } - else { - fv_pt = tri_verts; - *poly_index_pt++ = origi; - } - - for (; *fv_pt > -1; fv_pt++) { - v_orig = (*(&mf->v1 + (*fv_pt))); - - if (vert_tag_array[v_orig]) - { - mv = mvert + v_orig; - *bt++ = mv->co[0]; - *bt++ = mv->co[1]; - *bt++ = mv->co[2]; - - vert_tag_array[v_orig] = false; - } - *tri_pt++ = vert_remap_array[v_orig]; - uv_pt->uv[0] = tf->uv[*fv_pt][0]; - uv_pt->uv[1] = tf->uv[*fv_pt][1]; - uv_pt++; - } - } - } - } - else { - /* no need for a vertex mapping. simple/fast */ - - tot_bt_verts = numverts; - - for (mf = mface, i = 0; i < numpolys; mf++, i++) { - tot_bt_tris += (mf->v4 ? 2 : 1); - } - - m_vertexArray.resize(tot_bt_verts * 3); - btScalar *bt = &m_vertexArray[0]; - - m_triFaceArray.resize(tot_bt_tris * 3); - int *tri_pt = &m_triFaceArray[0]; - - m_polygonIndexArray.resize(tot_bt_tris); - int *poly_index_pt = &m_polygonIndexArray[0]; - - m_triFaceUVcoArray.clear(); - - for (mv = mvert, i = 0; i < numverts; mv++, i++) { - *bt++ = mv->co[0]; *bt++ = mv->co[1]; *bt++ = mv->co[2]; - } - - for (mf = mface, i = 0; i < numpolys; mf++, i++) { - int origi = index_mf_to_mpoly ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, i) : i; - - if (mf->v4) { - fv_pt = quad_verts; - *poly_index_pt++ = origi; - *poly_index_pt++ = origi; - } - else { - fv_pt = tri_verts; - *poly_index_pt++ = origi; - } - - for (; *fv_pt > -1; fv_pt++) - *tri_pt++ = (*(&mf->v1 + (*fv_pt))); - } - } - } - else { /* - * RAS Mesh Update - * - * */ - /* Note!, gameobj can be NULL here */ - - /* transverts are only used for deformed RAS_Meshes, the RAS_TexVert data - * is too hard to get at, see below for details */ - float(*transverts)[3] = NULL; - int transverts_tot = 0; /* with deformed meshes - should always be greater than the max orginal index, or we get crashes */ - - if (deformer) { - /* map locations from the deformed array - * - * Could call deformer->Update(); but rely on redraw updating. - * */ - transverts = deformer->GetTransVerts(&transverts_tot); - } - - // Tag verts we're using - numpolys = meshobj->NumPolygons(); - numverts = meshobj->m_sharedvertex_map.size(); - const float *xyz; - - - std::vector vert_tag_array(numverts, false); - std::vector vert_remap_array(numverts, 0); - - for (int p = 0; p < numpolys; p++) { - RAS_Polygon *poly = meshobj->GetPolygon(p); - if (poly->IsCollider()) { - for (i = 0; i < poly->VertexCount(); i++) { - v_orig = poly->GetVertex(i)->getOrigIndex(); - if (!vert_tag_array[v_orig]) { - vert_tag_array[v_orig] = true; - vert_remap_array[v_orig] = tot_bt_verts; - tot_bt_verts++; - } - } - tot_bt_tris += (poly->VertexCount() == 4 ? 2 : 1); - } - } - - // This case happens when none of the polys are colliders - if (tot_bt_tris == 0 || tot_bt_verts == 0) - return false; - - m_vertexArray.resize(tot_bt_verts * 3); - btScalar *bt = &m_vertexArray[0]; - - m_triFaceArray.resize(tot_bt_tris * 3); - int *tri_pt = &m_triFaceArray[0]; - - /* cant be used for anything useful in this case, since we don't rely on the original mesh - * will just be an array like pythons range(tot_bt_tris) */ - m_polygonIndexArray.resize(tot_bt_tris); - - - int p = 0; - int t = 0; - while (t < tot_bt_tris) { - RAS_Polygon *poly = meshobj->GetPolygon(p); - - if (poly->IsCollider()) { - /* quad or tri loop */ - fv_pt = (poly->VertexCount() == 3 ? tri_verts : quad_verts); - - for (; *fv_pt > -1; fv_pt++) { - v_orig = poly->GetVertex(*fv_pt)->getOrigIndex(); - if (vert_tag_array[v_orig]) { - if (transverts) { - /* deformed mesh, using RAS_TexVert locations would be too troublesome - * because they are use the gameob as a hash in the material slot */ - *bt++ = transverts[v_orig][0]; - *bt++ = transverts[v_orig][1]; - *bt++ = transverts[v_orig][2]; - } - else { - /* static mesh python may have modified */ - xyz = meshobj->GetVertexLocation(v_orig); - *bt++ = xyz[0]; - *bt++ = xyz[1]; - *bt++ = xyz[2]; - } - vert_tag_array[v_orig] = false; - } - *tri_pt++ = vert_remap_array[v_orig]; - } - } - // first triangle - m_polygonIndexArray[t] = p; - - // if the poly is a quad we transform it in two triangles - if (poly->VertexCount() == 4) { - t++; - // second triangle - m_polygonIndexArray[t] = p; - } - t++; - p++; - } - } - -#if 0 - /* needs #include */ - printf("# vert count %d\n", m_vertexArray.size()); - for (int i = 0; i < m_vertexArray.size(); i += 3) { - printf("v %.6f %.6f %.6f\n", m_vertexArray[i], m_vertexArray[i + 1], m_vertexArray[i + 2]); - } - - printf("# face count %d\n", m_triFaceArray.size()); - for (int i = 0; i < m_triFaceArray.size(); i += 3) { - printf("f %d %d %d\n", m_triFaceArray[i] + 1, m_triFaceArray[i + 1] + 1, m_triFaceArray[i + 2] + 1); - } -#endif - - /* force recreation of the m_triangleIndexVertexArray. - * If this has multiple users we cant delete */ - if (m_triangleIndexVertexArray) { - m_forceReInstance = true; - } - - // Make sure to also replace the mesh in the shape map! Otherwise we leave dangling references when we free. - // Note, this whole business could cause issues with shared meshes. If we update one mesh, do we replace - // them all? - std::map::iterator mit = m_meshShapeMap.find(m_meshObject); - if (mit != m_meshShapeMap.end()) { - m_meshShapeMap.erase(mit); - m_meshShapeMap[meshobj] = this; - } - - m_meshObject = meshobj; - - if (dm) { - dm->needsFree = 1; - dm->release(dm); - } - return true; -} - -bool CcdShapeConstructionInfo::SetProxy(CcdShapeConstructionInfo* shapeInfo) -{ - if (shapeInfo == NULL) - return false; - // no support for dynamic change - assert(IsUnused()); - m_shapeType = PHY_SHAPE_PROXY; - m_shapeProxy = shapeInfo; - return true; -} - -btCollisionShape* CcdShapeConstructionInfo::CreateBulletShape(btScalar margin, bool useGimpact, bool useBvh) -{ - btCollisionShape* collisionShape = 0; - btCompoundShape* compoundShape = 0; - - if (m_shapeType == PHY_SHAPE_PROXY && m_shapeProxy != NULL) - return m_shapeProxy->CreateBulletShape(margin, useGimpact, useBvh); - - switch (m_shapeType) - { - default: - break; - - case PHY_SHAPE_BOX: - collisionShape = new btBoxShape(m_halfExtend); - collisionShape->setMargin(margin); - break; - - case PHY_SHAPE_SPHERE: - collisionShape = new btSphereShape(m_radius); - collisionShape->setMargin(margin); - break; - - case PHY_SHAPE_CYLINDER: - collisionShape = new btCylinderShapeZ(m_halfExtend); - collisionShape->setMargin(margin); - break; - - case PHY_SHAPE_CONE: - collisionShape = new btConeShapeZ(m_radius, m_height); - collisionShape->setMargin(margin); - break; - - case PHY_SHAPE_POLYTOPE: - collisionShape = new btConvexHullShape(&m_vertexArray[0], m_vertexArray.size()/3, 3*sizeof(btScalar)); - collisionShape->setMargin(margin); - break; - - case PHY_SHAPE_CAPSULE: - collisionShape = new btCapsuleShapeZ(m_radius, m_height); - collisionShape->setMargin(margin); - break; - - case PHY_SHAPE_MESH: - // Let's use the latest btScaledBvhTriangleMeshShape: it allows true sharing of - // triangle mesh information between duplicates => drastic performance increase when - // duplicating complex mesh objects. - // BUT it causes a small performance decrease when sharing is not required: - // 9 multiplications/additions and one function call for each triangle that passes the mid phase filtering - // One possible optimization is to use directly the btBvhTriangleMeshShape when the scale is 1,1,1 - // and btScaledBvhTriangleMeshShape otherwise. - if (useGimpact) { - if (!m_triangleIndexVertexArray || m_forceReInstance) { - if (m_triangleIndexVertexArray) - delete m_triangleIndexVertexArray; - - m_triangleIndexVertexArray = new btTriangleIndexVertexArray( - m_polygonIndexArray.size(), - m_triFaceArray.data(), - 3 * sizeof(int), - m_vertexArray.size() / 3, - &m_vertexArray[0], - 3 * sizeof(btScalar)); - m_forceReInstance = false; - } - - btGImpactMeshShape *gimpactShape = new btGImpactMeshShape(m_triangleIndexVertexArray); - gimpactShape->setMargin(margin); - gimpactShape->updateBound(); - collisionShape = gimpactShape; - } - else { - if (!m_triangleIndexVertexArray || m_forceReInstance) { - ///enable welding, only for the objects that need it (such as soft bodies) - if (0.0f != m_weldingThreshold1) { - btTriangleMesh *collisionMeshData = new btTriangleMesh(true, false); - collisionMeshData->m_weldingThreshold = m_weldingThreshold1; - bool removeDuplicateVertices = true; - // m_vertexArray not in multiple of 3 anymore, use m_triFaceArray - for (unsigned int i = 0; i < m_triFaceArray.size(); i += 3) { - btScalar *bt = &m_vertexArray[3 * m_triFaceArray[i]]; - btVector3 v1(bt[0], bt[1], bt[2]); - bt = &m_vertexArray[3 * m_triFaceArray[i + 1]]; - btVector3 v2(bt[0], bt[1], bt[2]); - bt = &m_vertexArray[3 * m_triFaceArray[i + 2]]; - btVector3 v3(bt[0], bt[1], bt[2]); - collisionMeshData->addTriangle(v1, v2, v3, removeDuplicateVertices); - } - m_triangleIndexVertexArray = collisionMeshData; - } - else { - m_triangleIndexVertexArray = new btTriangleIndexVertexArray( - m_polygonIndexArray.size(), - m_triFaceArray.data(), - 3 * sizeof(int), - m_vertexArray.size() / 3, - &m_vertexArray[0], - 3 * sizeof(btScalar)); - } - - m_forceReInstance = false; - } - - btBvhTriangleMeshShape *unscaledShape = new btBvhTriangleMeshShape(m_triangleIndexVertexArray, true, useBvh); - unscaledShape->setMargin(margin); - collisionShape = new btScaledBvhTriangleMeshShape(unscaledShape, btVector3(1.0f, 1.0f, 1.0f)); - collisionShape->setMargin(margin); - } - break; - - case PHY_SHAPE_COMPOUND: - if (m_shapeArray.size() > 0) - { - compoundShape = new btCompoundShape(); - for (std::vector::iterator sit = m_shapeArray.begin(); - sit != m_shapeArray.end(); - sit++) - { - collisionShape = (*sit)->CreateBulletShape(margin, useGimpact, useBvh); - if (collisionShape) - { - collisionShape->setLocalScaling((*sit)->m_childScale); - compoundShape->addChildShape((*sit)->m_childTrans, collisionShape); - } - } - collisionShape = compoundShape; - } - break; - } - return collisionShape; -} - -void CcdShapeConstructionInfo::AddShape(CcdShapeConstructionInfo* shapeInfo) -{ - m_shapeArray.push_back(shapeInfo); - shapeInfo->AddRef(); -} - -CcdShapeConstructionInfo::~CcdShapeConstructionInfo() -{ - for (std::vector::iterator sit = m_shapeArray.begin(); - sit != m_shapeArray.end(); - sit++) - { - (*sit)->Release(); - } - m_shapeArray.clear(); - - if (m_triangleIndexVertexArray) - delete m_triangleIndexVertexArray; - m_vertexArray.clear(); - if (m_shapeType == PHY_SHAPE_MESH && m_meshObject != NULL) - { - std::map::iterator mit = m_meshShapeMap.find(m_meshObject); - if (mit != m_meshShapeMap.end() && mit->second == this) - { - m_meshShapeMap.erase(mit); - } - } - if (m_shapeType == PHY_SHAPE_PROXY && m_shapeProxy != NULL) - { - m_shapeProxy->Release(); - } -} - diff --git a/source/gameengine/Physics/Bullet/CcdPhysicsController.h b/source/gameengine/Physics/Bullet/CcdPhysicsController.h deleted file mode 100644 index 831e7346df7..00000000000 --- a/source/gameengine/Physics/Bullet/CcdPhysicsController.h +++ /dev/null @@ -1,832 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -/** \file CcdPhysicsController.h - * \ingroup physbullet - */ - - -#ifndef __CCDPHYSICSCONTROLLER_H__ -#define __CCDPHYSICSCONTROLLER_H__ - -#include -#include - -#include "PHY_IPhysicsController.h" - -/// PHY_IPhysicsController is the abstract simplified Interface to a physical object. -/// It contains the IMotionState and IDeformableMesh Interfaces. -#include "btBulletDynamicsCommon.h" -#include "BulletDynamics/Character/btKinematicCharacterController.h" -#include "LinearMath/btTransform.h" - -#include "PHY_IMotionState.h" -#include "PHY_ICharacter.h" - -extern float gDeactivationTime; -extern float gLinearSleepingTreshold; -extern float gAngularSleepingTreshold; -extern bool gDisableDeactivation; -class CcdPhysicsEnvironment; -class btMotionState; -class RAS_MeshObject; -struct DerivedMesh; -class btCollisionShape; - - -#define CCD_BSB_SHAPE_MATCHING 2 -#define CCD_BSB_BENDING_CONSTRAINTS 8 -#define CCD_BSB_AERO_VPOINT 16 /* aero model, Vertex normals are oriented toward velocity*/ -#define CCD_BSB_AERO_VTWOSIDE 32 /* aero model, Vertex normals are flipped to match velocity */ - -/* BulletSoftBody.collisionflags */ -#define CCD_BSB_COL_SDF_RS 2 /* SDF based rigid vs soft */ -#define CCD_BSB_COL_CL_RS 4 /* Cluster based rigid vs soft */ -#define CCD_BSB_COL_CL_SS 8 /* Cluster based soft vs soft */ -#define CCD_BSB_COL_VF_SS 16 /* Vertex/Face based soft vs soft */ - - -// Shape contructor -// It contains all the information needed to create a simple bullet shape at runtime -class CcdShapeConstructionInfo -{ -public: - struct UVco - { - float uv[2]; - }; - - static CcdShapeConstructionInfo* FindMesh(class RAS_MeshObject* mesh, struct DerivedMesh* dm, bool polytope); - - CcdShapeConstructionInfo() : - m_shapeType(PHY_SHAPE_NONE), - m_radius(1.0f), - m_height(1.0f), - m_halfExtend(0.f,0.f,0.f), - m_childScale(1.0f,1.0f,1.0f), - m_userData(NULL), - m_refCount(1), - m_meshObject(NULL), - m_triangleIndexVertexArray(NULL), - m_forceReInstance(false), - m_weldingThreshold1(0.f), - m_shapeProxy(NULL) - { - m_childTrans.setIdentity(); - } - - ~CcdShapeConstructionInfo(); - - CcdShapeConstructionInfo* AddRef() - { - m_refCount++; - return this; - } - - int Release() - { - if (--m_refCount > 0) - return m_refCount; - delete this; - return 0; - } - - bool IsUnused(void) - { - return (m_meshObject==NULL && m_shapeArray.size() == 0 && m_shapeProxy == NULL); - } - - void AddShape(CcdShapeConstructionInfo* shapeInfo); - - btStridingMeshInterface *GetMeshInterface() - { - return m_triangleIndexVertexArray; - } - - CcdShapeConstructionInfo* GetChildShape(int i) - { - if (i < 0 || i >= (int)m_shapeArray.size()) - return NULL; - - return m_shapeArray.at(i); - } - int FindChildShape(CcdShapeConstructionInfo* shapeInfo, void* userData) - { - if (shapeInfo == NULL) - return -1; - for (int i=0; i<(int)m_shapeArray.size(); i++) - { - CcdShapeConstructionInfo* childInfo = m_shapeArray.at(i); - if ((userData == NULL || userData == childInfo->m_userData) && - (childInfo == shapeInfo || - (childInfo->m_shapeType == PHY_SHAPE_PROXY && - childInfo->m_shapeProxy == shapeInfo))) - return i; - } - return -1; - } - - bool RemoveChildShape(int i) - { - if (i < 0 || i >= (int)m_shapeArray.size()) - return false; - m_shapeArray.at(i)->Release(); - if (i < (int)m_shapeArray.size()-1) - m_shapeArray[i] = m_shapeArray.back(); - m_shapeArray.pop_back(); - return true; - } - - bool SetMesh(class RAS_MeshObject* mesh, struct DerivedMesh* dm, bool polytope); - RAS_MeshObject* GetMesh(void) - { - return m_meshObject; - } - - bool UpdateMesh(class KX_GameObject* gameobj, class RAS_MeshObject* mesh); - - - bool SetProxy(CcdShapeConstructionInfo* shapeInfo); - CcdShapeConstructionInfo* GetProxy(void) - { - return m_shapeProxy; - } - - btCollisionShape* CreateBulletShape(btScalar margin, bool useGimpact=false, bool useBvh=true); - - // member variables - PHY_ShapeType m_shapeType; - btScalar m_radius; - btScalar m_height; - btVector3 m_halfExtend; - btTransform m_childTrans; - btVector3 m_childScale; - void* m_userData; - btAlignedObjectArray m_vertexArray; // Contains both vertex array for polytope shape and - // triangle array for concave mesh shape. Each vertex is 3 consecutive values - // In this case a triangle is made of 3 consecutive points - std::vector m_polygonIndexArray; // Contains the array of polygon index in the - // original mesh that correspond to shape triangles. - // only set for concave mesh shape. - - std::vector m_triFaceArray; // Contains an array of triplets of face indices - // quads turn into 2 tris - - std::vector m_triFaceUVcoArray; // Contains an array of pair of UV coordinate for each vertex of faces - // quads turn into 2 tris - - void setVertexWeldingThreshold1(float threshold) - { - m_weldingThreshold1 = threshold*threshold; - } -protected: - static std::map m_meshShapeMap; - int m_refCount; // this class is shared between replicas - // keep track of users so that we can release it - RAS_MeshObject* m_meshObject; // Keep a pointer to the original mesh - // The list of vertexes and indexes for the triangle mesh, shared between Bullet shape. - btTriangleIndexVertexArray *m_triangleIndexVertexArray; - std::vector m_shapeArray; // for compound shapes - bool m_forceReInstance; //use gimpact for concave dynamic/moving collision detection - float m_weldingThreshold1; //welding closeby vertices together can improve softbody stability etc. - CcdShapeConstructionInfo* m_shapeProxy; // only used for PHY_SHAPE_PROXY, pointer to actual shape info - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:CcdShapeConstructionInfo") -#endif -}; - -struct CcdConstructionInfo -{ - - ///CollisionFilterGroups provides some optional usage of basic collision filtering - ///this is done during broadphase, so very early in the pipeline - ///more advanced collision filtering should be done in btCollisionDispatcher::NeedsCollision - enum CollisionFilterGroups - { - DefaultFilter = 1, - StaticFilter = 2, - KinematicFilter = 4, - DebrisFilter = 8, - SensorFilter = 16, - CharacterFilter = 32, - AllFilter = DefaultFilter | StaticFilter | KinematicFilter | DebrisFilter | SensorFilter | CharacterFilter, - }; - - - CcdConstructionInfo() - :m_localInertiaTensor(1.f, 1.f, 1.f), - m_gravity(0,0,0), - m_scaling(1.f,1.f,1.f), - m_linearFactor(0.f, 0.f, 0.f), - m_angularFactor(0.f, 0.f, 0.f), - m_mass(0.f), - m_clamp_vel_min(-1.f), - m_clamp_vel_max(-1.f), - m_clamp_angvel_min(0.0f), - m_clamp_angvel_max(0.0f), - m_restitution(0.1f), - m_friction(0.5f), - m_linearDamping(0.1f), - m_angularDamping(0.1f), - m_margin(0.06f), - m_gamesoftFlag(0), - m_soft_linStiff(1.f), - m_soft_angStiff(1.f), - m_soft_volume(1.f), - m_soft_viterations(0), - m_soft_piterations(1), - m_soft_diterations(0), - m_soft_citerations(4), - m_soft_kSRHR_CL(0.1f), - m_soft_kSKHR_CL(1.f), - m_soft_kSSHR_CL(0.5f), - m_soft_kSR_SPLT_CL(0.5f), - m_soft_kSK_SPLT_CL(0.5f), - m_soft_kSS_SPLT_CL(0.5f), - m_soft_kVCF(1.f), - m_soft_kDP(0.f), - m_soft_kDG(0.f), - m_soft_kLF(0.f), - m_soft_kPR(0.f), - m_soft_kVC(0.f), - m_soft_kDF(0.2f), - m_soft_kMT(0), - m_soft_kCHR(1.0f), - m_soft_kKHR(0.1f), - m_soft_kSHR(1.0f), - m_soft_kAHR(0.7f), - m_collisionFlags(0), - m_bDyna(false), - m_bRigid(false), - m_bSoft(false), - m_bSensor(false), - m_bCharacter(false), - m_bGimpact(false), - m_collisionFilterGroup(DefaultFilter), - m_collisionFilterMask(AllFilter), - m_collisionShape(0), - m_MotionState(0), - m_shapeInfo(0), - m_physicsEnv(0), - m_inertiaFactor(1.f), - m_do_anisotropic(false), - m_anisotropicFriction(1.f,1.f,1.f), - m_do_fh(false), - m_do_rot_fh(false), - m_fh_spring(0.f), - m_fh_damping(0.f), - m_fh_distance(1.f), - m_fh_normal(false) - // m_contactProcessingThreshold(1e10f) - { - - } - - btVector3 m_localInertiaTensor; - btVector3 m_gravity; - btVector3 m_scaling; - btVector3 m_linearFactor; - btVector3 m_angularFactor; - btScalar m_mass; - btScalar m_clamp_vel_min; - btScalar m_clamp_vel_max; - btScalar m_clamp_angvel_min; // Minimum angular velocity, in radians/sec. - btScalar m_clamp_angvel_max; // Maximum angular velocity, in radians/sec. - btScalar m_restitution; - btScalar m_friction; - btScalar m_linearDamping; - btScalar m_angularDamping; - btScalar m_margin; - - //////////////////// - float m_stepHeight; - float m_jumpSpeed; - float m_fallSpeed; - unsigned char m_maxJumps; - - int m_gamesoftFlag; - float m_soft_linStiff; /* linear stiffness 0..1 */ - float m_soft_angStiff; /* angular stiffness 0..1 */ - float m_soft_volume; /* volume preservation 0..1 */ - - int m_soft_viterations; /* Velocities solver iterations */ - int m_soft_piterations; /* Positions solver iterations */ - int m_soft_diterations; /* Drift solver iterations */ - int m_soft_citerations; /* Cluster solver iterations */ - - float m_soft_kSRHR_CL; /* Soft vs rigid hardness [0,1] (cluster only) */ - float m_soft_kSKHR_CL; /* Soft vs kinetic hardness [0,1] (cluster only) */ - float m_soft_kSSHR_CL; /* Soft vs soft hardness [0,1] (cluster only) */ - float m_soft_kSR_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */ - - float m_soft_kSK_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */ - float m_soft_kSS_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */ - float m_soft_kVCF; /* Velocities correction factor (Baumgarte) */ - float m_soft_kDP; /* Damping coefficient [0,1] */ - - float m_soft_kDG; /* Drag coefficient [0,+inf] */ - float m_soft_kLF; /* Lift coefficient [0,+inf] */ - float m_soft_kPR; /* Pressure coefficient [-inf,+inf] */ - float m_soft_kVC; /* Volume conversation coefficient [0,+inf] */ - - float m_soft_kDF; /* Dynamic friction coefficient [0,1] */ - float m_soft_kMT; /* Pose matching coefficient [0,1] */ - float m_soft_kCHR; /* Rigid contacts hardness [0,1] */ - float m_soft_kKHR; /* Kinetic contacts hardness [0,1] */ - - float m_soft_kSHR; /* Soft contacts hardness [0,1] */ - float m_soft_kAHR; /* Anchors hardness [0,1] */ - int m_soft_collisionflags; /* Vertex/Face or Signed Distance Field(SDF) or Clusters, Soft versus Soft or Rigid */ - int m_soft_numclusteriterations; /* number of iterations to refine collision clusters*/ -/////////////////// - - - - int m_collisionFlags; - bool m_bDyna; - bool m_bRigid; - bool m_bSoft; - bool m_bSensor; - bool m_bCharacter; - bool m_bGimpact; // use Gimpact for mesh body - - ///optional use of collision group/mask: - ///only collision with object goups that match the collision mask. - ///this is very basic early out. advanced collision filtering should be - ///done in the btCollisionDispatcher::NeedsCollision and NeedsResponse - ///both values default to 1 - short int m_collisionFilterGroup; - short int m_collisionFilterMask; - - ///these pointers are used as argument passing for the CcdPhysicsController constructor - ///and not anymore after that - class btCollisionShape* m_collisionShape; - class PHY_IMotionState* m_MotionState; - class CcdShapeConstructionInfo* m_shapeInfo; - - CcdPhysicsEnvironment* m_physicsEnv; //needed for self-replication - float m_inertiaFactor;//tweak the inertia (hooked up to Blender 'formfactor' - bool m_do_anisotropic; - btVector3 m_anisotropicFriction; - - bool m_do_fh; ///< Should the object have a linear Fh spring? - bool m_do_rot_fh; ///< Should the object have an angular Fh spring? - btScalar m_fh_spring; ///< Spring constant (both linear and angular) - btScalar m_fh_damping; ///< Damping factor (linear and angular) in range [0, 1] - btScalar m_fh_distance; ///< The range above the surface where Fh is active. - bool m_fh_normal; ///< Should the object slide off slopes? - float m_radius;//for fh backwards compatibility - - ///m_contactProcessingThreshold allows to process contact points with positive distance - ///normally only contacts with negative distance (penetration) are solved - ///however, rigid body stacking is more stable when positive contacts are still passed into the constraint solver - ///this might sometimes lead to collisions with 'internal edges' such as a sliding character controller - ///so disable/set m_contactProcessingThreshold to zero for sliding characters etc. - // float m_contactProcessingThreshold;///< Process contacts with positive distance in range [0..INF] -}; - -class btRigidBody; -class btCollisionObject; -class btSoftBody; -class btPairCachingGhostObject; - -class BlenderBulletCharacterController : public btKinematicCharacterController, public PHY_ICharacter -{ -private: - btMotionState* m_motionState; - unsigned char m_jumps; - unsigned char m_maxJumps; - -public: - BlenderBulletCharacterController(btMotionState *motionState, btPairCachingGhostObject *ghost, btConvexShape* shape, float stepHeight); - - virtual void updateAction(btCollisionWorld *collisionWorld, btScalar dt); - - unsigned char getMaxJumps() const; - - void setMaxJumps(unsigned char maxJumps); - - unsigned char getJumpCount() const; - - virtual bool canJump() const; - - virtual void jump(); - - const btVector3& getWalkDirection(); - - // PHY_ICharacter interface - virtual void Jump() { jump(); } - virtual bool OnGround() { return onGround(); } - virtual float GetGravity() { return getGravity(); } - virtual void SetGravity(float gravity) { setGravity(gravity); } - virtual unsigned char GetMaxJumps() { return getMaxJumps(); } - virtual void SetMaxJumps(unsigned char maxJumps) { setMaxJumps(maxJumps); } - virtual unsigned char GetJumpCount() { return getJumpCount(); } - virtual void SetWalkDirection(const MT_Vector3& dir) - { - btVector3 vec = btVector3(dir[0], dir[1], dir[2]); - setWalkDirection(vec); - } - virtual MT_Vector3 GetWalkDirection() - { - btVector3 vec = getWalkDirection(); - return MT_Vector3(vec[0], vec[1], vec[2]); - } - -#ifdef WITH_CXX_GUARDEDALLOC - using PHY_ICharacter::operator new; - using PHY_ICharacter::operator delete; -#endif -}; - -class CleanPairCallback : public btOverlapCallback -{ - btBroadphaseProxy *m_cleanProxy; - btOverlappingPairCache *m_pairCache; - btDispatcher *m_dispatcher; - -public: - CleanPairCallback(btBroadphaseProxy *cleanProxy, btOverlappingPairCache *pairCache, btDispatcher *dispatcher) - :m_cleanProxy(cleanProxy), - m_pairCache(pairCache), - m_dispatcher(dispatcher) - { - } - - virtual bool processOverlap(btBroadphasePair &pair); -}; - -///CcdPhysicsController is a physics object that supports continuous collision detection and time of impact based physics resolution. -class CcdPhysicsController : public PHY_IPhysicsController -{ -protected: - btCollisionObject* m_object; - BlenderBulletCharacterController* m_characterController; - - - class PHY_IMotionState* m_MotionState; - btMotionState* m_bulletMotionState; - class btCollisionShape* m_collisionShape; - class CcdShapeConstructionInfo* m_shapeInfo; - btCollisionShape* m_bulletChildShape; - - btAlignedObjectArray m_ccdConstraintRefs; // keep track of typed constraints referencing this rigid body - friend class CcdPhysicsEnvironment; // needed when updating the controller - - //some book keeping for replication - bool m_softbodyMappingDone; - bool m_softBodyTransformInitialized; - bool m_prototypeTransformInitialized; - btTransform m_softbodyStartTrans; - - - void* m_newClientInfo; - int m_registerCount; // needed when multiple sensors use the same controller - CcdConstructionInfo m_cci;//needed for replication - - CcdPhysicsController* m_parentCtrl; - - int m_savedCollisionFlags; - short m_savedCollisionFilterGroup; - short m_savedCollisionFilterMask; - MT_Scalar m_savedMass; - bool m_savedDyna; - bool m_suspended; - - - void GetWorldOrientation(btMatrix3x3& mat); - - void CreateRigidbody(); - bool CreateSoftbody(); - bool CreateCharacterController(); - - bool Register() { - return (m_registerCount++ == 0) ? true : false; - } - bool Unregister() { - return (--m_registerCount == 0) ? true : false; - } - - bool Registered() const - { - return (m_registerCount != 0); - } - - void addCcdConstraintRef(btTypedConstraint* c); - void removeCcdConstraintRef(btTypedConstraint* c); - btTypedConstraint* getCcdConstraintRef(int index); - int getNumCcdConstraintRefs() const; - - void SetWorldOrientation(const btMatrix3x3& mat); - void ForceWorldTransform(const btMatrix3x3& mat, const btVector3& pos); - - public: - - int m_collisionDelay; - - - CcdPhysicsController (const CcdConstructionInfo& ci); - - /** - * Delete the current Bullet shape used in the rigid body. - */ - bool DeleteControllerShape(); - - /** - * Delete the old Bullet shape and set the new Bullet shape : newShape - * \param newShape The new Bullet shape to set, if is NULL we create a new Bullet shape - */ - bool ReplaceControllerShape(btCollisionShape *newShape); - - virtual ~CcdPhysicsController(); - - CcdConstructionInfo& GetConstructionInfo() - { - return m_cci; - } - const CcdConstructionInfo& GetConstructionInfo() const - { - return m_cci; - } - - - btRigidBody* GetRigidBody(); - const btRigidBody* GetRigidBody() const; - btCollisionObject* GetCollisionObject(); - btSoftBody* GetSoftBody(); - btKinematicCharacterController* GetCharacterController(); - - CcdShapeConstructionInfo* GetShapeInfo() { return m_shapeInfo; } - - btCollisionShape* GetCollisionShape() { - return m_object->getCollisionShape(); - } - //////////////////////////////////// - // PHY_IPhysicsController interface - //////////////////////////////////// - - - /** - * SynchronizeMotionStates ynchronizes dynas, kinematic and deformable entities (and do 'late binding') - */ - virtual bool SynchronizeMotionStates(float time); - - /** - * Called for every physics simulation step. Use this method for - * things like limiting linear and angular velocity. - */ - void SimulationTick(float timestep); - - /** - * WriteMotionStateToDynamics ynchronizes dynas, kinematic and deformable entities (and do 'late binding') - */ - - virtual void WriteMotionStateToDynamics(bool nondynaonly); - virtual void WriteDynamicsToMotionState(); - - // controller replication - virtual void PostProcessReplica(class PHY_IMotionState* motionstate,class PHY_IPhysicsController* parentctrl); - virtual void SetPhysicsEnvironment(class PHY_IPhysicsEnvironment *env); - - // kinematic methods - virtual void RelativeTranslate(const MT_Vector3& dloc,bool local); - virtual void RelativeRotate(const MT_Matrix3x3&rotval, bool local); - virtual MT_Matrix3x3 GetOrientation(); - virtual void SetOrientation(const MT_Matrix3x3& orn); - virtual void SetPosition(const MT_Vector3& pos); - virtual void GetPosition(MT_Vector3& pos) const; - virtual void SetScaling(const MT_Vector3& scale); - virtual void SetTransform(); - - virtual MT_Scalar GetMass(); - virtual void SetMass(MT_Scalar newmass); - - // physics methods - virtual void ApplyImpulse(const MT_Point3& attach, const MT_Vector3& impulsein, bool local); - virtual void ApplyTorque(const MT_Vector3& torque,bool local); - virtual void ApplyForce(const MT_Vector3& force,bool local); - virtual void SetAngularVelocity(const MT_Vector3& ang_vel,bool local); - virtual void SetLinearVelocity(const MT_Vector3& lin_vel,bool local); - virtual void Jump(); - virtual void SetActive(bool active); - - 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); - - // reading out information from physics - virtual MT_Vector3 GetLinearVelocity(); - virtual MT_Vector3 GetAngularVelocity(); - virtual MT_Vector3 GetVelocity(const MT_Point3& posin); - virtual MT_Vector3 GetLocalInertia(); - - // dyna's that are rigidbody are free in orientation, dyna's with non-rigidbody are restricted - virtual void SetRigidBody(bool rigid); - - - virtual void ResolveCombinedVelocities(float linvelX,float linvelY,float linvelZ,float angVelX,float angVelY,float angVelZ); - virtual void RefreshCollisions(); - virtual void SuspendDynamics(bool ghost); - virtual void RestoreDynamics(); - - // Shape control - virtual void AddCompoundChild(PHY_IPhysicsController* child); - virtual void RemoveCompoundChild(PHY_IPhysicsController* child); - - // clientinfo for raycasts for example - virtual void* GetNewClientInfo(); - virtual void SetNewClientInfo(void* clientinfo); - virtual PHY_IPhysicsController* GetReplica(); - virtual PHY_IPhysicsController* GetReplicaForSensors(); - - ///There should be no 'SetCollisionFilterGroup' method, as changing this during run-time is will result in errors - short int GetCollisionFilterGroup() const - { - return m_cci.m_collisionFilterGroup; - } - ///There should be no 'SetCollisionFilterGroup' method, as changing this during run-time is will result in errors - short int GetCollisionFilterMask() const - { - return m_cci.m_collisionFilterMask; - } - - virtual void CalcXform() {} - virtual void SetMargin(float margin) - { - if (m_collisionShape) { - m_collisionShape->setMargin(margin); - // if the shape use a unscaled shape we have also to set the correct margin in it - if (m_collisionShape->getShapeType() == SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE) - ((btScaledBvhTriangleMeshShape *)m_collisionShape)->getChildShape()->setMargin(margin); - } - } - virtual float GetMargin() const - { - return (m_collisionShape) ? m_collisionShape->getMargin() : 0.f; - } - virtual float GetRadius() const - { - // this is not the actual shape radius, it's only used for Fh support - return m_cci.m_radius; - } - virtual void SetRadius(float margin) - { - if (m_collisionShape && m_collisionShape->getShapeType() == SPHERE_SHAPE_PROXYTYPE) - { - btSphereShape* sphereShape = static_cast(m_collisionShape); - sphereShape->setUnscaledRadius(margin); - } - m_cci.m_radius = margin; - } - - // velocity clamping - virtual void SetLinVelocityMin(float val) - { - m_cci.m_clamp_vel_min= val; - } - virtual float GetLinVelocityMin() const - { - return m_cci.m_clamp_vel_min; - } - virtual void SetLinVelocityMax(float val) - { - m_cci.m_clamp_vel_max= val; - } - virtual float GetLinVelocityMax() const - { - return m_cci.m_clamp_vel_max; - } - - virtual void SetAngularVelocityMin(float val) - { - m_cci.m_clamp_angvel_min = val; - } - virtual float GetAngularVelocityMin() const - { - return m_cci.m_clamp_angvel_min; - } - virtual void SetAngularVelocityMax(float val) - { - m_cci.m_clamp_angvel_max = val; - } - virtual float GetAngularVelocityMax() const - { - return m_cci.m_clamp_angvel_max; - } - - bool WantsSleeping(); - - void UpdateDeactivation(float timeStep); - - void SetCenterOfMassTransform(btTransform& xform); - - static btTransform& GetTransformFromMotionState(PHY_IMotionState* motionState); - - void setAabb(const btVector3& aabbMin,const btVector3& aabbMax); - - - class PHY_IMotionState* GetMotionState() - { - return m_MotionState; - } - - const class PHY_IMotionState* GetMotionState() const - { - return m_MotionState; - } - - class CcdPhysicsEnvironment* GetPhysicsEnvironment() - { - return m_cci.m_physicsEnv; - } - - void SetParentCtrl(CcdPhysicsController* parentCtrl) - { - m_parentCtrl = parentCtrl; - } - - CcdPhysicsController* GetParentCtrl() - { - return m_parentCtrl; - } - - const CcdPhysicsController* GetParentCtrl() const - { - return m_parentCtrl; - } - - virtual bool IsDynamic() - { - return GetConstructionInfo().m_bDyna; - } - - virtual bool IsSuspended() const - { - return m_suspended; - } - - virtual bool IsCompound() - { - return GetConstructionInfo().m_shapeInfo->m_shapeType == PHY_SHAPE_COMPOUND; - } - - virtual bool ReinstancePhysicsShape(KX_GameObject *from_gameobj, RAS_MeshObject* from_meshobj); - - /* Method to replicate rigid body joint contraints for group instances. */ - virtual void ReplicateConstraints(KX_GameObject *gameobj, std::vector constobj); - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:CcdPhysicsController") -#endif -}; - - - - -///DefaultMotionState implements standard motionstate, using btTransform -class DefaultMotionState : public PHY_IMotionState - -{ - public: - DefaultMotionState(); - - virtual ~DefaultMotionState(); - - 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(); - - btTransform m_worldTransform; - btVector3 m_localScaling; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:DefaultMotionState") -#endif -}; - - -#endif /* __CCDPHYSICSCONTROLLER_H__ */ diff --git a/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp b/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp deleted file mode 100644 index 78d2d88cc65..00000000000 --- a/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp +++ /dev/null @@ -1,3795 +0,0 @@ -/** \file gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp - * \ingroup physbullet - */ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - - - - -#include "CcdPhysicsEnvironment.h" -#include "CcdPhysicsController.h" -#include "CcdGraphicController.h" - -#include -#include "btBulletDynamicsCommon.h" -#include "LinearMath/btIDebugDraw.h" -#include "BulletCollision/CollisionDispatch/btGhostObject.h" -#include "BulletCollision/CollisionDispatch/btSimulationIslandManager.h" -#include "BulletSoftBody/btSoftRigidDynamicsWorld.h" -#include "BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.h" -#include "BulletCollision/Gimpact/btGImpactCollisionAlgorithm.h" -#include "BulletCollision/NarrowPhaseCollision/btRaycastCallback.h" - -//profiling/timings -#include "LinearMath/btQuickprof.h" - - -#include "PHY_IMotionState.h" -#include "PHY_ICharacter.h" -#include "PHY_Pro.h" -#include "KX_GameObject.h" -#include "KX_PythonInit.h" // for KX_RasterizerDrawDebugLine -#include "KX_BlenderSceneConverter.h" -#include "RAS_MeshObject.h" -#include "RAS_Polygon.h" -#include "RAS_TexVert.h" - -#include "DNA_scene_types.h" -#include "DNA_world_types.h" -#include "DNA_object_force_types.h" - -extern "C" { - #include "BLI_utildefines.h" - #include "BKE_object.h" -} - -#define CCD_CONSTRAINT_DISABLE_LINKED_COLLISION 0x80 - -#ifdef NEW_BULLET_VEHICLE_SUPPORT -#include "BulletDynamics/Vehicle/btRaycastVehicle.h" -#include "BulletDynamics/Vehicle/btVehicleRaycaster.h" -#include "BulletDynamics/Vehicle/btWheelInfo.h" -#include "PHY_IVehicle.h" -static btRaycastVehicle::btVehicleTuning gTuning; - -#endif //NEW_BULLET_VEHICLE_SUPPORT -#include "LinearMath/btAabbUtil2.h" -#include "MT_Matrix4x4.h" -#include "MT_Vector3.h" -#include "MT_MinMax.h" - -#ifdef WIN32 -void DrawRasterizerLine(const float* from,const float* to,int color); -#endif - - -#include "BulletDynamics/ConstraintSolver/btContactConstraint.h" - - -#include -#include // for memset - -// This was copied from the old KX_ConvertPhysicsObjects -#ifdef WIN32 -#ifdef _MSC_VER -//only use SIMD Hull code under Win32 -//#define TEST_HULL 1 -#ifdef TEST_HULL -#define USE_HULL 1 -//#define TEST_SIMD_HULL 1 - -#include "NarrowPhaseCollision/Hull.h" -#endif //#ifdef TEST_HULL - -#endif //_MSC_VER -#endif //WIN32 - -#ifdef NEW_BULLET_VEHICLE_SUPPORT -class WrapperVehicle : public PHY_IVehicle -{ - - btRaycastVehicle* m_vehicle; - PHY_IPhysicsController* m_chassis; - -public: - - WrapperVehicle(btRaycastVehicle* vehicle,PHY_IPhysicsController* chassis) - :m_vehicle(vehicle), - m_chassis(chassis) - { - } - - ~WrapperVehicle() - { - delete m_vehicle; - } - - btRaycastVehicle* GetVehicle() - { - return m_vehicle; - } - - PHY_IPhysicsController* GetChassis() - { - return m_chassis; - } - - virtual void AddWheel( - PHY_IMotionState* motionState, - MT_Vector3 connectionPoint, - MT_Vector3 downDirection, - MT_Vector3 axleDirection, - float suspensionRestLength, - float wheelRadius, - bool hasSteering - ) - { - btVector3 connectionPointCS0(connectionPoint[0],connectionPoint[1],connectionPoint[2]); - btVector3 wheelDirectionCS0(downDirection[0],downDirection[1],downDirection[2]); - btVector3 wheelAxle(axleDirection[0],axleDirection[1],axleDirection[2]); - - - btWheelInfo& info = m_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxle, - suspensionRestLength,wheelRadius,gTuning,hasSteering); - info.m_clientInfo = motionState; - - } - - void SyncWheels() - { - int numWheels = GetNumWheels(); - int i; - for (i=0;igetWheelInfo(i); - PHY_IMotionState* motionState = (PHY_IMotionState*)info.m_clientInfo; - // m_vehicle->updateWheelTransformsWS(info,false); - m_vehicle->updateWheelTransform(i,false); - btTransform trans = m_vehicle->getWheelInfo(i).m_worldTransform; - btQuaternion orn = trans.getRotation(); - const btVector3& pos = trans.getOrigin(); - motionState->SetWorldOrientation(orn.x(),orn.y(),orn.z(),orn[3]); - motionState->SetWorldPosition(pos.x(),pos.y(),pos.z()); - - } - } - - virtual int GetNumWheels() const - { - return m_vehicle->getNumWheels(); - } - - virtual void GetWheelPosition(int wheelIndex,float& posX,float& posY,float& posZ) const - { - if ((wheelIndex>=0) && (wheelIndex< m_vehicle->getNumWheels())) - { - btVector3 origin = m_vehicle->getWheelTransformWS(wheelIndex).getOrigin(); - - posX = origin.x(); - posY = origin.y(); - posZ = origin.z(); - } - } - - virtual void GetWheelOrientationQuaternion(int wheelIndex,float& quatX,float& quatY,float& quatZ,float& quatW) const - { - if ((wheelIndex>=0) && (wheelIndex< m_vehicle->getNumWheels())) - { - btQuaternion quat = m_vehicle->getWheelTransformWS(wheelIndex).getRotation(); - - quatX = quat.x(); - quatY = quat.y(); - quatZ = quat.z(); - quatW = quat.w(); - } - } - - virtual float GetWheelRotation(int wheelIndex) const - { - float rotation = 0.f; - - if ((wheelIndex>=0) && (wheelIndex< m_vehicle->getNumWheels())) - { - btWheelInfo& info = m_vehicle->getWheelInfo(wheelIndex); - rotation = info.m_rotation; - } - - return rotation; - } - - - - virtual int GetUserConstraintId() const - { - return m_vehicle->getUserConstraintId(); - } - - virtual int GetUserConstraintType() const - { - return m_vehicle->getUserConstraintType(); - } - - virtual void SetSteeringValue(float steering,int wheelIndex) - { - if ((wheelIndex>=0) && (wheelIndex< m_vehicle->getNumWheels())) { - m_vehicle->setSteeringValue(steering,wheelIndex); - } - } - - virtual void ApplyEngineForce(float force,int wheelIndex) - { - if ((wheelIndex>=0) && (wheelIndex< m_vehicle->getNumWheels())) { - m_vehicle->applyEngineForce(force,wheelIndex); - } - } - - virtual void ApplyBraking(float braking,int wheelIndex) - { - if ((wheelIndex>=0) && (wheelIndex< m_vehicle->getNumWheels())) - { - btWheelInfo& info = m_vehicle->getWheelInfo(wheelIndex); - info.m_brake = braking; - } - } - - virtual void SetWheelFriction(float friction,int wheelIndex) - { - if ((wheelIndex>=0) && (wheelIndex< m_vehicle->getNumWheels())) - { - btWheelInfo& info = m_vehicle->getWheelInfo(wheelIndex); - info.m_frictionSlip = friction; - } - - } - - virtual void SetSuspensionStiffness(float suspensionStiffness,int wheelIndex) - { - if ((wheelIndex>=0) && (wheelIndex< m_vehicle->getNumWheels())) - { - btWheelInfo& info = m_vehicle->getWheelInfo(wheelIndex); - info.m_suspensionStiffness = suspensionStiffness; - - } - } - - virtual void SetSuspensionDamping(float suspensionDamping,int wheelIndex) - { - if ((wheelIndex>=0) && (wheelIndex< m_vehicle->getNumWheels())) - { - btWheelInfo& info = m_vehicle->getWheelInfo(wheelIndex); - info.m_wheelsDampingRelaxation = suspensionDamping; - } - } - - virtual void SetSuspensionCompression(float suspensionCompression,int wheelIndex) - { - if ((wheelIndex>=0) && (wheelIndex< m_vehicle->getNumWheels())) - { - btWheelInfo& info = m_vehicle->getWheelInfo(wheelIndex); - info.m_wheelsDampingCompression = suspensionCompression; - } - } - - - - virtual void SetRollInfluence(float rollInfluence,int wheelIndex) - { - if ((wheelIndex>=0) && (wheelIndex< m_vehicle->getNumWheels())) - { - btWheelInfo& info = m_vehicle->getWheelInfo(wheelIndex); - info.m_rollInfluence = rollInfluence; - } - } - - virtual void SetCoordinateSystem(int rightIndex,int upIndex,int forwardIndex) - { - m_vehicle->setCoordinateSystem(rightIndex,upIndex,forwardIndex); - } - - - -}; - -class BlenderVehicleRaycaster: public btDefaultVehicleRaycaster -{ - btDynamicsWorld* m_dynamicsWorld; -public: - BlenderVehicleRaycaster(btDynamicsWorld* world) - :btDefaultVehicleRaycaster(world), m_dynamicsWorld(world) - { - } - - virtual void* castRay(const btVector3& from,const btVector3& to, btVehicleRaycasterResult& result) - { - // RayResultCallback& resultCallback; - - btCollisionWorld::ClosestRayResultCallback rayCallback(from,to); - - // We override btDefaultVehicleRaycaster so we can set this flag, otherwise our - // vehicles go crazy (http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=9662) - rayCallback.m_flags |= btTriangleRaycastCallback::kF_UseSubSimplexConvexCastRaytest; - - m_dynamicsWorld->rayTest(from, to, rayCallback); - - if (rayCallback.hasHit()) - { - - const btRigidBody* body = btRigidBody::upcast(rayCallback.m_collisionObject); - if (body && body->hasContactResponse()) - { - result.m_hitPointInWorld = rayCallback.m_hitPointWorld; - result.m_hitNormalInWorld = rayCallback.m_hitNormalWorld; - result.m_hitNormalInWorld.normalize(); - result.m_distFraction = rayCallback.m_closestHitFraction; - return (void*)body; - } - } - return 0; - } -}; -#endif //NEW_BULLET_VEHICLE_SUPPORT - -class CcdOverlapFilterCallBack : public btOverlapFilterCallback -{ -private: - class CcdPhysicsEnvironment* m_physEnv; -public: - CcdOverlapFilterCallBack(CcdPhysicsEnvironment* env) : - m_physEnv(env) - { - } - virtual ~CcdOverlapFilterCallBack() - { - } - // return true when pairs need collision - virtual bool needBroadphaseCollision(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) const; -}; - - -void CcdPhysicsEnvironment::SetDebugDrawer(btIDebugDraw* debugDrawer) -{ - if (debugDrawer && m_dynamicsWorld) - m_dynamicsWorld->setDebugDrawer(debugDrawer); - m_debugDrawer = debugDrawer; -} - -#if 0 -static void DrawAabb(btIDebugDraw* debugDrawer,const btVector3& from,const btVector3& to,const btVector3& color) -{ - btVector3 halfExtents = (to-from)* 0.5f; - btVector3 center = (to+from) *0.5f; - int i,j; - - btVector3 edgecoord(1.f,1.f,1.f),pa,pb; - for (i=0;i<4;i++) - { - for (j=0;j<3;j++) - { - pa = btVector3(edgecoord[0]*halfExtents[0], edgecoord[1]*halfExtents[1], - edgecoord[2]*halfExtents[2]); - pa+=center; - - int othercoord = j%3; - edgecoord[othercoord]*=-1.f; - pb = btVector3(edgecoord[0]*halfExtents[0], edgecoord[1]*halfExtents[1], - edgecoord[2]*halfExtents[2]); - pb+=center; - - debugDrawer->drawLine(pa,pb,color); - } - edgecoord = btVector3(-1.f,-1.f,-1.f); - if (i<3) - edgecoord[i]*=-1.f; - } -} -#endif - - - - - -CcdPhysicsEnvironment::CcdPhysicsEnvironment(bool useDbvtCulling,btDispatcher* dispatcher,btOverlappingPairCache* pairCache) -:m_cullingCache(NULL), -m_cullingTree(NULL), -m_numIterations(10), -m_numTimeSubSteps(1), -m_ccdMode(0), -m_solverType(-1), -m_profileTimings(0), -m_enableSatCollisionDetection(false), -m_deactivationTime(2.0f), -m_linearDeactivationThreshold(0.8f), -m_angularDeactivationThreshold(1.0f), -m_contactBreakingThreshold(0.02f), -m_solver(NULL), -m_ownPairCache(NULL), -m_filterCallback(NULL), -m_ghostPairCallback(NULL), -m_ownDispatcher(NULL), -m_scalingPropagated(false) -{ - - for (int i=0;isetConvexConvexMultipointIterations(); - - if (!dispatcher) - { - btCollisionDispatcher* disp = new btCollisionDispatcher(m_collisionConfiguration); - dispatcher = disp; - btGImpactCollisionAlgorithm::registerAlgorithm(disp); - m_ownDispatcher = dispatcher; - } - - //m_broadphase = new btAxisSweep3(btVector3(-1000,-1000,-1000),btVector3(1000,1000,1000)); - //m_broadphase = new btSimpleBroadphase(); - m_broadphase = new btDbvtBroadphase(); - // avoid any collision in the culling tree - if (useDbvtCulling) { - m_cullingCache = new btNullPairCache(); - m_cullingTree = new btDbvtBroadphase(m_cullingCache); - } - - m_filterCallback = new CcdOverlapFilterCallBack(this); - m_ghostPairCallback = new btGhostPairCallback(); - m_broadphase->getOverlappingPairCache()->setOverlapFilterCallback(m_filterCallback); - m_broadphase->getOverlappingPairCache()->setInternalGhostPairCallback(m_ghostPairCallback); - - SetSolverType(1);//issues with quickstep and memory allocations -// m_dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher,m_broadphase,m_solver,m_collisionConfiguration); - m_dynamicsWorld = new btSoftRigidDynamicsWorld(dispatcher,m_broadphase,m_solver,m_collisionConfiguration); - m_dynamicsWorld->setInternalTickCallback(&CcdPhysicsEnvironment::StaticSimulationSubtickCallback, this); - //m_dynamicsWorld->getSolverInfo().m_linearSlop = 0.01f; - //m_dynamicsWorld->getSolverInfo().m_solverMode= SOLVER_USE_WARMSTARTING + SOLVER_USE_2_FRICTION_DIRECTIONS + SOLVER_RANDMIZE_ORDER + SOLVER_USE_FRICTION_WARMSTARTING; - - m_debugDrawer = 0; - SetGravity(0.f,0.f,-9.81f); -} - -void CcdPhysicsEnvironment::AddCcdPhysicsController(CcdPhysicsController* ctrl) -{ - // the controller is already added we do nothing - if (!m_controllers.insert(ctrl).second) { - return; - } - - btRigidBody* body = ctrl->GetRigidBody(); - btCollisionObject* obj = ctrl->GetCollisionObject(); - - //this m_userPointer is just used for triggers, see CallbackTriggers - obj->setUserPointer(ctrl); - if (body) { - body->setGravity(m_gravity); - body->setSleepingThresholds(m_linearDeactivationThreshold, m_angularDeactivationThreshold); - } - - if (body) - { - //use explicit group/filter for finer control over collision in bullet => near/radar sensor - m_dynamicsWorld->addRigidBody(body, ctrl->GetCollisionFilterGroup(), ctrl->GetCollisionFilterMask()); - } else - { - if (ctrl->GetSoftBody()) - { - btSoftBody* softBody = ctrl->GetSoftBody(); - m_dynamicsWorld->addSoftBody(softBody); - } else - { - if (obj->getCollisionShape()) - { - m_dynamicsWorld->addCollisionObject(obj, ctrl->GetCollisionFilterGroup(), ctrl->GetCollisionFilterMask()); - } - if (ctrl->GetCharacterController()) - { - m_dynamicsWorld->addAction(ctrl->GetCharacterController()); - } - } - } - if (obj->isStaticOrKinematicObject()) - { - obj->setActivationState(ISLAND_SLEEPING); - } - - assert(obj->getBroadphaseHandle()); -} - -void CcdPhysicsEnvironment::RemoveConstraint(btTypedConstraint *con) -{ - btRigidBody &rbA = con->getRigidBodyA(); - btRigidBody &rbB = con->getRigidBodyB(); - rbA.activate(); - rbB.activate(); - m_dynamicsWorld->removeConstraint(con); - - if (rbA.getUserPointer()) { - ((CcdPhysicsController *)rbA.getUserPointer())->removeCcdConstraintRef(con); - } - - if (rbB.getUserPointer()) { - ((CcdPhysicsController *)rbB.getUserPointer())->removeCcdConstraintRef(con); - } - - /* Since we remove the constraint in the onwer and the target, we can delete it, - * KX_ConstraintWrapper keep the constraint id not the pointer, so no problems. */ - delete con; -} - -bool CcdPhysicsEnvironment::RemoveCcdPhysicsController(CcdPhysicsController* ctrl) -{ - // if the physics controller is already removed we do nothing - if (!m_controllers.erase(ctrl)) { - return false; - } - - //also remove constraint - btRigidBody* body = ctrl->GetRigidBody(); - if (body) - { - btBroadphaseProxy *proxy = ctrl->GetCollisionObject()->getBroadphaseHandle(); - btDispatcher *dispatcher = m_dynamicsWorld->getDispatcher(); - btOverlappingPairCache *pairCache = m_dynamicsWorld->getPairCache(); - - CleanPairCallback cleanPairs(proxy, pairCache, dispatcher); - pairCache->processAllOverlappingPairs(&cleanPairs, dispatcher); - - for (int i = ctrl->getNumCcdConstraintRefs() - 1; i >= 0; i--) - { - btTypedConstraint* con = ctrl->getCcdConstraintRef(i); - RemoveConstraint(con); - } - m_dynamicsWorld->removeRigidBody(ctrl->GetRigidBody()); - - // Handle potential vehicle constraints - int numVehicles = m_wrapperVehicles.size(); - int vehicle_constraint = 0; - for (int i=0;iGetChassis() == ctrl) - vehicle_constraint = wrapperVehicle->GetVehicle()->getUserConstraintId(); - } - - if (vehicle_constraint > 0) - RemoveConstraintById(vehicle_constraint); - } else - { - //if a softbody - if (ctrl->GetSoftBody()) - { - m_dynamicsWorld->removeSoftBody(ctrl->GetSoftBody()); - } else - { - m_dynamicsWorld->removeCollisionObject(ctrl->GetCollisionObject()); - - if (ctrl->GetCharacterController()) - { - m_dynamicsWorld->removeAction(ctrl->GetCharacterController()); - } - } - } - - return true; -} - -void CcdPhysicsEnvironment::UpdateCcdPhysicsController(CcdPhysicsController* ctrl, btScalar newMass, int newCollisionFlags, short int newCollisionGroup, short int newCollisionMask) -{ - // this function is used when the collisionning group of a controller is changed - // remove and add the collistioning object - btRigidBody* body = ctrl->GetRigidBody(); - btSoftBody *softBody = ctrl->GetSoftBody(); - btCollisionObject* obj = ctrl->GetCollisionObject(); - if (obj) - { - btVector3 inertia(0.0f,0.0f,0.0f); - m_dynamicsWorld->removeCollisionObject(obj); - obj->setCollisionFlags(newCollisionFlags); - if (body) - { - if (newMass) - body->getCollisionShape()->calculateLocalInertia(newMass, inertia); - body->setMassProps(newMass, inertia); - m_dynamicsWorld->addRigidBody(body, newCollisionGroup, newCollisionMask); - } - else if (softBody) { - m_dynamicsWorld->addSoftBody(softBody); - } - else { - m_dynamicsWorld->addCollisionObject(obj, newCollisionGroup, newCollisionMask); - } - } - // to avoid nasty interaction, we must update the property of the controller as well - ctrl->m_cci.m_mass = newMass; - ctrl->m_cci.m_collisionFilterGroup = newCollisionGroup; - ctrl->m_cci.m_collisionFilterMask = newCollisionMask; - ctrl->m_cci.m_collisionFlags = newCollisionFlags; -} - -void CcdPhysicsEnvironment::RefreshCcdPhysicsController(CcdPhysicsController* ctrl) -{ - btCollisionObject* obj = ctrl->GetCollisionObject(); - if (obj) - { - btBroadphaseProxy* proxy = obj->getBroadphaseHandle(); - if (proxy) - { - m_dynamicsWorld->getPairCache()->cleanProxyFromPairs(proxy,m_dynamicsWorld->getDispatcher()); - } - } -} - -bool CcdPhysicsEnvironment::IsActiveCcdPhysicsController(CcdPhysicsController *ctrl) -{ - return (m_controllers.find(ctrl) != m_controllers.end()); -} - -void CcdPhysicsEnvironment::AddCcdGraphicController(CcdGraphicController* ctrl) -{ - if (m_cullingTree && !ctrl->GetBroadphaseHandle()) - { - btVector3 minAabb; - btVector3 maxAabb; - ctrl->GetAabb(minAabb, maxAabb); - - ctrl->SetBroadphaseHandle(m_cullingTree->createProxy( - minAabb, - maxAabb, - INVALID_SHAPE_PROXYTYPE, // this parameter is not used - ctrl, - 0, // this object does not collision with anything - 0, - NULL, // dispatcher => this parameter is not used - 0)); - - assert(ctrl->GetBroadphaseHandle()); - } -} - -void CcdPhysicsEnvironment::RemoveCcdGraphicController(CcdGraphicController* ctrl) -{ - if (m_cullingTree) - { - btBroadphaseProxy* bp = ctrl->GetBroadphaseHandle(); - if (bp) - { - m_cullingTree->destroyProxy(bp,NULL); - ctrl->SetBroadphaseHandle(0); - } - } -} - -void CcdPhysicsEnvironment::UpdateCcdPhysicsControllerShape(CcdShapeConstructionInfo *shapeInfo) -{ - for (std::set::iterator it = m_controllers.begin(); it != m_controllers.end(); ++it) { - CcdPhysicsController *ctrl = *it; - - if (ctrl->GetShapeInfo() != shapeInfo) - continue; - - ctrl->ReplaceControllerShape(NULL); - RefreshCcdPhysicsController(ctrl); - } -} - -void CcdPhysicsEnvironment::BeginFrame() -{ - -} - -void CcdPhysicsEnvironment::DebugDrawWorld() -{ - if (m_dynamicsWorld->getDebugDrawer() && m_dynamicsWorld->getDebugDrawer()->getDebugMode() >0) - m_dynamicsWorld->debugDrawWorld(); -} - -void CcdPhysicsEnvironment::StaticSimulationSubtickCallback(btDynamicsWorld *world, btScalar timeStep) -{ - // Get the pointer to the CcdPhysicsEnvironment associated with this Bullet world. - CcdPhysicsEnvironment *this_ = static_cast(world->getWorldUserInfo()); - this_->SimulationSubtickCallback(timeStep); -} - -void CcdPhysicsEnvironment::SimulationSubtickCallback(btScalar timeStep) -{ - std::set::iterator it; - - for (it = m_controllers.begin(); it != m_controllers.end(); it++) { - (*it)->SimulationTick(timeStep); - } -} - -bool CcdPhysicsEnvironment::ProceedDeltaTime(double curTime,float timeStep,float interval) -{ - std::set::iterator it; - int i; - - // Update Bullet global variables. - gDeactivationTime = m_deactivationTime; - gContactBreakingThreshold = m_contactBreakingThreshold; - - for (it=m_controllers.begin(); it!=m_controllers.end(); it++) - { - (*it)->SynchronizeMotionStates(timeStep); - } - - float subStep = timeStep / float(m_numTimeSubSteps); - i = m_dynamicsWorld->stepSimulation(interval,25,subStep);//perform always a full simulation step -//uncomment next line to see where Bullet spend its time (printf in console) -//CProfileManager::dumpAll(); - - ProcessFhSprings(curTime,i*subStep); - - for (it=m_controllers.begin(); it!=m_controllers.end(); it++) - { - (*it)->SynchronizeMotionStates(timeStep); - } - - //for (it=m_controllers.begin(); it!=m_controllers.end(); it++) - //{ - // (*it)->SynchronizeMotionStates(timeStep); - //} - - for (i=0;iSyncWheels(); - } - - - CallbackTriggers(); - - return true; -} - -class ClosestRayResultCallbackNotMe : public btCollisionWorld::ClosestRayResultCallback -{ - btCollisionObject* m_owner; - btCollisionObject* m_parent; - -public: - ClosestRayResultCallbackNotMe(const btVector3& rayFromWorld,const btVector3& rayToWorld,btCollisionObject* owner,btCollisionObject* parent) - :btCollisionWorld::ClosestRayResultCallback(rayFromWorld,rayToWorld), - m_owner(owner), - m_parent(parent) - { - - } - - virtual bool needsCollision(btBroadphaseProxy* proxy0) const - { - //don't collide with self - if (proxy0->m_clientObject == m_owner) - return false; - - if (proxy0->m_clientObject == m_parent) - return false; - - return btCollisionWorld::ClosestRayResultCallback::needsCollision(proxy0); - } - -}; - -void CcdPhysicsEnvironment::ProcessFhSprings(double curTime,float interval) -{ - std::set::iterator it; - // Add epsilon to the tick rate for numerical stability - int numIter = (int)(interval*(KX_KetsjiEngine::GetTicRate() + 0.001f)); - - for (it=m_controllers.begin(); it!=m_controllers.end(); it++) - { - CcdPhysicsController* ctrl = (*it); - btRigidBody* body = ctrl->GetRigidBody(); - - if (body && (ctrl->GetConstructionInfo().m_do_fh || ctrl->GetConstructionInfo().m_do_rot_fh)) - { - //printf("has Fh or RotFh\n"); - //re-implement SM_FhObject.cpp using btCollisionWorld::rayTest and info from ctrl->getConstructionInfo() - //send a ray from {0.0, 0.0, 0.0} towards {0.0, 0.0, -10.0}, in local coordinates - CcdPhysicsController* parentCtrl = ctrl->GetParentCtrl(); - btRigidBody* parentBody = parentCtrl?parentCtrl->GetRigidBody() : 0; - btRigidBody* cl_object = parentBody ? parentBody : body; - - if (body->isStaticOrKinematicObject()) - continue; - - btVector3 rayDirLocal(0,0,-10); - - //m_dynamicsWorld - //ctrl->GetRigidBody(); - btVector3 rayFromWorld = body->getCenterOfMassPosition(); - //btVector3 rayToWorld = rayFromWorld + body->getCenterOfMassTransform().getBasis() * rayDirLocal; - //ray always points down the z axis in world space... - btVector3 rayToWorld = rayFromWorld + rayDirLocal; - - ClosestRayResultCallbackNotMe resultCallback(rayFromWorld,rayToWorld,body,parentBody); - - m_dynamicsWorld->rayTest(rayFromWorld,rayToWorld,resultCallback); - if (resultCallback.hasHit()) - { - //we hit this one: resultCallback.m_collisionObject; - CcdPhysicsController* controller = static_cast(resultCallback.m_collisionObject->getUserPointer()); - - if (controller) - { - if (controller->GetConstructionInfo().m_fh_distance < SIMD_EPSILON) - continue; - - btRigidBody* hit_object = controller->GetRigidBody(); - if (!hit_object) - continue; - - CcdConstructionInfo& hitObjShapeProps = controller->GetConstructionInfo(); - - float distance = resultCallback.m_closestHitFraction*rayDirLocal.length()-ctrl->GetConstructionInfo().m_radius; - if (distance >= hitObjShapeProps.m_fh_distance) - continue; - - - - //btVector3 ray_dir = cl_object->getCenterOfMassTransform().getBasis()* rayDirLocal.normalized(); - btVector3 ray_dir = rayDirLocal.normalized(); - btVector3 normal = resultCallback.m_hitNormalWorld; - normal.normalize(); - - for (int i=0; iGetConstructionInfo().m_do_fh) - { - btVector3 lspot = cl_object->getCenterOfMassPosition() + - rayDirLocal * resultCallback.m_closestHitFraction; - - - - - lspot -= hit_object->getCenterOfMassPosition(); - btVector3 rel_vel = cl_object->getLinearVelocity() - hit_object->getVelocityInLocalPoint(lspot); - btScalar rel_vel_ray = ray_dir.dot(rel_vel); - btScalar spring_extent = 1.0f - distance / hitObjShapeProps.m_fh_distance; - - btScalar i_spring = spring_extent * hitObjShapeProps.m_fh_spring; - btScalar i_damp = rel_vel_ray * hitObjShapeProps.m_fh_damping; - - cl_object->setLinearVelocity(cl_object->getLinearVelocity() + (-(i_spring + i_damp) * ray_dir)); - if (hitObjShapeProps.m_fh_normal) - { - cl_object->setLinearVelocity(cl_object->getLinearVelocity()+(i_spring + i_damp) *(normal - normal.dot(ray_dir) * ray_dir)); - } - - btVector3 lateral = rel_vel - rel_vel_ray * ray_dir; - - - if (ctrl->GetConstructionInfo().m_do_anisotropic) { - //Bullet basis contains no scaling/shear etc. - const btMatrix3x3& lcs = cl_object->getCenterOfMassTransform().getBasis(); - btVector3 loc_lateral = lateral * lcs; - const btVector3& friction_scaling = cl_object->getAnisotropicFriction(); - loc_lateral *= friction_scaling; - lateral = lcs * loc_lateral; - } - - btScalar rel_vel_lateral = lateral.length(); - - if (rel_vel_lateral > SIMD_EPSILON) { - btScalar friction_factor = hit_object->getFriction();//cl_object->getFriction(); - - btScalar max_friction = friction_factor * btMax(btScalar(0.0f), i_spring); - - btScalar rel_mom_lateral = rel_vel_lateral / cl_object->getInvMass(); - - btVector3 friction = (rel_mom_lateral > max_friction) ? - -lateral * (max_friction / rel_vel_lateral) : - -lateral; - - cl_object->applyCentralImpulse(friction); - } - } - - - if (ctrl->GetConstructionInfo().m_do_rot_fh) { - btVector3 up2 = cl_object->getWorldTransform().getBasis().getColumn(2); - - btVector3 t_spring = up2.cross(normal) * hitObjShapeProps.m_fh_spring; - btVector3 ang_vel = cl_object->getAngularVelocity(); - - // only rotations that tilt relative to the normal are damped - ang_vel -= ang_vel.dot(normal) * normal; - - btVector3 t_damp = ang_vel * hitObjShapeProps.m_fh_damping; - - cl_object->setAngularVelocity(cl_object->getAngularVelocity() + (t_spring - t_damp)); - } - } - } - } - } - } -} - -int CcdPhysicsEnvironment::GetDebugMode() const -{ - if (m_debugDrawer) { - return m_debugDrawer->getDebugMode(); - } - return 0; -} - -void CcdPhysicsEnvironment::SetDebugMode(int debugMode) -{ - if (m_debugDrawer) { - m_debugDrawer->setDebugMode(debugMode); - } -} - -void CcdPhysicsEnvironment::SetNumIterations(int numIter) -{ - m_numIterations = numIter; -} -void CcdPhysicsEnvironment::SetDeactivationTime(float dTime) -{ - m_deactivationTime = dTime; -} -void CcdPhysicsEnvironment::SetDeactivationLinearTreshold(float linTresh) -{ - m_linearDeactivationThreshold = linTresh; - - // Update from all controllers. - for (std::set::iterator it = m_controllers.begin(); it != m_controllers.end(); it++) { - if ((*it)->GetRigidBody()) - (*it)->GetRigidBody()->setSleepingThresholds(m_linearDeactivationThreshold, m_angularDeactivationThreshold); - } -} -void CcdPhysicsEnvironment::SetDeactivationAngularTreshold(float angTresh) -{ - m_angularDeactivationThreshold = angTresh; - - // Update from all controllers. - for (std::set::iterator it = m_controllers.begin(); it != m_controllers.end(); it++) { - if ((*it)->GetRigidBody()) - (*it)->GetRigidBody()->setSleepingThresholds(m_linearDeactivationThreshold, m_angularDeactivationThreshold); - } -} - -void CcdPhysicsEnvironment::SetContactBreakingTreshold(float contactBreakingTreshold) -{ - m_contactBreakingThreshold = contactBreakingTreshold; -} - - -void CcdPhysicsEnvironment::SetCcdMode(int ccdMode) -{ - m_ccdMode = ccdMode; -} - - -void CcdPhysicsEnvironment::SetSolverSorConstant(float sor) -{ - m_dynamicsWorld->getSolverInfo().m_sor = sor; -} - -void CcdPhysicsEnvironment::SetSolverTau(float tau) -{ - m_dynamicsWorld->getSolverInfo().m_tau = tau; -} -void CcdPhysicsEnvironment::SetSolverDamping(float damping) -{ - m_dynamicsWorld->getSolverInfo().m_damping = damping; -} - - -void CcdPhysicsEnvironment::SetLinearAirDamping(float damping) -{ - //gLinearAirDamping = damping; -} - -void CcdPhysicsEnvironment::SetUseEpa(bool epa) -{ - //gUseEpa = epa; -} - -void CcdPhysicsEnvironment::SetSolverType(int solverType) -{ - - switch (solverType) - { - case 1: - { - if (m_solverType != solverType) - { - - m_solver = new btSequentialImpulseConstraintSolver(); - - - break; - } - } - - case 0: - default: - if (m_solverType != solverType) - { -// m_solver = new OdeConstraintSolver(); - - break; - } - - }; - - m_solverType = solverType; -} - - - -void CcdPhysicsEnvironment::GetGravity(MT_Vector3& grav) -{ - const btVector3& gravity = m_dynamicsWorld->getGravity(); - grav[0] = gravity.getX(); - grav[1] = gravity.getY(); - grav[2] = gravity.getZ(); -} - - -void CcdPhysicsEnvironment::SetGravity(float x,float y,float z) -{ - m_gravity = btVector3(x,y,z); - m_dynamicsWorld->setGravity(m_gravity); - m_dynamicsWorld->getWorldInfo().m_gravity.setValue(x,y,z); -} - - - - -static int gConstraintUid = 1; - -//Following the COLLADA physics specification for constraints -int CcdPhysicsEnvironment::CreateUniversalD6Constraint( - class PHY_IPhysicsController* ctrlRef,class PHY_IPhysicsController* ctrlOther, - btTransform& frameInA, - btTransform& frameInB, - const btVector3& linearMinLimits, - const btVector3& linearMaxLimits, - const btVector3& angularMinLimits, - const btVector3& angularMaxLimits,int flags -) -{ - - bool disableCollisionBetweenLinkedBodies = (0!=(flags & CCD_CONSTRAINT_DISABLE_LINKED_COLLISION)); - - //we could either add some logic to recognize ball-socket and hinge, or let that up to the user - //perhaps some warning or hint that hinge/ball-socket is more efficient? - - - btGeneric6DofConstraint* genericConstraint = 0; - CcdPhysicsController* ctrl0 = (CcdPhysicsController*) ctrlRef; - CcdPhysicsController* ctrl1 = (CcdPhysicsController*) ctrlOther; - - btRigidBody* rb0 = ctrl0->GetRigidBody(); - btRigidBody* rb1 = ctrl1->GetRigidBody(); - - if (rb1) - { - - - bool useReferenceFrameA = true; - genericConstraint = new btGeneric6DofSpringConstraint( - *rb0,*rb1, - frameInA,frameInB,useReferenceFrameA); - genericConstraint->setLinearLowerLimit(linearMinLimits); - genericConstraint->setLinearUpperLimit(linearMaxLimits); - genericConstraint->setAngularLowerLimit(angularMinLimits); - genericConstraint->setAngularUpperLimit(angularMaxLimits); - } else - { - // TODO: Implement single body case... - //No, we can use a fixed rigidbody in above code, rather than unnecessary duplation of code - - } - - if (genericConstraint) - { - // m_constraints.push_back(genericConstraint); - m_dynamicsWorld->addConstraint(genericConstraint,disableCollisionBetweenLinkedBodies); - - genericConstraint->setUserConstraintId(gConstraintUid++); - genericConstraint->setUserConstraintType(PHY_GENERIC_6DOF_CONSTRAINT); - //64 bit systems can't cast pointer to int. could use size_t instead. - return genericConstraint->getUserConstraintId(); - } - return 0; -} - -void CcdPhysicsEnvironment::RemoveConstraintById(int constraintId) -{ - // For soft body constraints - if (constraintId == 0) - return; - - int i; - int numConstraints = m_dynamicsWorld->getNumConstraints(); - for (i=0;igetConstraint(i); - if (constraint->getUserConstraintId() == constraintId) - { - RemoveConstraint(constraint); - break; - } - } - - WrapperVehicle *vehicle; - if ((vehicle = (WrapperVehicle*)GetVehicleConstraint(constraintId))) - { - m_dynamicsWorld->removeVehicle(vehicle->GetVehicle()); - m_wrapperVehicles.erase(std::remove(m_wrapperVehicles.begin(), m_wrapperVehicles.end(), vehicle)); - delete vehicle; - } -} - - -struct FilterClosestRayResultCallback : public btCollisionWorld::ClosestRayResultCallback -{ - PHY_IRayCastFilterCallback& m_phyRayFilter; - const btCollisionShape* m_hitTriangleShape; - int m_hitTriangleIndex; - - - FilterClosestRayResultCallback (PHY_IRayCastFilterCallback& phyRayFilter,const btVector3& rayFrom,const btVector3& rayTo) - : btCollisionWorld::ClosestRayResultCallback(rayFrom,rayTo), - m_phyRayFilter(phyRayFilter), - m_hitTriangleShape(NULL), - m_hitTriangleIndex(0) - { - } - - virtual ~FilterClosestRayResultCallback() - { - } - - virtual bool needsCollision(btBroadphaseProxy* proxy0) const - { - if (!(proxy0->m_collisionFilterGroup & m_collisionFilterMask)) - return false; - if (!(m_collisionFilterGroup & proxy0->m_collisionFilterMask)) - return false; - btCollisionObject* object = (btCollisionObject*)proxy0->m_clientObject; - CcdPhysicsController* phyCtrl = static_cast(object->getUserPointer()); - if (phyCtrl == m_phyRayFilter.m_ignoreController) - return false; - return m_phyRayFilter.needBroadphaseRayCast(phyCtrl); - } - - virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult& rayResult,bool normalInWorldSpace) - { - //CcdPhysicsController* curHit = static_cast(rayResult.m_collisionObject->getUserPointer()); - // save shape information as ClosestRayResultCallback::AddSingleResult() does not do it - if (rayResult.m_localShapeInfo) - { - m_hitTriangleShape = rayResult.m_collisionObject->getCollisionShape(); - m_hitTriangleIndex = rayResult.m_localShapeInfo->m_triangleIndex; - } else - { - m_hitTriangleShape = NULL; - m_hitTriangleIndex = 0; - } - return ClosestRayResultCallback::addSingleResult(rayResult,normalInWorldSpace); - } - -}; - -static bool GetHitTriangle(btCollisionShape* shape, CcdShapeConstructionInfo* shapeInfo, int hitTriangleIndex, btVector3 triangle[]) -{ - // this code is copied from Bullet - const unsigned char *vertexbase; - int numverts; - PHY_ScalarType type; - int stride; - const unsigned char *indexbase; - int indexstride; - int numfaces; - PHY_ScalarType indicestype; - btStridingMeshInterface* meshInterface = shapeInfo->GetMeshInterface(); - - if (!meshInterface) - return false; - - meshInterface->getLockedReadOnlyVertexIndexBase( - &vertexbase, - numverts, - type, - stride, - &indexbase, - indexstride, - numfaces, - indicestype, - 0); - - unsigned int* gfxbase = (unsigned int*)(indexbase+hitTriangleIndex*indexstride); - const btVector3& meshScaling = shape->getLocalScaling(); - for (int j=2;j>=0;j--) - { - int graphicsindex = (indicestype == PHY_SHORT) ? ((unsigned short *)gfxbase)[j] : gfxbase[j]; - - btScalar* graphicsbase = (btScalar*)(vertexbase+graphicsindex*stride); - - triangle[j] = btVector3(graphicsbase[0]*meshScaling.getX(),graphicsbase[1]*meshScaling.getY(),graphicsbase[2]*meshScaling.getZ()); - } - meshInterface->unLockReadOnlyVertexBase(0); - return true; -} - -PHY_IPhysicsController* CcdPhysicsEnvironment::RayTest(PHY_IRayCastFilterCallback &filterCallback, float fromX,float fromY,float fromZ, float toX,float toY,float toZ) -{ - btVector3 rayFrom(fromX,fromY,fromZ); - btVector3 rayTo(toX,toY,toZ); - - btVector3 hitPointWorld,normalWorld; - - //Either Ray Cast with or without filtering - - //btCollisionWorld::ClosestRayResultCallback rayCallback(rayFrom,rayTo); - FilterClosestRayResultCallback rayCallback(filterCallback,rayFrom,rayTo); - - - PHY_RayCastResult result; - memset(&result, 0, sizeof(result)); - - // don't collision with sensor object - rayCallback.m_collisionFilterMask = CcdConstructionInfo::AllFilter ^ CcdConstructionInfo::SensorFilter; - // use faster (less accurate) ray callback, works better with 0 collision margins - rayCallback.m_flags |= btTriangleRaycastCallback::kF_UseSubSimplexConvexCastRaytest; - //, ,filterCallback.m_faceNormal); - - m_dynamicsWorld->rayTest(rayFrom,rayTo,rayCallback); - if (rayCallback.hasHit()) - { - CcdPhysicsController* controller = static_cast(rayCallback.m_collisionObject->getUserPointer()); - result.m_controller = controller; - result.m_hitPoint[0] = rayCallback.m_hitPointWorld.getX(); - result.m_hitPoint[1] = rayCallback.m_hitPointWorld.getY(); - result.m_hitPoint[2] = rayCallback.m_hitPointWorld.getZ(); - - if (rayCallback.m_hitTriangleShape != NULL) - { - // identify the mesh polygon - CcdShapeConstructionInfo* shapeInfo = controller->m_shapeInfo; - if (shapeInfo) - { - btCollisionShape* shape = controller->GetCollisionObject()->getCollisionShape(); - if (shape->isCompound()) - { - btCompoundShape* compoundShape = (btCompoundShape*)shape; - CcdShapeConstructionInfo* compoundShapeInfo = shapeInfo; - // need to search which sub-shape has been hit - for (int i=0; igetNumChildShapes(); i++) - { - shapeInfo = compoundShapeInfo->GetChildShape(i); - shape=compoundShape->getChildShape(i); - if (shape == rayCallback.m_hitTriangleShape) - break; - } - } - if (shape == rayCallback.m_hitTriangleShape && - rayCallback.m_hitTriangleIndex < shapeInfo->m_polygonIndexArray.size()) - { - // save original collision shape triangle for soft body - int hitTriangleIndex = rayCallback.m_hitTriangleIndex; - - result.m_meshObject = shapeInfo->GetMesh(); - if (shape->isSoftBody()) - { - // soft body using different face numbering because of randomization - // hopefully we have stored the original face number in m_tag - const btSoftBody* softBody = static_cast(rayCallback.m_collisionObject); - if (softBody->m_faces[hitTriangleIndex].m_tag != 0) - { - rayCallback.m_hitTriangleIndex = (int)((uintptr_t)(softBody->m_faces[hitTriangleIndex].m_tag)-1); - } - } - // retrieve the original mesh polygon (in case of quad->tri conversion) - result.m_polygon = shapeInfo->m_polygonIndexArray.at(rayCallback.m_hitTriangleIndex); - // hit triangle in world coordinate, for face normal and UV coordinate - btVector3 triangle[3]; - bool triangleOK = false; - if (filterCallback.m_faceUV && (3*rayCallback.m_hitTriangleIndex) < shapeInfo->m_triFaceUVcoArray.size()) - { - // interpolate the UV coordinate of the hit point - CcdShapeConstructionInfo::UVco* uvCo = &shapeInfo->m_triFaceUVcoArray[3*rayCallback.m_hitTriangleIndex]; - // 1. get the 3 coordinate of the triangle in world space - btVector3 v1, v2, v3; - if (shape->isSoftBody()) - { - // soft body give points directly in world coordinate - const btSoftBody* softBody = static_cast(rayCallback.m_collisionObject); - v1 = softBody->m_faces[hitTriangleIndex].m_n[0]->m_x; - v2 = softBody->m_faces[hitTriangleIndex].m_n[1]->m_x; - v3 = softBody->m_faces[hitTriangleIndex].m_n[2]->m_x; - } else - { - // for rigid body we must apply the world transform - triangleOK = GetHitTriangle(shape, shapeInfo, hitTriangleIndex, triangle); - if (!triangleOK) - // if we cannot get the triangle, no use to continue - goto SKIP_UV_NORMAL; - v1 = rayCallback.m_collisionObject->getWorldTransform()(triangle[0]); - v2 = rayCallback.m_collisionObject->getWorldTransform()(triangle[1]); - v3 = rayCallback.m_collisionObject->getWorldTransform()(triangle[2]); - } - // 2. compute barycentric coordinate of the hit point - btVector3 v = v2-v1; - btVector3 w = v3-v1; - btVector3 u = v.cross(w); - btScalar A = u.length(); - - v = v2-rayCallback.m_hitPointWorld; - w = v3-rayCallback.m_hitPointWorld; - u = v.cross(w); - btScalar A1 = u.length(); - - v = rayCallback.m_hitPointWorld-v1; - w = v3-v1; - u = v.cross(w); - btScalar A2 = u.length(); - - btVector3 baryCo; - baryCo.setX(A1/A); - baryCo.setY(A2/A); - baryCo.setZ(1.0f-baryCo.getX()-baryCo.getY()); - // 3. compute UV coordinate - result.m_hitUV[0] = baryCo.getX()*uvCo[0].uv[0] + baryCo.getY()*uvCo[1].uv[0] + baryCo.getZ()*uvCo[2].uv[0]; - result.m_hitUV[1] = baryCo.getX()*uvCo[0].uv[1] + baryCo.getY()*uvCo[1].uv[1] + baryCo.getZ()*uvCo[2].uv[1]; - result.m_hitUVOK = 1; - } - - // Bullet returns the normal from "outside". - // If the user requests the real normal, compute it now - if (filterCallback.m_faceNormal) - { - if (shape->isSoftBody()) - { - // we can get the real normal directly from the body - const btSoftBody* softBody = static_cast(rayCallback.m_collisionObject); - rayCallback.m_hitNormalWorld = softBody->m_faces[hitTriangleIndex].m_normal; - } else - { - if (!triangleOK) - triangleOK = GetHitTriangle(shape, shapeInfo, hitTriangleIndex, triangle); - if (triangleOK) - { - btVector3 triangleNormal; - triangleNormal = (triangle[1]-triangle[0]).cross(triangle[2]-triangle[0]); - rayCallback.m_hitNormalWorld = rayCallback.m_collisionObject->getWorldTransform().getBasis()*triangleNormal; - } - } - } - SKIP_UV_NORMAL: - ; - } - } - } - if (rayCallback.m_hitNormalWorld.length2() > (SIMD_EPSILON*SIMD_EPSILON)) - { - rayCallback.m_hitNormalWorld.normalize(); - } else - { - rayCallback.m_hitNormalWorld.setValue(1,0,0); - } - result.m_hitNormal[0] = rayCallback.m_hitNormalWorld.getX(); - result.m_hitNormal[1] = rayCallback.m_hitNormalWorld.getY(); - result.m_hitNormal[2] = rayCallback.m_hitNormalWorld.getZ(); - filterCallback.reportHit(&result); - } - - - return result.m_controller; -} - -// Handles occlusion culling. -// The implementation is based on the CDTestFramework -struct OcclusionBuffer -{ - struct WriteOCL - { - static inline bool Process(btScalar &q, btScalar v) - { - if (q < v) { - q = v; - } - return false; - } - static inline void Occlusion(bool &flag) - { - flag = true; - } - }; - - struct QueryOCL - { - static inline bool Process(btScalar &q, btScalar v) - { - return (q <= v); - } - static inline void Occlusion(bool &flag) - { - } - }; - - btScalar *m_buffer; - size_t m_bufferSize; - bool m_initialized; - bool m_occlusion; - int m_sizes[2]; - btScalar m_scales[2]; - btScalar m_offsets[2]; - btScalar m_wtc[16]; // world to clip transform - btScalar m_mtc[16]; // model to clip transform - // constructor: size=largest dimension of the buffer. - // Buffer size depends on aspect ratio - OcclusionBuffer() - { - m_initialized = false; - m_occlusion = false; - m_buffer = NULL; - m_bufferSize = 0; - } - // multiplication of column major matrices: m = m1 * m2 - template - void CMmat4mul(btScalar *m, const T1 *m1, const T2 *m2) - { - m[0] = btScalar(m1[0] * m2[0] + m1[4] * m2[1] + m1[8] * m2[2] + m1[12] * m2[3]); - m[1] = btScalar(m1[1] * m2[0] + m1[5] * m2[1] + m1[9] * m2[2] + m1[13] * m2[3]); - m[2] = btScalar(m1[2] * m2[0] + m1[6] * m2[1] + m1[10] * m2[2] + m1[14] * m2[3]); - m[3] = btScalar(m1[3] * m2[0] + m1[7] * m2[1] + m1[11] * m2[2] + m1[15] * m2[3]); - - m[4] = btScalar(m1[0] * m2[4] + m1[4] * m2[5] + m1[8] * m2[6] + m1[12] * m2[7]); - m[5] = btScalar(m1[1] * m2[4] + m1[5] * m2[5] + m1[9] * m2[6] + m1[13] * m2[7]); - m[6] = btScalar(m1[2] * m2[4] + m1[6] * m2[5] + m1[10] * m2[6] + m1[14] * m2[7]); - m[7] = btScalar(m1[3] * m2[4] + m1[7] * m2[5] + m1[11] * m2[6] + m1[15] * m2[7]); - - m[8] = btScalar(m1[0] * m2[8] + m1[4] * m2[9] + m1[8] * m2[10] + m1[12] * m2[11]); - m[9] = btScalar(m1[1] * m2[8] + m1[5] * m2[9] + m1[9] * m2[10] + m1[13] * m2[11]); - m[10] = btScalar(m1[2] * m2[8] + m1[6] * m2[9] + m1[10] * m2[10] + m1[14] * m2[11]); - m[11] = btScalar(m1[3] * m2[8] + m1[7] * m2[9] + m1[11] * m2[10] + m1[15] * m2[11]); - - m[12] = btScalar(m1[0] * m2[12] + m1[4] * m2[13] + m1[8] * m2[14] + m1[12] * m2[15]); - m[13] = btScalar(m1[1] * m2[12] + m1[5] * m2[13] + m1[9] * m2[14] + m1[13] * m2[15]); - m[14] = btScalar(m1[2] * m2[12] + m1[6] * m2[13] + m1[10] * m2[14] + m1[14] * m2[15]); - m[15] = btScalar(m1[3] * m2[12] + m1[7] * m2[13] + m1[11] * m2[14] + m1[15] * m2[15]); - } - - void setup(int size, const int *view, float modelview[16], float projection[16]) - { - m_initialized = false; - m_occlusion = false; - // compute the size of the buffer - int maxsize = (view[2] > view[3]) ? view[2] : view[3]; - assert(maxsize > 0); - double ratio = 1.0 / (2 * maxsize); - // ensure even number - m_sizes[0] = 2 * ((int)(size * view[2] * ratio + 0.5)); - m_sizes[1] = 2 * ((int)(size * view[3] * ratio + 0.5)); - m_scales[0] = btScalar(m_sizes[0] / 2); - m_scales[1] = btScalar(m_sizes[1] / 2); - m_offsets[0] = m_scales[0] + 0.5f; - m_offsets[1] = m_scales[1] + 0.5f; - // prepare matrix - // at this time of the rendering, the modelview matrix is the - // world to camera transformation and the projection matrix is - // camera to clip transformation. combine both so that - CMmat4mul(m_wtc, projection, modelview); - } - - void initialize() - { - size_t newsize = (m_sizes[0] * m_sizes[1]) * sizeof(btScalar); - if (m_buffer) { - // see if we can reuse - if (newsize > m_bufferSize) { - free(m_buffer); - m_buffer = NULL; - m_bufferSize = 0; - } - } - if (!m_buffer) { - m_buffer = (btScalar *)calloc(1, newsize); - m_bufferSize = newsize; - } - else { - // buffer exists already, just clears it - memset(m_buffer, 0, newsize); - } - // memory allocate must succeed - assert(m_buffer != NULL); - m_initialized = true; - m_occlusion = false; - } - - void SetModelMatrix(float *fl) - { - CMmat4mul(m_mtc,m_wtc,fl); - if (!m_initialized) { - initialize(); - } - } - - // transform a segment in world coordinate to clip coordinate - void transformW(const btVector3 &x, btVector4 &t) - { - t[0] = x[0] * m_wtc[0] + x[1] * m_wtc[4] + x[2] * m_wtc[8] + m_wtc[12]; - t[1] = x[0] * m_wtc[1] + x[1] * m_wtc[5] + x[2] * m_wtc[9] + m_wtc[13]; - t[2] = x[0] * m_wtc[2] + x[1] * m_wtc[6] + x[2] * m_wtc[10] + m_wtc[14]; - t[3] = x[0] * m_wtc[3] + x[1] * m_wtc[7] + x[2] * m_wtc[11] + m_wtc[15]; - } - - void transformM(const float *x, btVector4 &t) - { - t[0] = x[0] * m_mtc[0] + x[1] * m_mtc[4] + x[2] * m_mtc[8] + m_mtc[12]; - t[1] = x[0] * m_mtc[1] + x[1] * m_mtc[5] + x[2] * m_mtc[9] + m_mtc[13]; - t[2] = x[0] * m_mtc[2] + x[1] * m_mtc[6] + x[2] * m_mtc[10] + m_mtc[14]; - t[3] = x[0] * m_mtc[3] + x[1] * m_mtc[7] + x[2] * m_mtc[11] + m_mtc[15]; - } - // convert polygon to device coordinates - static bool project(btVector4 *p, int n) - { - for (int i = 0; i < n; ++i) { - p[i][2] = 1 / p[i][3]; - p[i][0] *= p[i][2]; - p[i][1] *= p[i][2]; - } - return true; - } - // pi: closed polygon in clip coordinate, NP = number of segments - // po: same polygon with clipped segments removed - template - static int clip(const btVector4 *pi, btVector4 *po) - { - btScalar s[2 * NP]; - btVector4 pn[2 * NP]; - int i, j, m, n, ni; - // deal with near clipping - for (i = 0, m = 0; i < NP; ++i) { - s[i] = pi[i][2] + pi[i][3]; - if (s[i] < 0) { - m += 1 << i; - } - } - if (m == ((1 << NP) - 1)) { - return 0; - } - if (m != 0) { - for (i = NP - 1, j = 0, n = 0; j < NP; i = j++) { - const btVector4 &a = pi[i]; - const btVector4 &b = pi[j]; - const btScalar t = s[i] / (a[3] + a[2] - b[3] - b[2]); - if ((t > 0) && (t < 1)) { - pn[n][0] = a[0] + (b[0] - a[0]) * t; - pn[n][1] = a[1] + (b[1] - a[1]) * t; - pn[n][2] = a[2] + (b[2] - a[2]) * t; - pn[n][3] = a[3] + (b[3] - a[3]) * t; - ++n; - } - if (s[j] > 0) { - pn[n++] = b; - } - } - // ready to test far clipping, start from the modified polygon - pi = pn; - ni = n; - } - else { - // no clipping on the near plane, keep same vector - ni = NP; - } - // now deal with far clipping - for (i = 0, m = 0; i < ni; ++i) { - s[i] = pi[i][2] - pi[i][3]; - if (s[i] > 0) { - m += 1 << i; - } - } - if (m == ((1 << ni) - 1)) { - return 0; - } - if (m != 0) { - for (i = ni - 1, j = 0, n = 0;j < ni; i = j++) { - const btVector4 &a = pi[i]; - const btVector4 &b = pi[j]; - const btScalar t = s[i] / (a[2] - a[3] - b[2] + b[3]); - if ((t > 0) && (t < 1)) { - po[n][0] = a[0] + (b[0] - a[0]) * t; - po[n][1] = a[1] + (b[1] - a[1]) * t; - po[n][2] = a[2] + (b[2] - a[2]) * t; - po[n][3] = a[3] + (b[3] - a[3]) * t; - ++n; - } - if (s[j] < 0) { - po[n++] = b; - } - } - return n; - } - for (int i = 0; i < ni; ++i) { - po[i] = pi[i]; - } - return ni; - } - // write or check a triangle to buffer. a,b,c in device coordinates (-1,+1) - template - inline bool draw(const btVector4 &a, - const btVector4 &b, - const btVector4 &c, - const float face, - const btScalar minarea) - { - const btScalar a2 = btCross(b - a, c - a)[2]; - if ((face * a2) < 0.0f || btFabs(a2) < minarea) { - return false; - } - // further down we are normally going to write to the Zbuffer, mark it so - POLICY::Occlusion(m_occlusion); - - int x[3], y[3], ib = 1, ic = 2; - btScalar z[3]; - x[0] = (int)(a.x() * m_scales[0] + m_offsets[0]); - y[0] = (int)(a.y() * m_scales[1] + m_offsets[1]); - z[0] = a.z(); - if (a2 < 0.f) { - // negative aire is possible with double face => must - // change the order of b and c otherwise the algorithm doesn't work - ib = 2; - ic = 1; - } - x[ib] = (int)(b.x() * m_scales[0] + m_offsets[0]); - x[ic] = (int)(c.x() * m_scales[0] + m_offsets[0]); - y[ib] = (int)(b.y() * m_scales[1] + m_offsets[1]); - y[ic] = (int)(c.y() * m_scales[1] + m_offsets[1]); - z[ib] = b.z(); - z[ic] = c.z(); - const int mix = btMax(0, btMin(x[0], btMin(x[1], x[2]))); - const int mxx = btMin(m_sizes[0], 1 + btMax(x[0], btMax(x[1], x[2]))); - const int miy = btMax(0, btMin(y[0], btMin(y[1], y[2]))); - const int mxy = btMin(m_sizes[1], 1 + btMax(y[0], btMax(y[1], y[2]))); - const int width = mxx - mix; - const int height = mxy - miy; - if ((width * height) <= 1) { - // degenerated in at most one single pixel - btScalar *scan = &m_buffer[miy * m_sizes[0] + mix]; - // use for loop to detect the case where width or height == 0 - for (int iy = miy; iy < mxy; ++iy) { - for (int ix = mix; ix < mxx; ++ix) { - if (POLICY::Process(*scan, z[0])) { - return true; - } - if (POLICY::Process(*scan, z[1])) { - return true; - } - if (POLICY::Process(*scan, z[2])) { - return true; - } - } - } - } - else if (width == 1) { - // Degenerated in at least 2 vertical lines - // The algorithm below doesn't work when face has a single pixel width - // We cannot use general formulas because the plane is degenerated. - // We have to interpolate along the 3 edges that overlaps and process each pixel. - // sort the y coord to make formula simpler - int ytmp; - btScalar ztmp; - if (y[0] > y[1]) { - ytmp = y[1]; - y[1] = y[0]; - y[0] = ytmp; - ztmp = z[1]; - z[1] = z[0]; - z[0] = ztmp; - } - if (y[0] > y[2]) { - ytmp = y[2]; - y[2] = y[0]; - y[0] = ytmp; - ztmp = z[2]; - z[2] = z[0]; - z[0] = ztmp; - } - if (y[1] > y[2]) { - ytmp = y[2]; - y[2] = y[1]; - y[1] = ytmp; - ztmp = z[2]; - z[2] = z[1]; - z[1] = ztmp; - } - int dy[] = {y[0] - y[1], - y[1] - y[2], - y[2] - y[0]}; - btScalar dzy[3]; - dzy[0] = (dy[0]) ? (z[0] - z[1]) / dy[0] : btScalar(0.0f); - dzy[1] = (dy[1]) ? (z[1] - z[2]) / dy[1] : btScalar(0.0f); - dzy[2] = (dy[2]) ? (z[2] - z[0]) / dy[2] : btScalar(0.0f); - btScalar v[3] = {dzy[0] * (miy - y[0]) + z[0], - dzy[1] * (miy - y[1]) + z[1], - dzy[2] * (miy - y[2]) + z[2]}; - dy[0] = y[1] - y[0]; - dy[1] = y[0] - y[1]; - dy[2] = y[2] - y[0]; - btScalar *scan = &m_buffer[miy * m_sizes[0] + mix]; - for (int iy = miy; iy < mxy; ++iy) { - if (dy[0] >= 0 && POLICY::Process(*scan, v[0])) { - return true; - } - if (dy[1] >= 0 && POLICY::Process(*scan, v[1])) { - return true; - } - if (dy[2] >= 0 && POLICY::Process(*scan, v[2])) { - return true; - } - scan += m_sizes[0]; - v[0] += dzy[0]; - v[1] += dzy[1]; - v[2] += dzy[2]; - dy[0]--; - dy[1]++; - dy[2]--; - } - } - else if (height == 1) { - // Degenerated in at least 2 horizontal lines - // The algorithm below doesn't work when face has a single pixel width - // We cannot use general formulas because the plane is degenerated. - // We have to interpolate along the 3 edges that overlaps and process each pixel. - int xtmp; - btScalar ztmp; - if (x[0] > x[1]) { - xtmp = x[1]; - x[1] = x[0]; - x[0] = xtmp; - ztmp = z[1]; - z[1] = z[0]; - z[0] = ztmp; - } - if (x[0] > x[2]) { - xtmp = x[2]; - x[2] = x[0]; - x[0] = xtmp; - ztmp = z[2]; - z[2] = z[0]; - z[0] = ztmp; - } - if (x[1] > x[2]) { - xtmp = x[2]; - x[2] = x[1]; - x[1] = xtmp; - ztmp = z[2]; - z[2] = z[1]; - z[1] = ztmp; - } - int dx[] = {x[0] - x[1], - x[1] - x[2], - x[2] - x[0]}; - btScalar dzx[3]; - dzx[0] = (dx[0]) ? (z[0]-z[1]) / dx[0] : btScalar(0.0f); - dzx[1] = (dx[1]) ? (z[1]-z[2]) / dx[1] : btScalar(0.0f); - dzx[2] = (dx[2]) ? (z[2]-z[0]) / dx[2] : btScalar(0.0f); - btScalar v[3] = {dzx[0] * (mix - x[0]) + z[0], - dzx[1] * (mix - x[1]) + z[1], - dzx[2] * (mix - x[2]) + z[2]}; - dx[0] = x[1] - x[0]; - dx[1] = x[0] - x[1]; - dx[2] = x[2] - x[0]; - btScalar *scan = &m_buffer[miy * m_sizes[0] + mix]; - for (int ix = mix; ix < mxx; ++ix) { - if (dx[0] >= 0 && POLICY::Process(*scan, v[0])) { - return true; - } - if (dx[1] >= 0 && POLICY::Process(*scan, v[1])) { - return true; - } - if (dx[2] >= 0 && POLICY::Process(*scan, v[2])) { - return true; - } - scan++; - v[0] += dzx[0]; - v[1] += dzx[1]; - v[2] += dzx[2]; - dx[0]--; - dx[1]++; - dx[2]--; - } - } - else { - // general case - const int dx[] = {y[0] - y[1], - y[1] - y[2], - y[2] - y[0]}; - const int dy[] = {x[1] - x[0] - dx[0] * width, - x[2] - x[1] - dx[1] * width, - x[0] - x[2] - dx[2] * width}; - const int a = x[2] * y[0] + x[0] * y[1] - x[2] * y[1] - x[0] * y[2] + x[1] * y[2] - x[1] * y[0]; - const btScalar ia = 1 / (btScalar)a; - const btScalar dzx = ia * (y[2] * (z[1] - z[0]) + y[1] * (z[0] - z[2]) + y[0] * (z[2] - z[1])); - const btScalar dzy = ia * (x[2] * (z[0] - z[1]) + x[0] * (z[1] - z[2]) + x[1] * (z[2] - z[0])) - (dzx * width); - int c[] = {miy * x[1] + mix * y[0] - x[1] * y[0] - mix * y[1] + x[0] * y[1] - miy * x[0], - miy * x[2] + mix * y[1] - x[2] * y[1] - mix * y[2] + x[1] * y[2] - miy * x[1], - miy * x[0] + mix * y[2] - x[0] * y[2] - mix * y[0] + x[2] * y[0] - miy * x[2]}; - btScalar v = ia * ((z[2] * c[0]) + (z[0] * c[1]) + (z[1] * c[2])); - btScalar *scan = &m_buffer[miy * m_sizes[0]]; - - for (int iy = miy; iy < mxy; ++iy) { - for (int ix = mix; ix < mxx; ++ix) { - if ((c[0] >= 0) && (c[1] >= 0) && (c[2] >= 0)) { - if (POLICY::Process(scan[ix], v)) { - return true; - } - } - c[0] += dx[0]; c[1] += dx[1]; c[2] += dx[2]; v += dzx; - } - c[0] += dy[0]; c[1] += dy[1]; c[2] += dy[2]; v += dzy; - scan += m_sizes[0]; - } - } - return false; - } - // clip than write or check a polygon - template - inline bool clipDraw(const btVector4 *p, - const float face, - btScalar minarea) - { - btVector4 o[NP * 2]; - int n = clip(p, o); - bool earlyexit = false; - if (n) { - project(o, n); - for (int i = 2; i < n && !earlyexit; ++i) { - earlyexit |= draw(o[0], o[i - 1], o[i], face, minarea); - } - } - return earlyexit; - } - // add a triangle (in model coordinate) - // face = 0.f if face is double side, - // = 1.f if face is single sided and scale is positive - // = -1.f if face is single sided and scale is negative - void appendOccluderM(const float *a, - const float *b, - const float *c, - const float face) - { - btVector4 p[3]; - transformM(a, p[0]); - transformM(b, p[1]); - transformM(c, p[2]); - clipDraw<3, WriteOCL>(p, face, btScalar(0.0f)); - } - // add a quad (in model coordinate) - void appendOccluderM(const float *a, - const float *b, - const float *c, - const float *d, - const float face) - { - btVector4 p[4]; - transformM(a, p[0]); - transformM(b, p[1]); - transformM(c, p[2]); - transformM(d, p[3]); - clipDraw<4, WriteOCL>(p, face, btScalar(0.0f)); - } - // query occluder for a box (c=center, e=extend) in world coordinate - inline bool queryOccluderW(const btVector3 &c, - const btVector3 &e) - { - if (!m_occlusion) { - // no occlusion yet, no need to check - return true; - } - btVector4 x[8]; - transformW(btVector3(c[0] - e[0], c[1] - e[1], c[2] - e[2]), x[0]); - transformW(btVector3(c[0] + e[0], c[1] - e[1], c[2] - e[2]), x[1]); - transformW(btVector3(c[0] + e[0], c[1] + e[1], c[2] - e[2]), x[2]); - transformW(btVector3(c[0] - e[0], c[1] + e[1], c[2] - e[2]), x[3]); - transformW(btVector3(c[0] - e[0], c[1] - e[1], c[2] + e[2]), x[4]); - transformW(btVector3(c[0] + e[0], c[1] - e[1], c[2] + e[2]), x[5]); - transformW(btVector3(c[0] + e[0], c[1] + e[1], c[2] + e[2]), x[6]); - transformW(btVector3(c[0] - e[0], c[1] + e[1], c[2] + e[2]), x[7]); - - for (int i = 0; i < 8; ++i) { - // the box is clipped, it's probably a large box, don't waste our time to check - if ((x[i][2] + x[i][3]) <= 0) { - return true; - } - } - static const int d[] = {1, 0, 3, 2, - 4, 5, 6, 7, - 4, 7, 3, 0, - 6, 5, 1, 2, - 7, 6, 2, 3, - 5, 4, 0, 1}; - for (unsigned int i = 0; i < (sizeof(d) / sizeof(d[0]));) { - const btVector4 p[] = {x[d[i + 0]], - x[d[i + 1]], - x[d[i + 2]], - x[d[i + 3]]}; - i += 4; - if (clipDraw<4, QueryOCL>(p, 1.0f, 0.0f)) { - return true; - } - } - return false; - } -}; - - -struct DbvtCullingCallback : btDbvt::ICollide -{ - PHY_CullingCallback m_clientCallback; - void* m_userData; - OcclusionBuffer *m_ocb; - - DbvtCullingCallback(PHY_CullingCallback clientCallback, void* userData) - { - m_clientCallback = clientCallback; - m_userData = userData; - m_ocb = NULL; - } - bool Descent(const btDbvtNode* node) - { - return(m_ocb->queryOccluderW(node->volume.Center(),node->volume.Extents())); - } - void Process(const btDbvtNode* node,btScalar depth) - { - Process(node); - } - void Process(const btDbvtNode* leaf) - { - btBroadphaseProxy* proxy=(btBroadphaseProxy*)leaf->data; - // the client object is a graphic controller - CcdGraphicController* ctrl = static_cast(proxy->m_clientObject); - KX_ClientObjectInfo *info = (KX_ClientObjectInfo*)ctrl->GetNewClientInfo(); - if (m_ocb) - { - // means we are doing occlusion culling. Check if this object is an occluders - KX_GameObject* gameobj = KX_GameObject::GetClientObject(info); - if (gameobj && gameobj->GetOccluder()) - { - float *fl = gameobj->GetOpenGLMatrixPtr()->getPointer(); - // this will create the occlusion buffer if not already done - // and compute the transformation from model local space to clip space - m_ocb->SetModelMatrix(fl); - float face = (gameobj->IsNegativeScaling()) ? -1.0f : 1.0f; - // walk through the meshes and for each add to buffer - for (int i=0; iGetMeshCount(); i++) - { - RAS_MeshObject* meshobj = gameobj->GetMesh(i); - const float *v1, *v2, *v3, *v4; - - int polycount = meshobj->NumPolygons(); - for (int j=0; jGetPolygon(j); - switch (poly->VertexCount()) - { - case 3: - v1 = poly->GetVertex(0)->getXYZ(); - v2 = poly->GetVertex(1)->getXYZ(); - v3 = poly->GetVertex(2)->getXYZ(); - m_ocb->appendOccluderM(v1,v2,v3,((poly->IsTwoside())?0.f:face)); - break; - case 4: - v1 = poly->GetVertex(0)->getXYZ(); - v2 = poly->GetVertex(1)->getXYZ(); - v3 = poly->GetVertex(2)->getXYZ(); - v4 = poly->GetVertex(3)->getXYZ(); - m_ocb->appendOccluderM(v1,v2,v3,v4,((poly->IsTwoside())?0.f:face)); - break; - } - } - } - } - } - if (info) - (*m_clientCallback)(info, m_userData); - } -}; - -static OcclusionBuffer gOcb; -bool CcdPhysicsEnvironment::CullingTest(PHY_CullingCallback callback, void* userData, MT_Vector4 *planes, int nplanes, int occlusionRes, const int *viewport, float modelview[16], float projection[16]) -{ - if (!m_cullingTree) - return false; - DbvtCullingCallback dispatcher(callback, userData); - btVector3 planes_n[6]; - btScalar planes_o[6]; - if (nplanes > 6) - nplanes = 6; - for (int i=0; i occlusion culling - if (occlusionRes) - { - gOcb.setup(occlusionRes, viewport, modelview, projection); - dispatcher.m_ocb = &gOcb; - // occlusion culling, the direction of the view is taken from the first plan which MUST be the near plane - btDbvt::collideOCL(m_cullingTree->m_sets[1].m_root,planes_n,planes_o,planes_n[0],nplanes,dispatcher); - btDbvt::collideOCL(m_cullingTree->m_sets[0].m_root,planes_n,planes_o,planes_n[0],nplanes,dispatcher); - } - else { - btDbvt::collideKDOP(m_cullingTree->m_sets[1].m_root,planes_n,planes_o,nplanes,dispatcher); - btDbvt::collideKDOP(m_cullingTree->m_sets[0].m_root,planes_n,planes_o,nplanes,dispatcher); - } - return true; -} - -int CcdPhysicsEnvironment::GetNumContactPoints() -{ - return 0; -} - -void CcdPhysicsEnvironment::GetContactPoint(int i,float& hitX,float& hitY,float& hitZ,float& normalX,float& normalY,float& normalZ) -{ - -} - - - - -btBroadphaseInterface* CcdPhysicsEnvironment::GetBroadphase() -{ - return m_dynamicsWorld->getBroadphase(); -} - -btDispatcher* CcdPhysicsEnvironment::GetDispatcher() -{ - return m_dynamicsWorld->getDispatcher(); -} - -void CcdPhysicsEnvironment::MergeEnvironment(PHY_IPhysicsEnvironment *other_env) -{ - CcdPhysicsEnvironment *other = dynamic_cast(other_env); - if (other == NULL) { - printf("KX_Scene::MergeScene: Other scene is not using Bullet physics, not merging physics.\n"); - return; - } - - std::set::iterator it; - - while (other->m_controllers.begin() != other->m_controllers.end()) - { - it= other->m_controllers.begin(); - CcdPhysicsController* ctrl= (*it); - - other->RemoveCcdPhysicsController(ctrl); - this->AddCcdPhysicsController(ctrl); - } -} - -CcdPhysicsEnvironment::~CcdPhysicsEnvironment() -{ - -#ifdef NEW_BULLET_VEHICLE_SUPPORT - m_wrapperVehicles.clear(); -#endif //NEW_BULLET_VEHICLE_SUPPORT - - //m_broadphase->DestroyScene(); - //delete broadphase ? release reference on broadphase ? - - //first delete scene, then dispatcher, because pairs have to release manifolds on the dispatcher - //delete m_dispatcher; - delete m_dynamicsWorld; - - - if (NULL != m_ownPairCache) - delete m_ownPairCache; - - if (NULL != m_ownDispatcher) - delete m_ownDispatcher; - - if (NULL != m_solver) - delete m_solver; - - if (NULL != m_debugDrawer) - delete m_debugDrawer; - - if (NULL != m_filterCallback) - delete m_filterCallback; - - if (NULL != m_ghostPairCallback) - delete m_ghostPairCallback; - - if (NULL != m_collisionConfiguration) - delete m_collisionConfiguration; - - if (NULL != m_broadphase) - delete m_broadphase; - - if (NULL != m_cullingTree) - delete m_cullingTree; - - if (NULL != m_cullingCache) - delete m_cullingCache; - -} - - -float CcdPhysicsEnvironment::GetConstraintParam(int constraintId,int param) -{ - btTypedConstraint* typedConstraint = GetConstraintById(constraintId); - if (!typedConstraint) - return 0.0f; - - switch (typedConstraint->getUserConstraintType()) - { - case PHY_GENERIC_6DOF_CONSTRAINT: - { - - switch (param) - { - case 0: case 1: case 2: - { - //param = 0..2 are linear constraint values - btGeneric6DofConstraint* genCons = (btGeneric6DofConstraint*)typedConstraint; - genCons->calculateTransforms(); - return genCons->getRelativePivotPosition(param); - break; - } - case 3: case 4: case 5: - { - //param = 3..5 are relative constraint (Euler) angles - btGeneric6DofConstraint* genCons = (btGeneric6DofConstraint*)typedConstraint; - genCons->calculateTransforms(); - return genCons->getAngle(param-3); - break; - } - default: - { - } - } - break; - }; - default: - { - }; - }; - return 0.f; -} - -void CcdPhysicsEnvironment::SetConstraintParam(int constraintId,int param,float value0,float value1) -{ - btTypedConstraint* typedConstraint = GetConstraintById(constraintId); - if (!typedConstraint) - return; - - switch (typedConstraint->getUserConstraintType()) - { - case PHY_GENERIC_6DOF_CONSTRAINT: - { - - switch (param) - { - case 0: case 1: case 2: case 3: case 4: case 5: - { - //param = 0..5 are constraint limits, with low/high limit value - btGeneric6DofConstraint* genCons = (btGeneric6DofConstraint*)typedConstraint; - genCons->setLimit(param,value0,value1); - break; - } - case 6: case 7: case 8: - { - //param = 6,7,8 are translational motors, with value0=target velocity, value1 = max motor force - btGeneric6DofConstraint* genCons = (btGeneric6DofConstraint*)typedConstraint; - int transMotorIndex = param-6; - btTranslationalLimitMotor* transMotor = genCons->getTranslationalLimitMotor(); - transMotor->m_targetVelocity[transMotorIndex] = value0; - transMotor->m_maxMotorForce[transMotorIndex] = value1; - transMotor->m_enableMotor[transMotorIndex] = (value1>0.f); - break; - } - case 9: case 10: case 11: - { - //param = 9,10,11 are rotational motors, with value0=target velocity, value1 = max motor force - btGeneric6DofConstraint* genCons = (btGeneric6DofConstraint*)typedConstraint; - int angMotorIndex = param-9; - btRotationalLimitMotor* rotMotor = genCons->getRotationalLimitMotor(angMotorIndex); - rotMotor->m_enableMotor = (value1 > 0.f); - rotMotor->m_targetVelocity = value0; - rotMotor->m_maxMotorForce = value1; - break; - } - - case 12: case 13: case 14: case 15: case 16: case 17: - { - //param 12-17 are for motorized springs on each of the degrees of freedom - btGeneric6DofSpringConstraint* genCons = (btGeneric6DofSpringConstraint*)typedConstraint; - int springIndex = param-12; - if (value0!=0.f) - { - bool springEnabled = true; - genCons->setStiffness(springIndex,value0); - genCons->setDamping(springIndex,value1); - genCons->enableSpring(springIndex,springEnabled); - genCons->setEquilibriumPoint(springIndex); - } else - { - bool springEnabled = false; - genCons->enableSpring(springIndex,springEnabled); - } - break; - } - - default: - { - } - }; - break; - }; - case PHY_CONE_TWIST_CONSTRAINT: - { - switch (param) - { - case 3: case 4: case 5: - { - //param = 3,4,5 are constraint limits, high limit values - btConeTwistConstraint* coneTwist = (btConeTwistConstraint*)typedConstraint; - if (value1<0.0f) - coneTwist->setLimit(param,btScalar(BT_LARGE_FLOAT)); - else - coneTwist->setLimit(param,value1); - break; - } - default: - { - } - }; - break; - }; - case PHY_ANGULAR_CONSTRAINT: - case PHY_LINEHINGE_CONSTRAINT: - { - switch (param) - { - case 3: - { - //param = 3 is a constraint limit, with low/high limit value - btHingeConstraint* hingeCons = (btHingeConstraint*)typedConstraint; - hingeCons->setLimit(value0,value1); - break; - } - default: - { - } - } - break; - }; - default: - { - }; - }; -} - -btTypedConstraint* CcdPhysicsEnvironment::GetConstraintById(int constraintId) -{ - // For soft body constraints - if (constraintId == 0) - return NULL; - - int numConstraints = m_dynamicsWorld->getNumConstraints(); - int i; - for (i=0;igetConstraint(i); - if (constraint->getUserConstraintId()==constraintId) - { - return constraint; - } - } - return 0; -} - - -void CcdPhysicsEnvironment::AddSensor(PHY_IPhysicsController* ctrl) -{ - CcdPhysicsController* ctrl1 = (CcdPhysicsController* )ctrl; - AddCcdPhysicsController(ctrl1); -} - -bool CcdPhysicsEnvironment::RemoveCollisionCallback(PHY_IPhysicsController* ctrl) -{ - CcdPhysicsController* ccdCtrl = (CcdPhysicsController*)ctrl; - return ccdCtrl->Unregister(); -} - - -void CcdPhysicsEnvironment::RemoveSensor(PHY_IPhysicsController* ctrl) -{ - RemoveCcdPhysicsController((CcdPhysicsController*)ctrl); -} - -void CcdPhysicsEnvironment::AddTouchCallback(int response_class, PHY_ResponseCallback callback, void *user) -{ - /* printf("addTouchCallback\n(response class = %i)\n",response_class); - - //map PHY_ convention into SM_ convention - switch (response_class) - { - case PHY_FH_RESPONSE: - printf("PHY_FH_RESPONSE\n"); - break; - case PHY_SENSOR_RESPONSE: - printf("PHY_SENSOR_RESPONSE\n"); - break; - case PHY_CAMERA_RESPONSE: - printf("PHY_CAMERA_RESPONSE\n"); - break; - case PHY_OBJECT_RESPONSE: - printf("PHY_OBJECT_RESPONSE\n"); - break; - case PHY_STATIC_RESPONSE: - printf("PHY_STATIC_RESPONSE\n"); - break; - default: - assert(0); - return; - } - */ - - m_triggerCallbacks[response_class] = callback; - m_triggerCallbacksUserPtrs[response_class] = user; - -} -bool CcdPhysicsEnvironment::RequestCollisionCallback(PHY_IPhysicsController* ctrl) -{ - CcdPhysicsController* ccdCtrl = static_cast(ctrl); - return ccdCtrl->Register(); -} - -void CcdPhysicsEnvironment::CallbackTriggers() -{ - bool draw_contact_points = m_debugDrawer && (m_debugDrawer->getDebugMode() & btIDebugDraw::DBG_DrawContactPoints); - - if (!m_triggerCallbacks[PHY_OBJECT_RESPONSE] && !draw_contact_points) - return; - - //walk over all overlapping pairs, and if one of the involved bodies is registered for trigger callback, perform callback - btDispatcher* dispatcher = m_dynamicsWorld->getDispatcher(); - int numManifolds = dispatcher->getNumManifolds(); - for (int i=0;igetManifoldByIndexInternal(i); - int numContacts = manifold->getNumContacts(); - if (!numContacts) continue; - - const btRigidBody* rb0 = static_cast(manifold->getBody0()); - const btRigidBody* rb1 = static_cast(manifold->getBody1()); - if (draw_contact_points) - { - for (int j=0;jgetContactPoint(j); - m_debugDrawer->drawContactPoint(cp.m_positionWorldOnB, - cp.m_normalWorldOnB, - cp.getDistance(), - cp.getLifeTime(), - color); - } - } - - //m_internalOwner is set in 'addPhysicsController' - CcdPhysicsController* ctrl0 = static_cast(rb0->getUserPointer()); - CcdPhysicsController* ctrl1 = static_cast(rb1->getUserPointer()); - bool usecallback = false; - - // Test if one of the controller is registered and use collision callback. - if (ctrl0->Registered()) - usecallback = true; - else if (ctrl1->Registered()) { - colliding_ctrl0 = false; - usecallback = true; - } - - if (usecallback) { - static PHY_CollData coll_data; - const btManifoldPoint &cp = manifold->getContactPoint(0); - - /* Make sure that "point1" is always on the object we report on, and - * "point2" on the other object. Also ensure the normal is oriented - * correctly. */ - btVector3 point1 = colliding_ctrl0 ? cp.m_positionWorldOnA : cp.m_positionWorldOnB; - btVector3 point2 = colliding_ctrl0 ? cp.m_positionWorldOnB : cp.m_positionWorldOnA; - btVector3 normal = colliding_ctrl0 ? -cp.m_normalWorldOnB : cp.m_normalWorldOnB; - - coll_data.m_point1 = MT_Vector3(point1.m_floats); - coll_data.m_point2 = MT_Vector3(point2.m_floats); - coll_data.m_normal = MT_Vector3(normal.m_floats); - - m_triggerCallbacks[PHY_OBJECT_RESPONSE](m_triggerCallbacksUserPtrs[PHY_OBJECT_RESPONSE], - ctrl0, ctrl1, &coll_data); - } - // Bullet does not refresh the manifold contact point for object without contact response - // may need to remove this when a newer Bullet version is integrated - if (!dispatcher->needsResponse(rb0, rb1)) - { - // Refresh algorithm fails sometimes when there is penetration - // (usuall the case with ghost and sensor objects) - // Let's just clear the manifold, in any case, it is recomputed on each frame. - manifold->clearManifold(); //refreshContactPoints(rb0->getCenterOfMassTransform(),rb1->getCenterOfMassTransform()); - } - } -} - -// This call back is called before a pair is added in the cache -// Handy to remove objects that must be ignored by sensors -bool CcdOverlapFilterCallBack::needBroadphaseCollision(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) const -{ - btCollisionObject *colObj0, *colObj1; - CcdPhysicsController *sensorCtrl, *objCtrl; - - KX_GameObject *kxObj0 = KX_GameObject::GetClientObject( - (KX_ClientObjectInfo*) - ((CcdPhysicsController*) - (((btCollisionObject*)proxy0->m_clientObject)->getUserPointer())) - ->GetNewClientInfo()); - KX_GameObject *kxObj1 = KX_GameObject::GetClientObject( - (KX_ClientObjectInfo*) - ((CcdPhysicsController*) - (((btCollisionObject*)proxy1->m_clientObject)->getUserPointer())) - ->GetNewClientInfo()); - - // First check the filters. Note that this is called during scene - // conversion, so we can't assume the KX_GameObject instances exist. This - // may make some objects erroneously collide on the first frame, but the - // alternative is to have them erroneously miss. - bool collides; - collides = (proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) != 0; - collides = collides && (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask); - if (kxObj0 && kxObj1) { - collides = collides && kxObj0->CheckCollision(kxObj1); - collides = collides && kxObj1->CheckCollision(kxObj0); - } - if (!collides) - return false; - - // additional check for sensor object - if (proxy0->m_collisionFilterGroup & btBroadphaseProxy::SensorTrigger) - { - // this is a sensor object, the other one can't be a sensor object because - // they exclude each other in the above test - assert(!(proxy1->m_collisionFilterGroup & btBroadphaseProxy::SensorTrigger)); - colObj0 = (btCollisionObject*)proxy0->m_clientObject; - colObj1 = (btCollisionObject*)proxy1->m_clientObject; - } - else if (proxy1->m_collisionFilterGroup & btBroadphaseProxy::SensorTrigger) - { - colObj0 = (btCollisionObject*)proxy1->m_clientObject; - colObj1 = (btCollisionObject*)proxy0->m_clientObject; - } - else - { - return true; - } - if (!colObj0 || !colObj1) - return false; - sensorCtrl = static_cast(colObj0->getUserPointer()); - objCtrl = static_cast(colObj1->getUserPointer()); - if (m_physEnv->m_triggerCallbacks[PHY_BROADPH_RESPONSE]) - { - return m_physEnv->m_triggerCallbacks[PHY_BROADPH_RESPONSE](m_physEnv->m_triggerCallbacksUserPtrs[PHY_BROADPH_RESPONSE], sensorCtrl, objCtrl, 0); - } - return true; -} - - -#ifdef NEW_BULLET_VEHICLE_SUPPORT - -//complex constraint for vehicles -PHY_IVehicle* CcdPhysicsEnvironment::GetVehicleConstraint(int constraintId) -{ - int i; - - int numVehicles = m_wrapperVehicles.size(); - for (i=0;iGetVehicle()->getUserConstraintId() == constraintId) - return wrapperVehicle; - } - - return 0; -} - -#endif //NEW_BULLET_VEHICLE_SUPPORT - - -PHY_ICharacter* CcdPhysicsEnvironment::GetCharacterController(KX_GameObject *ob) -{ - CcdPhysicsController* controller = (CcdPhysicsController*)ob->GetPhysicsController(); - return (controller) ? dynamic_cast(controller->GetCharacterController()) : NULL; -} - - -PHY_IPhysicsController* CcdPhysicsEnvironment::CreateSphereController(float radius,const MT_Vector3& position) -{ - - CcdConstructionInfo cinfo; - memset(&cinfo, 0, sizeof(cinfo)); /* avoid uninitialized values */ - cinfo.m_collisionShape = new btSphereShape(radius); // memory leak! The shape is not deleted by Bullet and we cannot add it to the KX_Scene.m_shapes list - cinfo.m_MotionState = 0; - cinfo.m_physicsEnv = this; - // declare this object as Dyamic rather than static!! - // The reason as it is designed to detect all type of object, including static object - // It would cause static-static message to be printed on the console otherwise - cinfo.m_collisionFlags |= btCollisionObject::CF_NO_CONTACT_RESPONSE | btCollisionObject::CF_STATIC_OBJECT; - DefaultMotionState* motionState = new DefaultMotionState(); - cinfo.m_MotionState = motionState; - // we will add later the possibility to select the filter from option - cinfo.m_collisionFilterMask = CcdConstructionInfo::AllFilter ^ CcdConstructionInfo::SensorFilter; - cinfo.m_collisionFilterGroup = CcdConstructionInfo::SensorFilter; - cinfo.m_bSensor = true; - motionState->m_worldTransform.setIdentity(); - motionState->m_worldTransform.setOrigin(btVector3(position[0],position[1],position[2])); - - CcdPhysicsController* sphereController = new CcdPhysicsController(cinfo); - - return sphereController; -} - -int findClosestNode(btSoftBody* sb,const btVector3& worldPoint); -int findClosestNode(btSoftBody* sb,const btVector3& worldPoint) -{ - int node = -1; - - btSoftBody::tNodeArray& nodes(sb->m_nodes); - float maxDistSqr = 1e30f; - - for (int n=0;nGetRigidBody() : 0; - btRigidBody* rb1 = c1 ? c1->GetRigidBody() : 0; - - - - - bool rb0static = rb0 ? rb0->isStaticOrKinematicObject() : true; - bool rb1static = rb1 ? rb1->isStaticOrKinematicObject() : true; - - btCollisionObject* colObj0 = c0->GetCollisionObject(); - if (!colObj0) - { - return 0; - } - - btVector3 pivotInA(pivotX,pivotY,pivotZ); - - - - //it might be a soft body, let's try - btSoftBody* sb0 = c0 ? c0->GetSoftBody() : 0; - btSoftBody* sb1 = c1 ? c1->GetSoftBody() : 0; - if (sb0 && sb1) - { - //not between two soft bodies? - return 0; - } - - if (sb0) - { - //either cluster or node attach, let's find closest node first - //the soft body doesn't have a 'real' world transform, so get its initial world transform for now - btVector3 pivotPointSoftWorld = sb0->m_initialWorldTransform(pivotInA); - int node=findClosestNode(sb0,pivotPointSoftWorld); - if (node >=0) - { - bool clusterconstaint = false; -/* - switch (type) - { - case PHY_LINEHINGE_CONSTRAINT: - { - if (sb0->clusterCount() && rb1) - { - btSoftBody::LJoint::Specs ls; - ls.erp=0.5f; - ls.position=sb0->clusterCom(0); - sb0->appendLinearJoint(ls,rb1); - clusterconstaint = true; - break; - } - } - case PHY_GENERIC_6DOF_CONSTRAINT: - { - if (sb0->clusterCount() && rb1) - { - btSoftBody::AJoint::Specs as; - as.erp = 1; - as.cfm = 1; - as.axis.setValue(axisX,axisY,axisZ); - sb0->appendAngularJoint(as,rb1); - clusterconstaint = true; - break; - } - - break; - } - default: - { - - } - }; - */ - - if (!clusterconstaint) - { - if (rb1) - { - sb0->appendAnchor(node,rb1,disableCollisionBetweenLinkedBodies); - } else - { - sb0->setMass(node,0.f); - } - } - - - } - return 0;//can't remove soft body anchors yet - } - - if (sb1) - { - btVector3 pivotPointAWorld = colObj0->getWorldTransform()(pivotInA); - int node=findClosestNode(sb1,pivotPointAWorld); - if (node >=0) - { - bool clusterconstaint = false; - - /* - switch (type) - { - case PHY_LINEHINGE_CONSTRAINT: - { - if (sb1->clusterCount() && rb0) - { - btSoftBody::LJoint::Specs ls; - ls.erp=0.5f; - ls.position=sb1->clusterCom(0); - sb1->appendLinearJoint(ls,rb0); - clusterconstaint = true; - break; - } - } - case PHY_GENERIC_6DOF_CONSTRAINT: - { - if (sb1->clusterCount() && rb0) - { - btSoftBody::AJoint::Specs as; - as.erp = 1; - as.cfm = 1; - as.axis.setValue(axisX,axisY,axisZ); - sb1->appendAngularJoint(as,rb0); - clusterconstaint = true; - break; - } - - break; - } - default: - { - - - } - };*/ - - - if (!clusterconstaint) - { - if (rb0) - { - sb1->appendAnchor(node,rb0,disableCollisionBetweenLinkedBodies); - } else - { - sb1->setMass(node,0.f); - } - } - - - } - return 0;//can't remove soft body anchors yet - } - - if (rb0static && rb1static) - { - - return 0; - } - - - if (!rb0) - return 0; - - btVector3 pivotInB = rb1 ? rb1->getCenterOfMassTransform().inverse()(rb0->getCenterOfMassTransform()(pivotInA)) : - rb0->getCenterOfMassTransform() * pivotInA; - btVector3 axisInA(axisX,axisY,axisZ); - - - bool angularOnly = false; - - switch (type) - { - case PHY_POINT2POINT_CONSTRAINT: - { - // If either of the controllers is missing, we can't do anything. - if (!c0 || !c1) return 0; - - btPoint2PointConstraint* p2p = 0; - - if (rb1) - { - p2p = new btPoint2PointConstraint(*rb0, - *rb1,pivotInA,pivotInB); - } else - { - p2p = new btPoint2PointConstraint(*rb0, - pivotInA); - } - - c0->addCcdConstraintRef(p2p); - c1->addCcdConstraintRef(p2p); - m_dynamicsWorld->addConstraint(p2p,disableCollisionBetweenLinkedBodies); -// m_constraints.push_back(p2p); - - p2p->setUserConstraintId(gConstraintUid++); - p2p->setUserConstraintType(type); - //64 bit systems can't cast pointer to int. could use size_t instead. - return p2p->getUserConstraintId(); - - break; - } - - case PHY_GENERIC_6DOF_CONSTRAINT: - { - // If either of the controllers is missing, we can't do anything. - if (!c0 || !c1) return 0; - - btGeneric6DofConstraint* genericConstraint = 0; - - if (rb1) - { - btTransform frameInA; - btTransform frameInB; - - btVector3 axis1(axis1X,axis1Y,axis1Z), axis2(axis2X,axis2Y,axis2Z); - if (axis1.length() == 0.0f) - { - btPlaneSpace1( axisInA, axis1, axis2 ); - } - - frameInA.getBasis().setValue( axisInA.x(), axis1.x(), axis2.x(), - axisInA.y(), axis1.y(), axis2.y(), - axisInA.z(), axis1.z(), axis2.z() ); - frameInA.setOrigin( pivotInA ); - - btTransform inv = rb1->getCenterOfMassTransform().inverse(); - - btTransform globalFrameA = rb0->getCenterOfMassTransform() * frameInA; - - frameInB = inv * globalFrameA; - bool useReferenceFrameA = true; - - genericConstraint = new btGeneric6DofSpringConstraint( - *rb0,*rb1, - frameInA,frameInB,useReferenceFrameA); - - - } else - { - static btRigidBody s_fixedObject2( 0,0,0); - btTransform frameInA; - btTransform frameInB; - - btVector3 axis1, axis2; - btPlaneSpace1( axisInA, axis1, axis2 ); - - frameInA.getBasis().setValue( axisInA.x(), axis1.x(), axis2.x(), - axisInA.y(), axis1.y(), axis2.y(), - axisInA.z(), axis1.z(), axis2.z() ); - - frameInA.setOrigin( pivotInA ); - - ///frameInB in worldspace - frameInB = rb0->getCenterOfMassTransform() * frameInA; - - bool useReferenceFrameA = true; - genericConstraint = new btGeneric6DofSpringConstraint( - *rb0,s_fixedObject2, - frameInA,frameInB,useReferenceFrameA); - } - - if (genericConstraint) - { - //m_constraints.push_back(genericConstraint); - c0->addCcdConstraintRef(genericConstraint); - c1->addCcdConstraintRef(genericConstraint); - m_dynamicsWorld->addConstraint(genericConstraint,disableCollisionBetweenLinkedBodies); - genericConstraint->setUserConstraintId(gConstraintUid++); - genericConstraint->setUserConstraintType(type); - //64 bit systems can't cast pointer to int. could use size_t instead. - return genericConstraint->getUserConstraintId(); - } - - break; - } - case PHY_CONE_TWIST_CONSTRAINT: - { - // If either of the controllers is missing, we can't do anything. - if (!c0 || !c1) return 0; - - btConeTwistConstraint* coneTwistContraint = 0; - - - if (rb1) - { - btTransform frameInA; - btTransform frameInB; - - btVector3 axis1(axis1X,axis1Y,axis1Z), axis2(axis2X,axis2Y,axis2Z); - if (axis1.length() == 0.0f) - { - btPlaneSpace1( axisInA, axis1, axis2 ); - } - - frameInA.getBasis().setValue( axisInA.x(), axis1.x(), axis2.x(), - axisInA.y(), axis1.y(), axis2.y(), - axisInA.z(), axis1.z(), axis2.z() ); - frameInA.setOrigin( pivotInA ); - - btTransform inv = rb1->getCenterOfMassTransform().inverse(); - - btTransform globalFrameA = rb0->getCenterOfMassTransform() * frameInA; - - frameInB = inv * globalFrameA; - - coneTwistContraint = new btConeTwistConstraint( *rb0,*rb1, - frameInA,frameInB); - - - } else - { - static btRigidBody s_fixedObject2( 0,0,0); - btTransform frameInA; - btTransform frameInB; - - btVector3 axis1, axis2; - btPlaneSpace1( axisInA, axis1, axis2 ); - - frameInA.getBasis().setValue( axisInA.x(), axis1.x(), axis2.x(), - axisInA.y(), axis1.y(), axis2.y(), - axisInA.z(), axis1.z(), axis2.z() ); - - frameInA.setOrigin( pivotInA ); - - ///frameInB in worldspace - frameInB = rb0->getCenterOfMassTransform() * frameInA; - - coneTwistContraint = new btConeTwistConstraint( - *rb0,s_fixedObject2, - frameInA,frameInB); - } - - if (coneTwistContraint) - { - //m_constraints.push_back(genericConstraint); - c0->addCcdConstraintRef(coneTwistContraint); - c1->addCcdConstraintRef(coneTwistContraint); - m_dynamicsWorld->addConstraint(coneTwistContraint,disableCollisionBetweenLinkedBodies); - coneTwistContraint->setUserConstraintId(gConstraintUid++); - coneTwistContraint->setUserConstraintType(type); - //64 bit systems can't cast pointer to int. could use size_t instead. - return coneTwistContraint->getUserConstraintId(); - } - - - - break; - } - case PHY_ANGULAR_CONSTRAINT: - angularOnly = true; - - - case PHY_LINEHINGE_CONSTRAINT: - { - // If either of the controllers is missing, we can't do anything. - if (!c0 || !c1) return 0; - - btHingeConstraint* hinge = 0; - - if (rb1) - { - // We know the orientations so we should use them instead of - // having btHingeConstraint fill in the blanks any way it wants to. - btTransform frameInA; - btTransform frameInB; - - btVector3 axis1(axis1X,axis1Y,axis1Z), axis2(axis2X,axis2Y,axis2Z); - if (axis1.length() == 0.0f) - { - btPlaneSpace1( axisInA, axis1, axis2 ); - } - - // Internally btHingeConstraint's hinge-axis is z - frameInA.getBasis().setValue( axis1.x(), axis2.x(), axisInA.x(), - axis1.y(), axis2.y(), axisInA.y(), - axis1.z(), axis2.z(), axisInA.z() ); - - frameInA.setOrigin( pivotInA ); - - btTransform inv = rb1->getCenterOfMassTransform().inverse(); - - btTransform globalFrameA = rb0->getCenterOfMassTransform() * frameInA; - - frameInB = inv * globalFrameA; - - hinge = new btHingeConstraint(*rb0,*rb1,frameInA,frameInB); - - - } else - { - static btRigidBody s_fixedObject2( 0,0,0); - - btTransform frameInA; - btTransform frameInB; - - btVector3 axis1(axis1X,axis1Y,axis1Z), axis2(axis2X,axis2Y,axis2Z); - if (axis1.length() == 0.0f) - { - btPlaneSpace1( axisInA, axis1, axis2 ); - } - - // Internally btHingeConstraint's hinge-axis is z - frameInA.getBasis().setValue( axis1.x(), axis2.x(), axisInA.x(), - axis1.y(), axis2.y(), axisInA.y(), - axis1.z(), axis2.z(), axisInA.z() ); - frameInA.setOrigin( pivotInA ); - frameInB = rb0->getCenterOfMassTransform() * frameInA; - - hinge = new btHingeConstraint(*rb0, s_fixedObject2, frameInA, frameInB); - } - hinge->setAngularOnly(angularOnly); - - //m_constraints.push_back(hinge); - c0->addCcdConstraintRef(hinge); - c1->addCcdConstraintRef(hinge); - m_dynamicsWorld->addConstraint(hinge,disableCollisionBetweenLinkedBodies); - hinge->setUserConstraintId(gConstraintUid++); - hinge->setUserConstraintType(type); - //64 bit systems can't cast pointer to int. could use size_t instead. - return hinge->getUserConstraintId(); - break; - } -#ifdef NEW_BULLET_VEHICLE_SUPPORT - - case PHY_VEHICLE_CONSTRAINT: - { - btRaycastVehicle::btVehicleTuning* tuning = new btRaycastVehicle::btVehicleTuning(); - btRigidBody* chassis = rb0; - btDefaultVehicleRaycaster* raycaster = new BlenderVehicleRaycaster(m_dynamicsWorld); - btRaycastVehicle* vehicle = new btRaycastVehicle(*tuning,chassis,raycaster); - WrapperVehicle* wrapperVehicle = new WrapperVehicle(vehicle,ctrl0); - m_wrapperVehicles.push_back(wrapperVehicle); - m_dynamicsWorld->addVehicle(vehicle); - vehicle->setUserConstraintId(gConstraintUid++); - vehicle->setUserConstraintType(type); - return vehicle->getUserConstraintId(); - - break; - }; -#endif //NEW_BULLET_VEHICLE_SUPPORT - - default: - { - } - }; - - //btRigidBody& rbA,btRigidBody& rbB, const btVector3& pivotInA,const btVector3& pivotInB - - return 0; - -} - - - -PHY_IPhysicsController* CcdPhysicsEnvironment::CreateConeController(float coneradius,float coneheight) -{ - CcdConstructionInfo cinfo; -//don't memset cinfo: this is C++ and values should be set in the constructor! - - // we don't need a CcdShapeConstructionInfo for this shape: - // it is simple enough for the standard copy constructor (see CcdPhysicsController::GetReplica) - cinfo.m_collisionShape = new btConeShape(coneradius,coneheight); - cinfo.m_MotionState = 0; - cinfo.m_physicsEnv = this; - cinfo.m_collisionFlags |= btCollisionObject::CF_NO_CONTACT_RESPONSE | btCollisionObject::CF_STATIC_OBJECT; - DefaultMotionState* motionState = new DefaultMotionState(); - cinfo.m_MotionState = motionState; - - // we will add later the possibility to select the filter from option - cinfo.m_collisionFilterMask = CcdConstructionInfo::AllFilter ^ CcdConstructionInfo::SensorFilter; - cinfo.m_collisionFilterGroup = CcdConstructionInfo::SensorFilter; - cinfo.m_bSensor = true; - motionState->m_worldTransform.setIdentity(); -// motionState->m_worldTransform.setOrigin(btVector3(position[0],position[1],position[2])); - - CcdPhysicsController* sphereController = new CcdPhysicsController(cinfo); - - - return sphereController; -} - -float CcdPhysicsEnvironment::getAppliedImpulse(int constraintid) -{ - // For soft body constraints - if (constraintid == 0) - return 0.0f; - - int i; - int numConstraints = m_dynamicsWorld->getNumConstraints(); - for (i=0;igetConstraint(i); - if (constraint->getUserConstraintId() == constraintid) - { - return constraint->getAppliedImpulse(); - } - } - - return 0.f; -} - -void CcdPhysicsEnvironment::ExportFile(const char* filename) -{ - btDefaultSerializer* serializer = new btDefaultSerializer(); - - - for (int i=0;igetNumCollisionObjects();i++) - { - - btCollisionObject* colObj = m_dynamicsWorld->getCollisionObjectArray()[i]; - - CcdPhysicsController* controller = static_cast(colObj->getUserPointer()); - if (controller) - { - const char* name = KX_GameObject::GetClientObject((KX_ClientObjectInfo*)controller->GetNewClientInfo())->GetName(); - if (name) - { - serializer->registerNameForPointer(colObj,name); - } - } - } - - m_dynamicsWorld->serialize(serializer); - - FILE* file = fopen(filename,"wb"); - if (file) - { - fwrite(serializer->getBufferPointer(),serializer->getCurrentBufferSize(),1, file); - fclose(file); - } -} - -struct BlenderDebugDraw : public btIDebugDraw -{ - BlenderDebugDraw () : - m_debugMode(0) - { - } - - int m_debugMode; - - virtual void drawLine(const btVector3& from,const btVector3& to,const btVector3& color) - { - if (m_debugMode >0) - { - MT_Vector3 kxfrom(from[0],from[1],from[2]); - MT_Vector3 kxto(to[0],to[1],to[2]); - MT_Vector3 kxcolor(color[0],color[1],color[2]); - - KX_RasterizerDrawDebugLine(kxfrom,kxto,kxcolor); - } - } - - virtual void reportErrorWarning(const char* warningString) - { - - } - - virtual void drawContactPoint(const btVector3& PointOnB,const btVector3& normalOnB,float distance,int lifeTime,const btVector3& color) - { - drawLine(PointOnB, PointOnB + normalOnB, color); - drawSphere(PointOnB, 0.1f, color); - } - - virtual void setDebugMode(int debugMode) - { - m_debugMode = debugMode; - } - virtual int getDebugMode() const - { - return m_debugMode; - } - ///todo: find out if Blender can do this - virtual void draw3dText(const btVector3& location,const char* textString) - { - - } - -}; - -CcdPhysicsEnvironment *CcdPhysicsEnvironment::Create(Scene *blenderscene, bool visualizePhysics) -{ - CcdPhysicsEnvironment* ccdPhysEnv = new CcdPhysicsEnvironment((blenderscene->gm.mode & WO_DBVT_CULLING) != 0); - ccdPhysEnv->SetDebugDrawer(new BlenderDebugDraw()); - ccdPhysEnv->SetDeactivationLinearTreshold(blenderscene->gm.lineardeactthreshold); - ccdPhysEnv->SetDeactivationAngularTreshold(blenderscene->gm.angulardeactthreshold); - ccdPhysEnv->SetDeactivationTime(blenderscene->gm.deactivationtime); - - if (visualizePhysics) - ccdPhysEnv->SetDebugMode(btIDebugDraw::DBG_DrawWireframe|btIDebugDraw::DBG_DrawAabb|btIDebugDraw::DBG_DrawContactPoints|btIDebugDraw::DBG_DrawText|btIDebugDraw::DBG_DrawConstraintLimits|btIDebugDraw::DBG_DrawConstraints); - - return ccdPhysEnv; -} - -void CcdPhysicsEnvironment::ConvertObject(KX_GameObject *gameobj, RAS_MeshObject *meshobj, DerivedMesh *dm, KX_Scene *kxscene, PHY_ShapeProps *shapeprops, PHY_MaterialProps *smmaterial, PHY_IMotionState *motionstate, int activeLayerBitInfo, bool isCompoundChild, bool hasCompoundChildren) -{ - Object* blenderobject = gameobj->GetBlenderObject(); - - bool isbulletdyna = (blenderobject->gameflag & OB_DYNAMIC) != 0; - bool isbulletsensor = (blenderobject->gameflag & OB_SENSOR) != 0; - bool isbulletchar = (blenderobject->gameflag & OB_CHARACTER) != 0; - bool isbulletsoftbody = (blenderobject->gameflag & OB_SOFT_BODY) != 0; - bool isbulletrigidbody = (blenderobject->gameflag & OB_RIGID_BODY) != 0; - bool useGimpact = false; - CcdConstructionInfo ci; - class CcdShapeConstructionInfo *shapeInfo = new CcdShapeConstructionInfo(); - - // get Root Parent of blenderobject - Object *blenderparent = blenderobject->parent; - while (blenderparent && blenderparent->parent) { - blenderparent = blenderparent->parent; - } - - KX_GameObject *parent = NULL; - if (blenderparent) - { - KX_BlenderSceneConverter *converter = (KX_BlenderSceneConverter*)KX_GetActiveEngine()->GetSceneConverter(); - parent = converter->FindGameObject(blenderparent); - isbulletsoftbody = false; - } - - if (!isbulletdyna) - { - ci.m_collisionFlags |= btCollisionObject::CF_STATIC_OBJECT; - } - if ((blenderobject->gameflag & (OB_GHOST | OB_SENSOR | OB_CHARACTER)) != 0) - { - ci.m_collisionFlags |= btCollisionObject::CF_NO_CONTACT_RESPONSE; - } - - ci.m_MotionState = motionstate; - ci.m_gravity = btVector3(0,0,0); - ci.m_linearFactor = btVector3(((blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_X_AXIS) !=0)? 0 : 1, - ((blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_Y_AXIS) !=0)? 0 : 1, - ((blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_Z_AXIS) !=0)? 0 : 1); - ci.m_angularFactor = btVector3(((blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_X_ROT_AXIS) !=0)? 0 : 1, - ((blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_Y_ROT_AXIS) !=0)? 0 : 1, - ((blenderobject->gameflag2 & OB_LOCK_RIGID_BODY_Z_ROT_AXIS) !=0)? 0 : 1); - ci.m_localInertiaTensor =btVector3(0,0,0); - ci.m_mass = isbulletdyna ? shapeprops->m_mass : 0.f; - ci.m_clamp_vel_min = shapeprops->m_clamp_vel_min; - ci.m_clamp_vel_max = shapeprops->m_clamp_vel_max; - ci.m_clamp_angvel_min = shapeprops->m_clamp_angvel_min; - ci.m_clamp_angvel_max = shapeprops->m_clamp_angvel_max; - ci.m_stepHeight = isbulletchar ? shapeprops->m_step_height : 0.f; - ci.m_jumpSpeed = isbulletchar ? shapeprops->m_jump_speed : 0.f; - ci.m_fallSpeed = isbulletchar ? shapeprops->m_fall_speed : 0.f; - ci.m_maxJumps = isbulletchar ? shapeprops->m_max_jumps : 0; - - //mmm, for now, take this for the size of the dynamicobject - // Blender uses inertia for radius of dynamic object - shapeInfo->m_radius = ci.m_radius = blenderobject->inertia; - useGimpact = ((isbulletdyna || isbulletsensor) && !isbulletsoftbody); - - if (isbulletsoftbody) - { - if (blenderobject->bsoft) - { - ci.m_margin = blenderobject->bsoft->margin; - ci.m_gamesoftFlag = blenderobject->bsoft->flag; - - ci.m_soft_linStiff = blenderobject->bsoft->linStiff; - ci.m_soft_angStiff = blenderobject->bsoft->angStiff; /* angular stiffness 0..1 */ - ci.m_soft_volume = blenderobject->bsoft->volume; /* volume preservation 0..1 */ - - ci.m_soft_viterations = blenderobject->bsoft->viterations; /* Velocities solver iterations */ - ci.m_soft_piterations = blenderobject->bsoft->piterations; /* Positions solver iterations */ - ci.m_soft_diterations = blenderobject->bsoft->diterations; /* Drift solver iterations */ - ci.m_soft_citerations = blenderobject->bsoft->citerations; /* Cluster solver iterations */ - - ci.m_soft_kSRHR_CL = blenderobject->bsoft->kSRHR_CL; /* Soft vs rigid hardness [0,1] (cluster only) */ - ci.m_soft_kSKHR_CL = blenderobject->bsoft->kSKHR_CL; /* Soft vs kinetic hardness [0,1] (cluster only) */ - ci.m_soft_kSSHR_CL = blenderobject->bsoft->kSSHR_CL; /* Soft vs soft hardness [0,1] (cluster only) */ - ci.m_soft_kSR_SPLT_CL = blenderobject->bsoft->kSR_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */ - - ci.m_soft_kSK_SPLT_CL = blenderobject->bsoft->kSK_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */ - ci.m_soft_kSS_SPLT_CL = blenderobject->bsoft->kSS_SPLT_CL; /* Soft vs rigid impulse split [0,1] (cluster only) */ - ci.m_soft_kVCF = blenderobject->bsoft->kVCF; /* Velocities correction factor (Baumgarte) */ - ci.m_soft_kDP = blenderobject->bsoft->kDP; /* Damping coefficient [0,1] */ - - ci.m_soft_kDG = blenderobject->bsoft->kDG; /* Drag coefficient [0,+inf] */ - ci.m_soft_kLF = blenderobject->bsoft->kLF; /* Lift coefficient [0,+inf] */ - ci.m_soft_kPR = blenderobject->bsoft->kPR; /* Pressure coefficient [-inf,+inf] */ - ci.m_soft_kVC = blenderobject->bsoft->kVC; /* Volume conversation coefficient [0,+inf] */ - - ci.m_soft_kDF = blenderobject->bsoft->kDF; /* Dynamic friction coefficient [0,1] */ - ci.m_soft_kMT = blenderobject->bsoft->kMT; /* Pose matching coefficient [0,1] */ - ci.m_soft_kCHR = blenderobject->bsoft->kCHR; /* Rigid contacts hardness [0,1] */ - ci.m_soft_kKHR = blenderobject->bsoft->kKHR; /* Kinetic contacts hardness [0,1] */ - - ci.m_soft_kSHR = blenderobject->bsoft->kSHR; /* Soft contacts hardness [0,1] */ - ci.m_soft_kAHR = blenderobject->bsoft->kAHR; /* Anchors hardness [0,1] */ - ci.m_soft_collisionflags = blenderobject->bsoft->collisionflags; /* Vertex/Face or Signed Distance Field(SDF) or Clusters, Soft versus Soft or Rigid */ - ci.m_soft_numclusteriterations = blenderobject->bsoft->numclusteriterations; /* number of iterations to refine collision clusters*/ - - } - else - { - ci.m_margin = 0.f; - ci.m_gamesoftFlag = OB_BSB_BENDING_CONSTRAINTS | OB_BSB_SHAPE_MATCHING | OB_BSB_AERO_VPOINT; - - ci.m_soft_linStiff = 0.5f; - ci.m_soft_angStiff = 1.f; /* angular stiffness 0..1 */ - ci.m_soft_volume = 1.f; /* volume preservation 0..1 */ - - ci.m_soft_viterations = 0; - ci.m_soft_piterations = 1; - ci.m_soft_diterations = 0; - ci.m_soft_citerations = 4; - - ci.m_soft_kSRHR_CL = 0.1f; - ci.m_soft_kSKHR_CL = 1.f; - ci.m_soft_kSSHR_CL = 0.5f; - ci.m_soft_kSR_SPLT_CL = 0.5f; - - ci.m_soft_kSK_SPLT_CL = 0.5f; - ci.m_soft_kSS_SPLT_CL = 0.5f; - ci.m_soft_kVCF = 1; - ci.m_soft_kDP = 0; - - ci.m_soft_kDG = 0; - ci.m_soft_kLF = 0; - ci.m_soft_kPR = 0; - ci.m_soft_kVC = 0; - - ci.m_soft_kDF = 0.2f; - ci.m_soft_kMT = 0.05f; - ci.m_soft_kCHR = 1.0f; - ci.m_soft_kKHR = 0.1f; - - ci.m_soft_kSHR = 1.f; - ci.m_soft_kAHR = 0.7f; - ci.m_soft_collisionflags = OB_BSB_COL_SDF_RS + OB_BSB_COL_VF_SS; - ci.m_soft_numclusteriterations = 16; - } - } - else - { - ci.m_margin = blenderobject->margin; - } - - ci.m_localInertiaTensor = btVector3(ci.m_mass/3.f,ci.m_mass/3.f,ci.m_mass/3.f); - - btCollisionShape* bm = 0; - - char bounds = isbulletdyna ? OB_BOUND_SPHERE : OB_BOUND_TRIANGLE_MESH; - if (!(blenderobject->gameflag & OB_BOUNDS)) - { - if (blenderobject->gameflag & OB_SOFT_BODY) - bounds = OB_BOUND_TRIANGLE_MESH; - else if (blenderobject->gameflag & OB_CHARACTER) - bounds = OB_BOUND_SPHERE; - } - else - { - if (ELEM(blenderobject->collision_boundtype, OB_BOUND_CONVEX_HULL, OB_BOUND_TRIANGLE_MESH) - && blenderobject->type != OB_MESH) - { - // Can't use triangle mesh or convex hull on a non-mesh object, fall-back to sphere - bounds = OB_BOUND_SPHERE; - } - else - bounds = blenderobject->collision_boundtype; - } - - // Get bounds information - float bounds_center[3], bounds_extends[3]; - BoundBox *bb= BKE_object_boundbox_get(blenderobject); - if (bb==NULL) - { - bounds_center[0] = bounds_center[1] = bounds_center[2] = 0.0f; - bounds_extends[0] = bounds_extends[1] = bounds_extends[2] = 1.0f; - } - else - { - bounds_extends[0] = 0.5f * fabsf(bb->vec[0][0] - bb->vec[4][0]); - bounds_extends[1] = 0.5f * fabsf(bb->vec[0][1] - bb->vec[2][1]); - bounds_extends[2] = 0.5f * fabsf(bb->vec[0][2] - bb->vec[1][2]); - - bounds_center[0] = 0.5f * (bb->vec[0][0] + bb->vec[4][0]); - bounds_center[1] = 0.5f * (bb->vec[0][1] + bb->vec[2][1]); - bounds_center[2] = 0.5f * (bb->vec[0][2] + bb->vec[1][2]); - } - - switch (bounds) - { - case OB_BOUND_SPHERE: - { - //float radius = objprop->m_radius; - //btVector3 inertiaHalfExtents ( - // radius, - // radius, - // radius); - - //blender doesn't support multisphere, but for testing: - - //bm = new MultiSphereShape(inertiaHalfExtents,,&trans.getOrigin(),&radius,1); - shapeInfo->m_shapeType = PHY_SHAPE_SPHERE; - // XXX We calculated the radius but didn't use it? - // objprop.m_boundobject.c.m_radius = MT_max(bb.m_extends[0], MT_max(bb.m_extends[1], bb.m_extends[2])); - bm = shapeInfo->CreateBulletShape(ci.m_margin); - break; - }; - case OB_BOUND_BOX: - { - shapeInfo->m_halfExtend.setValue( - 2.f * bounds_extends[0], - 2.f * bounds_extends[1], - 2.f * bounds_extends[2]); - - shapeInfo->m_halfExtend /= 2.0f; - shapeInfo->m_halfExtend = shapeInfo->m_halfExtend.absolute(); - shapeInfo->m_shapeType = PHY_SHAPE_BOX; - bm = shapeInfo->CreateBulletShape(ci.m_margin); - break; - }; - case OB_BOUND_CYLINDER: - { - float radius = MT_max(bounds_extends[0], bounds_extends[1]); - shapeInfo->m_halfExtend.setValue( - radius, - radius, - bounds_extends[2] - ); - shapeInfo->m_shapeType = PHY_SHAPE_CYLINDER; - bm = shapeInfo->CreateBulletShape(ci.m_margin); - break; - } - - case OB_BOUND_CONE: - { - shapeInfo->m_radius = MT_max(bounds_extends[0], bounds_extends[1]); - shapeInfo->m_height = 2.f * bounds_extends[2]; - shapeInfo->m_shapeType = PHY_SHAPE_CONE; - bm = shapeInfo->CreateBulletShape(ci.m_margin); - break; - } - case OB_BOUND_CONVEX_HULL: - { - shapeInfo->SetMesh(meshobj, dm,true); - bm = shapeInfo->CreateBulletShape(ci.m_margin); - break; - } - case OB_BOUND_CAPSULE: - { - shapeInfo->m_radius = MT_max(bounds_extends[0], bounds_extends[1]); - shapeInfo->m_height = 2.f * (bounds_extends[2] - shapeInfo->m_radius); - if (shapeInfo->m_height < 0.f) - shapeInfo->m_height = 0.f; - shapeInfo->m_shapeType = PHY_SHAPE_CAPSULE; - bm = shapeInfo->CreateBulletShape(ci.m_margin); - break; - } - case OB_BOUND_TRIANGLE_MESH: - { - // mesh shapes can be shared, check first if we already have a shape on that mesh - class CcdShapeConstructionInfo *sharedShapeInfo = CcdShapeConstructionInfo::FindMesh(meshobj, dm, false); - if (sharedShapeInfo != NULL) - { - shapeInfo->Release(); - shapeInfo = sharedShapeInfo; - shapeInfo->AddRef(); - } else - { - shapeInfo->SetMesh(meshobj, dm, false); - } - - // Soft bodies can benefit from welding, don't do it on non-soft bodies - if (isbulletsoftbody) - { - // disable welding: it doesn't bring any additional stability and it breaks the relation between soft body collision shape and graphic mesh - // shapeInfo->setVertexWeldingThreshold1((blenderobject->bsoft) ? blenderobject->bsoft->welding ? 0.f); - shapeInfo->setVertexWeldingThreshold1(0.f); //todo: expose this to the UI - } - - bm = shapeInfo->CreateBulletShape(ci.m_margin, useGimpact, !isbulletsoftbody); - //should we compute inertia for dynamic shape? - //bm->calculateLocalInertia(ci.m_mass,ci.m_localInertiaTensor); - - break; - } - } - - -// ci.m_localInertiaTensor.setValue(0.1f,0.1f,0.1f); - - if (!bm) - { - delete motionstate; - shapeInfo->Release(); - return; - } - - //bm->setMargin(ci.m_margin); - - - if (isCompoundChild) - { - //find parent, compound shape and add to it - //take relative transform into account! - CcdPhysicsController* parentCtrl = (CcdPhysicsController*)parent->GetPhysicsController(); - assert(parentCtrl); - - // only makes compound shape if parent has a physics controller (i.e not an empty, etc) - if (parentCtrl) { - CcdShapeConstructionInfo* parentShapeInfo = parentCtrl->GetShapeInfo(); - btRigidBody* rigidbody = parentCtrl->GetRigidBody(); - btCollisionShape* colShape = rigidbody->getCollisionShape(); - assert(colShape->isCompound()); - btCompoundShape* compoundShape = (btCompoundShape*)colShape; - - // compute the local transform from parent, this may include several node in the chain - SG_Node* gameNode = gameobj->GetSGNode(); - SG_Node* parentNode = parent->GetSGNode(); - // relative transform - MT_Vector3 parentScale = parentNode->GetWorldScaling(); - parentScale[0] = MT_Scalar(1.0f)/parentScale[0]; - parentScale[1] = MT_Scalar(1.0f)/parentScale[1]; - parentScale[2] = MT_Scalar(1.0f)/parentScale[2]; - MT_Vector3 relativeScale = gameNode->GetWorldScaling() * parentScale; - MT_Matrix3x3 parentInvRot = parentNode->GetWorldOrientation().transposed(); - MT_Vector3 relativePos = parentInvRot*((gameNode->GetWorldPosition()-parentNode->GetWorldPosition())*parentScale); - MT_Matrix3x3 relativeRot = parentInvRot*gameNode->GetWorldOrientation(); - - shapeInfo->m_childScale.setValue(relativeScale[0],relativeScale[1],relativeScale[2]); - bm->setLocalScaling(shapeInfo->m_childScale); - shapeInfo->m_childTrans.getOrigin().setValue(relativePos[0],relativePos[1],relativePos[2]); - float rot[12]; - relativeRot.getValue(rot); - shapeInfo->m_childTrans.getBasis().setFromOpenGLSubMatrix(rot); - - parentShapeInfo->AddShape(shapeInfo); - compoundShape->addChildShape(shapeInfo->m_childTrans,bm); - //do some recalc? - //recalc inertia for rigidbody - if (!rigidbody->isStaticOrKinematicObject()) - { - btVector3 localInertia; - float mass = 1.f/rigidbody->getInvMass(); - compoundShape->calculateLocalInertia(mass,localInertia); - rigidbody->setMassProps(mass,localInertia); - } - shapeInfo->Release(); - // delete motionstate as it's not used - delete motionstate; - } - return; - } - - if (hasCompoundChildren) - { - // create a compound shape info - CcdShapeConstructionInfo *compoundShapeInfo = new CcdShapeConstructionInfo(); - compoundShapeInfo->m_shapeType = PHY_SHAPE_COMPOUND; - compoundShapeInfo->AddShape(shapeInfo); - // create the compound shape manually as we already have the child shape - btCompoundShape* compoundShape = new btCompoundShape(); - compoundShape->addChildShape(shapeInfo->m_childTrans,bm); - // now replace the shape - bm = compoundShape; - shapeInfo->Release(); - shapeInfo = compoundShapeInfo; - } - - - - - - -#ifdef TEST_SIMD_HULL - if (bm->IsPolyhedral()) - { - PolyhedralConvexShape* polyhedron = static_cast(bm); - if (!polyhedron->m_optionalHull) - { - //first convert vertices in 'Point3' format - int numPoints = polyhedron->GetNumVertices(); - Point3* points = new Point3[numPoints+1]; - //first 4 points should not be co-planar, so add central point to satisfy MakeHull - points[0] = Point3(0.f,0.f,0.f); - - btVector3 vertex; - for (int p=0;pGetVertex(p,vertex); - points[p+1] = Point3(vertex.getX(),vertex.getY(),vertex.getZ()); - } - - Hull* hull = Hull::MakeHull(numPoints+1,points); - polyhedron->m_optionalHull = hull; - } - - } -#endif //TEST_SIMD_HULL - - - ci.m_collisionShape = bm; - ci.m_shapeInfo = shapeInfo; - ci.m_friction = smmaterial->m_friction;//tweak the friction a bit, so the default 0.5 works nice - ci.m_restitution = smmaterial->m_restitution; - ci.m_physicsEnv = this; - // drag / damping is inverted - ci.m_linearDamping = 1.f - shapeprops->m_lin_drag; - ci.m_angularDamping = 1.f - shapeprops->m_ang_drag; - //need a bit of damping, else system doesn't behave well - ci.m_inertiaFactor = shapeprops->m_inertia/0.4f;//defaults to 0.4, don't want to change behavior - - ci.m_do_anisotropic = shapeprops->m_do_anisotropic; - ci.m_anisotropicFriction.setValue(shapeprops->m_friction_scaling[0],shapeprops->m_friction_scaling[1],shapeprops->m_friction_scaling[2]); - - -////////// - //do Fh, do Rot Fh - ci.m_do_fh = shapeprops->m_do_fh; - ci.m_do_rot_fh = shapeprops->m_do_rot_fh; - ci.m_fh_damping = smmaterial->m_fh_damping; - ci.m_fh_distance = smmaterial->m_fh_distance; - ci.m_fh_normal = smmaterial->m_fh_normal; - ci.m_fh_spring = smmaterial->m_fh_spring; - - ci.m_collisionFilterGroup = - (isbulletsensor) ? short(CcdConstructionInfo::SensorFilter) : - (isbulletdyna) ? short(CcdConstructionInfo::DefaultFilter) : - (isbulletchar) ? short(CcdConstructionInfo::CharacterFilter) : - short(CcdConstructionInfo::StaticFilter); - ci.m_collisionFilterMask = - (isbulletsensor) ? short(CcdConstructionInfo::AllFilter ^ CcdConstructionInfo::SensorFilter) : - (isbulletdyna) ? short(CcdConstructionInfo::AllFilter) : - (isbulletchar) ? short(CcdConstructionInfo::AllFilter) : - short(CcdConstructionInfo::AllFilter ^ CcdConstructionInfo::StaticFilter); - ci.m_bRigid = isbulletdyna && isbulletrigidbody; - ci.m_bSoft = isbulletsoftbody; - ci.m_bDyna = isbulletdyna; - ci.m_bSensor = isbulletsensor; - ci.m_bCharacter = isbulletchar; - ci.m_bGimpact = useGimpact; - MT_Vector3 scaling = gameobj->NodeGetWorldScaling(); - ci.m_scaling.setValue(scaling[0], scaling[1], scaling[2]); - CcdPhysicsController* physicscontroller = new CcdPhysicsController(ci); - // shapeInfo is reference counted, decrement now as we don't use it anymore - if (shapeInfo) - shapeInfo->Release(); - - gameobj->SetPhysicsController(physicscontroller,isbulletdyna); - - // record animation for dynamic objects - if (isbulletdyna) - gameobj->SetRecordAnimation(true); - - physicscontroller->SetNewClientInfo(gameobj->getClientInfo()); - - // don't add automatically sensor object, they are added when a collision sensor is registered - if (!isbulletsensor && (blenderobject->lay & activeLayerBitInfo) != 0) - { - this->AddCcdPhysicsController( physicscontroller); - } - - { - btRigidBody* rbody = physicscontroller->GetRigidBody(); - - if (rbody) - { - rbody->setLinearFactor(ci.m_linearFactor); - - if (isbulletrigidbody) - { - rbody->setAngularFactor(ci.m_angularFactor); - } - - if (rbody && (blenderobject->gameflag & OB_COLLISION_RESPONSE) != 0) - { - rbody->setActivationState(DISABLE_DEACTIVATION); - } - } - } - - if (parent) - physicscontroller->SuspendDynamics(false); - - CcdPhysicsController* parentCtrl = parent ? (CcdPhysicsController*)parent->GetPhysicsController() : 0; - physicscontroller->SetParentCtrl(parentCtrl); - - - //Now done directly in ci.m_collisionFlags so that it propagates to replica - //if (objprop->m_ghost) - //{ - // rbody->setCollisionFlags(rbody->getCollisionFlags() | btCollisionObject::CF_NO_CONTACT_RESPONSE); - //} - - if (isbulletdyna && !isbulletrigidbody) - { -#if 0 - //setting the inertia could achieve similar results to constraint the up - //but it is prone to instability, so use special 'Angular' constraint - btVector3 inertia = physicscontroller->GetRigidBody()->getInvInertiaDiagLocal(); - inertia.setX(0.f); - inertia.setZ(0.f); - - physicscontroller->GetRigidBody()->setInvInertiaDiagLocal(inertia); - physicscontroller->GetRigidBody()->updateInertiaTensor(); -#endif - - //this->createConstraint(physicscontroller,0,PHY_ANGULAR_CONSTRAINT,0,0,0,0,0,1); - - //Now done directly in ci.m_bRigid so that it propagates to replica - //physicscontroller->GetRigidBody()->setAngularFactor(0.f); - ; - } - - - STR_String materialname; - if (meshobj) - materialname = meshobj->GetMaterialName(0); - - -#if 0 - ///test for soft bodies - if (objprop->m_softbody && physicscontroller) - { - btSoftBody* softBody = physicscontroller->GetSoftBody(); - if (softBody && gameobj->GetMesh(0))//only the first mesh, if any - { - //should be a mesh then, so add a soft body deformer - KX_SoftBodyDeformer* softbodyDeformer = new KX_SoftBodyDeformer( gameobj->GetMesh(0),(BL_DeformableGameObject*)gameobj); - gameobj->SetDeformer(softbodyDeformer); - } - } -#endif -} - - -void CcdPhysicsEnvironment::SetupObjectConstraints(KX_GameObject *obj_src, KX_GameObject *obj_dest, - bRigidBodyJointConstraint *dat) -{ - PHY_IPhysicsController *phy_src = obj_src->GetPhysicsController(); - PHY_IPhysicsController *phy_dest = obj_dest->GetPhysicsController(); - PHY_IPhysicsEnvironment *phys_env = obj_src->GetScene()->GetPhysicsEnvironment(); - - /* We need to pass a full constraint frame, not just axis. */ - MT_Matrix3x3 localCFrame(MT_Vector3(dat->axX,dat->axY,dat->axZ)); - MT_Vector3 axis0 = localCFrame.getColumn(0); - MT_Vector3 axis1 = localCFrame.getColumn(1); - MT_Vector3 axis2 = localCFrame.getColumn(2); - MT_Vector3 scale = obj_src->NodeGetWorldScaling(); - - /* Apply not only the pivot and axis values, but also take scale into count - * this is not working well, if only one or two axis are scaled, but works ok on - * homogeneous scaling. */ - int constraintId = phys_env->CreateConstraint( - phy_src, phy_dest, (PHY_ConstraintType)dat->type, - (float)(dat->pivX * scale.x()), (float)(dat->pivY * scale.y()), (float)(dat->pivZ * scale.z()), - (float)(axis0.x() * scale.x()), (float)(axis0.y() * scale.y()), (float)(axis0.z() * scale.z()), - (float)(axis1.x() * scale.x()), (float)(axis1.y() * scale.y()), (float)(axis1.z() * scale.z()), - (float)(axis2.x() * scale.x()), (float)(axis2.y() * scale.y()), (float)(axis2.z() * scale.z()), - dat->flag); - - /* PHY_POINT2POINT_CONSTRAINT = 1, - * PHY_LINEHINGE_CONSTRAINT = 2, - * PHY_ANGULAR_CONSTRAINT = 3, - * PHY_CONE_TWIST_CONSTRAINT = 4, - * PHY_VEHICLE_CONSTRAINT = 11, - * PHY_GENERIC_6DOF_CONSTRAINT = 12 */ - - if (!constraintId) - return; - - int dof = 0; - int dof_max = 0; - int dofbit = 0; - - switch (dat->type) { - /* Set all the limits for generic 6DOF constraint. */ - case PHY_GENERIC_6DOF_CONSTRAINT: - dof_max = 6; - dofbit = 1; - break; - /* Set XYZ angular limits for cone twist constraint. */ - case PHY_CONE_TWIST_CONSTRAINT: - dof = 3; - dof_max = 6; - dofbit = 1 << 3; - break; - /* Set only X angular limits for line hinge and angular constraint. */ - case PHY_LINEHINGE_CONSTRAINT: - case PHY_ANGULAR_CONSTRAINT: - dof = 3; - dof_max = 4; - dofbit = 1 << 3; - break; - default: - break; - } - - for (; dof < dof_max; dof++) { - if (dat->flag & dofbit) { - phys_env->SetConstraintParam(constraintId, dof, dat->minLimit[dof], dat->maxLimit[dof]); - } - else { - /* minLimit > maxLimit means free (no limit) for this degree of freedom. */ - phys_env->SetConstraintParam(constraintId, dof, 1.0f, -1.0f); - } - dofbit <<= 1; - } - -} diff --git a/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h b/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h deleted file mode 100644 index a64d2c8f15f..00000000000 --- a/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h +++ /dev/null @@ -1,345 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -/** \file CcdPhysicsEnvironment.h - * \ingroup physbullet - * See also \ref bulletdoc - */ - -#ifndef __CCDPHYSICSENVIRONMENT_H__ -#define __CCDPHYSICSENVIRONMENT_H__ - -#include "PHY_IPhysicsEnvironment.h" -#include "KX_KetsjiEngine.h" - -#include -#include -#include -class CcdPhysicsController; -class CcdGraphicController; -#include "LinearMath/btVector3.h" -#include "LinearMath/btTransform.h" - - - - -class btTypedConstraint; -class btSimulationIslandManager; -class btCollisionDispatcher; -class btDispatcher; -//#include "btBroadphaseInterface.h" - -//switch on/off new vehicle support -#define NEW_BULLET_VEHICLE_SUPPORT 1 - -#include "BulletDynamics/ConstraintSolver/btContactSolverInfo.h" - -class WrapperVehicle; -class btPersistentManifold; -class btBroadphaseInterface; -struct btDbvtBroadphase; -class btOverlappingPairCache; -class btIDebugDraw; -class btDynamicsWorld; -class PHY_IVehicle; -class CcdOverlapFilterCallBack; -class CcdShapeConstructionInfo; - -/** CcdPhysicsEnvironment is an experimental mainloop for physics simulation using optional continuous collision detection. - * Physics Environment takes care of stepping the simulation and is a container for physics entities. - * It stores rigidbodies,constraints, materials etc. - * A derived class may be able to 'construct' entities by loading and/or converting - */ -class CcdPhysicsEnvironment : public PHY_IPhysicsEnvironment -{ - friend class CcdOverlapFilterCallBack; - btVector3 m_gravity; - - // Removes the constraint and his references from the owner and the target. - void RemoveConstraint(btTypedConstraint *con); - -protected: - btIDebugDraw* m_debugDrawer; - - class btDefaultCollisionConfiguration* m_collisionConfiguration; - class btBroadphaseInterface* m_broadphase; // broadphase for dynamic world - // for culling only - btOverlappingPairCache* m_cullingCache; - struct btDbvtBroadphase* m_cullingTree; // broadphase for culling - - //solver iterations - int m_numIterations; - - //timestep subdivisions - int m_numTimeSubSteps; - - - int m_ccdMode; - int m_solverType; - int m_profileTimings; - bool m_enableSatCollisionDetection; - - float m_deactivationTime; - float m_linearDeactivationThreshold; - float m_angularDeactivationThreshold; - float m_contactBreakingThreshold; - - void ProcessFhSprings(double curTime,float timeStep); - - public: - CcdPhysicsEnvironment(bool useDbvtCulling, btDispatcher* dispatcher=0, btOverlappingPairCache* pairCache=0); - - virtual ~CcdPhysicsEnvironment(); - - ///////////////////////////////////// - //PHY_IPhysicsEnvironment interface - ///////////////////////////////////// - - /// Perform an integration step of duration 'timeStep'. - - virtual void SetDebugDrawer(btIDebugDraw* debugDrawer); - - virtual void SetNumIterations(int numIter); - virtual void SetNumTimeSubSteps(int numTimeSubSteps) - { - m_numTimeSubSteps = numTimeSubSteps; - } - virtual void SetDeactivationTime(float dTime); - virtual void SetDeactivationLinearTreshold(float linTresh); - virtual void SetDeactivationAngularTreshold(float angTresh); - virtual void SetContactBreakingTreshold(float contactBreakingTreshold); - virtual void SetCcdMode(int ccdMode); - virtual void SetSolverType(int solverType); - virtual void SetSolverSorConstant(float sor); - virtual void SetSolverTau(float tau); - virtual void SetSolverDamping(float damping); - virtual void SetLinearAirDamping(float damping); - virtual void SetUseEpa(bool epa); - - virtual int GetNumTimeSubSteps() - { - return m_numTimeSubSteps; - } - - virtual void BeginFrame(); - virtual void EndFrame() {} - /// Perform an integration step of duration 'timeStep'. - virtual bool ProceedDeltaTime(double curTime,float timeStep,float interval); - - /** - * Called by Bullet for every physical simulation (sub)tick. - * Our constructor registers this callback to Bullet, which stores a pointer to 'this' in - * the btDynamicsWorld::getWorldUserInfo() pointer. - */ - static void StaticSimulationSubtickCallback(btDynamicsWorld *world, btScalar timeStep); - void SimulationSubtickCallback(btScalar timeStep); - - virtual void DebugDrawWorld(); -// virtual bool proceedDeltaTimeOneStep(float timeStep); - - virtual void SetFixedTimeStep(bool useFixedTimeStep,float fixedTimeStep) - { - SetNumTimeSubSteps((int)(fixedTimeStep / KX_KetsjiEngine::GetTicRate())); - } - //returns 0.f if no fixed timestep is used - - virtual float GetFixedTimeStep() { return 0.f; } - - virtual void SetDebugMode(int debugMode); - virtual int GetDebugMode()const; - - virtual void SetGravity(float x,float y,float z); - virtual void GetGravity(MT_Vector3& grav); - - - virtual int CreateConstraint(class PHY_IPhysicsController* ctrl,class PHY_IPhysicsController* ctrl2,PHY_ConstraintType type, - float pivotX,float pivotY,float pivotZ, - float axisX,float axisY,float axisZ, - float axis1X=0,float axis1Y=0,float axis1Z=0, - float axis2X=0,float axis2Y=0,float axis2Z=0,int flag=0 - ); - - - //Following the COLLADA physics specification for constraints - virtual int CreateUniversalD6Constraint( - class PHY_IPhysicsController* ctrlRef,class PHY_IPhysicsController* ctrlOther, - btTransform& localAttachmentFrameRef, - btTransform& localAttachmentOther, - const btVector3& linearMinLimits, - const btVector3& linearMaxLimits, - const btVector3& angularMinLimits, - const btVector3& angularMaxLimits,int flags - ); - - - virtual void SetConstraintParam(int constraintId,int param,float value,float value1); - - virtual float GetConstraintParam(int constraintId,int param); - - virtual void RemoveConstraintById(int constraintid); - - virtual float getAppliedImpulse(int constraintid); - - - virtual void CallbackTriggers(); - - -#ifdef NEW_BULLET_VEHICLE_SUPPORT - //complex constraint for vehicles - virtual PHY_IVehicle* GetVehicleConstraint(int constraintId); -#else - virtual class PHY_IVehicle* GetVehicleConstraint(int constraintId) - { - return 0; - } -#endif /* NEW_BULLET_VEHICLE_SUPPORT */ - // Character physics wrapper - virtual PHY_ICharacter* GetCharacterController(class KX_GameObject* ob); - - btTypedConstraint* GetConstraintById(int constraintId); - - virtual PHY_IPhysicsController* RayTest(PHY_IRayCastFilterCallback &filterCallback, float fromX,float fromY,float fromZ, float toX,float toY,float toZ); - virtual bool CullingTest(PHY_CullingCallback callback, void* userData, MT_Vector4* planes, int nplanes, int occlusionRes, const int *viewport, float modelview[16], float projection[16]); - - - //Methods for gamelogic collision/physics callbacks - virtual void AddSensor(PHY_IPhysicsController* ctrl); - virtual void RemoveSensor(PHY_IPhysicsController* ctrl); - virtual void AddTouchCallback(int response_class, PHY_ResponseCallback callback, void *user); - virtual bool RequestCollisionCallback(PHY_IPhysicsController* ctrl); - virtual bool RemoveCollisionCallback(PHY_IPhysicsController* ctrl); - //These two methods are used *solely* to create controllers for Near/Radar sensor! Don't use for anything else - virtual PHY_IPhysicsController* CreateSphereController(float radius,const MT_Vector3& position); - virtual PHY_IPhysicsController* CreateConeController(float coneradius,float coneheight); - - - virtual int GetNumContactPoints(); - - virtual void GetContactPoint(int i,float& hitX,float& hitY,float& hitZ,float& normalX,float& normalY,float& normalZ); - - ////////////////////// - //CcdPhysicsEnvironment interface - //////////////////////// - - void AddCcdPhysicsController(CcdPhysicsController* ctrl); - - bool RemoveCcdPhysicsController(CcdPhysicsController* ctrl); - - void UpdateCcdPhysicsController(CcdPhysicsController* ctrl, btScalar newMass, int newCollisionFlags, short int newCollisionGroup, short int newCollisionMask); - - void RefreshCcdPhysicsController(CcdPhysicsController* ctrl); - - bool IsActiveCcdPhysicsController(CcdPhysicsController *ctrl); - - void AddCcdGraphicController(CcdGraphicController* ctrl); - - void RemoveCcdGraphicController(CcdGraphicController* ctrl); - - /** - * Update all physics controllers shape which use the same shape construction info. - * Call RecreateControllerShape on controllers which use the same shape - * construction info that argument shapeInfo. - * You need to call this function when the shape construction info changed. - */ - void UpdateCcdPhysicsControllerShape(CcdShapeConstructionInfo *shapeInfo); - - btBroadphaseInterface* GetBroadphase(); - btDbvtBroadphase* GetCullingTree() { return m_cullingTree; } - - btDispatcher* GetDispatcher(); - - - bool IsSatCollisionDetectionEnabled() const - { - return m_enableSatCollisionDetection; - } - - void EnableSatCollisionDetection(bool enableSat) - { - m_enableSatCollisionDetection = enableSat; - } - - - const btPersistentManifold* GetManifold(int index) const; - - - void SyncMotionStates(float timeStep); - - class btSoftRigidDynamicsWorld* GetDynamicsWorld() - { - return m_dynamicsWorld; - } - - class btConstraintSolver* GetConstraintSolver(); - - void MergeEnvironment(PHY_IPhysicsEnvironment *other_env); - - static CcdPhysicsEnvironment *Create(struct Scene *blenderscene, bool visualizePhysics); - - virtual void ConvertObject(KX_GameObject* gameobj, - RAS_MeshObject* meshobj, - DerivedMesh* dm, - KX_Scene* kxscene, - PHY_ShapeProps* shapeprops, - PHY_MaterialProps* smmaterial, - PHY_IMotionState *motionstate, - int activeLayerBitInfo, - bool isCompoundChild, - bool hasCompoundChildren); - - /* Set the rigid body joints constraints values for converted objects and replicated group instances. */ - virtual void SetupObjectConstraints(KX_GameObject *obj_src, KX_GameObject *obj_dest, - bRigidBodyJointConstraint *dat); - - protected: - - - - std::set m_controllers; - - PHY_ResponseCallback m_triggerCallbacks[PHY_NUM_RESPONSE]; - void* m_triggerCallbacksUserPtrs[PHY_NUM_RESPONSE]; - - std::vector m_wrapperVehicles; - - //use explicit btSoftRigidDynamicsWorld/btDiscreteDynamicsWorld* so that we have access to - //btDiscreteDynamicsWorld::addRigidBody(body,filter,group) - //so that we can set the body collision filter/group at the time of creation - //and not afterwards (breaks the collision system for radar/near sensor) - //Ideally we would like to have access to this function from the btDynamicsWorld interface - //class btDynamicsWorld* m_dynamicsWorld; - class btSoftRigidDynamicsWorld* m_dynamicsWorld; - - class btConstraintSolver* m_solver; - - class btOverlappingPairCache* m_ownPairCache; - - class CcdOverlapFilterCallBack* m_filterCallback; - - class btGhostPairCallback* m_ghostPairCallback; - - class btDispatcher* m_ownDispatcher; - - bool m_scalingPropagated; - - virtual void ExportFile(const char* filename); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:CcdPhysicsEnvironment") -#endif -}; - -#endif /* __CCDPHYSICSENVIRONMENT_H__ */ diff --git a/source/gameengine/Physics/Dummy/CMakeLists.txt b/source/gameengine/Physics/Dummy/CMakeLists.txt deleted file mode 100644 index 692331f1ce4..00000000000 --- a/source/gameengine/Physics/Dummy/CMakeLists.txt +++ /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) 2006, Blender Foundation -# All rights reserved. -# -# The Original Code is: all of this file. -# -# Contributor(s): Jacques Beaurain. -# -# ***** END GPL LICENSE BLOCK ***** - -set(INC - . - ../common -) - -set(INC_SYS - ../../../../intern/moto/include -) - -set(SRC - DummyPhysicsEnvironment.cpp - - DummyPhysicsEnvironment.h -) - -blender_add_lib(ge_phys_dummy "${SRC}" "${INC}" "${INC_SYS}") diff --git a/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.cpp b/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.cpp deleted file mode 100644 index 99db56bfcef..00000000000 --- a/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.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 ***** - */ - -/** \file gameengine/Physics/Dummy/DummyPhysicsEnvironment.cpp - * \ingroup physdummy - */ - - -#include - -#include "DummyPhysicsEnvironment.h" -#include "PHY_IMotionState.h" - -DummyPhysicsEnvironment::DummyPhysicsEnvironment() -{ - // create physicsengine data -} - - - -DummyPhysicsEnvironment::~DummyPhysicsEnvironment() -{ - //destroy physicsengine data -} - -void DummyPhysicsEnvironment::BeginFrame() -{ - // beginning of logic frame: apply forces -} - -void DummyPhysicsEnvironment::EndFrame() -{ - // end of logic frame: clear forces -} - - - -bool DummyPhysicsEnvironment::ProceedDeltaTime(double curTime,float timeStep,float interval) -{ - //step physics simulation, typically perform - - //collision detection - //solve constraints - //integrate solution - // return true if an update was done. - return true; -} -void DummyPhysicsEnvironment::SetFixedTimeStep(bool useFixedTimeStep,float fixedTimeStep) -{ -} - -float DummyPhysicsEnvironment::GetFixedTimeStep() -{ - return 0.f; -} - -int DummyPhysicsEnvironment::GetDebugMode() const -{ - return 0; -} - -void DummyPhysicsEnvironment::SetGravity(float x,float y,float z) -{ -} - -void DummyPhysicsEnvironment::GetGravity(class MT_Vector3& grav) -{ -} - - - - -int DummyPhysicsEnvironment::CreateConstraint(class PHY_IPhysicsController* ctrl,class PHY_IPhysicsController* ctrl2,PHY_ConstraintType type, - float pivotX,float pivotY,float pivotZ,float axisX,float axisY,float axisZ, - float axis1X,float axis1Y,float axis1Z, - float axis2X,float axis2Y,float axis2Z,int flag - ) -{ - - int constraintid = 0; - return constraintid; - -} - -void DummyPhysicsEnvironment::RemoveConstraintById(int constraintid) -{ - if (constraintid) - { - } -} - -PHY_IPhysicsController* DummyPhysicsEnvironment::RayTest(PHY_IRayCastFilterCallback &filterCallback,float fromX,float fromY,float fromZ, float toX,float toY,float toZ) -{ - //collision detection / raytesting - return NULL; -} - diff --git a/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.h b/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.h deleted file mode 100644 index 3e9379dd60d..00000000000 --- a/source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.h +++ /dev/null @@ -1,134 +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 DummyPhysicsEnvironment.h - * \ingroup physdummy - */ - -#ifndef __DUMMYPHYSICSENVIRONMENT_H__ -#define __DUMMYPHYSICSENVIRONMENT_H__ - -#include "PHY_IPhysicsEnvironment.h" -#include "PHY_IMotionState.h" - -/** - * DummyPhysicsEnvironment is an empty placeholder - * Alternatives are ODE,Sumo and Dynamo PhysicsEnvironments - * Use DummyPhysicsEnvironment as a base to integrate your own physics engine - * Physics Environment takes care of stepping the simulation and is a container for physics entities (rigidbodies,constraints, materials etc.) - * - * A derived class may be able to 'construct' entities by loading and/or converting - */ -class DummyPhysicsEnvironment : public PHY_IPhysicsEnvironment -{ - -public: - DummyPhysicsEnvironment (); - virtual ~DummyPhysicsEnvironment (); - virtual void BeginFrame(); - virtual void EndFrame(); -// Perform an integration step of duration 'timeStep'. - virtual bool ProceedDeltaTime(double curTime,float timeStep,float interval); - virtual void SetFixedTimeStep(bool useFixedTimeStep,float fixedTimeStep); - virtual float GetFixedTimeStep(); - - virtual int GetDebugMode() const; - - virtual void SetGravity(float x,float y,float z); - virtual void GetGravity(class MT_Vector3& grav); - - virtual int CreateConstraint(class PHY_IPhysicsController* ctrl,class PHY_IPhysicsController* ctrl2,PHY_ConstraintType type, - float pivotX,float pivotY,float pivotZ, - float axisX,float axisY,float axisZ, - float axis1X=0,float axis1Y=0,float axis1Z=0, - float axis2X=0,float axis2Y=0,float axis2Z=0,int flag=0 - ); - - virtual void RemoveConstraintById(int constraintid); - - //complex constraint for vehicles - virtual PHY_IVehicle* GetVehicleConstraint(int constraintId) - { - return 0; - } - - // Character physics wrapper - virtual PHY_ICharacter* GetCharacterController(class KX_GameObject* ob) - { - return 0; - } - - virtual PHY_IPhysicsController* RayTest(PHY_IRayCastFilterCallback &filterCallback, float fromX,float fromY,float fromZ, float toX,float toY,float toZ); - virtual bool CullingTest(PHY_CullingCallback callback, void* userData, class MT_Vector4* planes, int nplanes, int occlusionRes, const int *viewport, float modelview[16], float projection[16]) { return false; } - - - //gamelogic callbacks - virtual void AddSensor(PHY_IPhysicsController* ctrl) {} - virtual void RemoveSensor(PHY_IPhysicsController* ctrl) {} - virtual void AddTouchCallback(int response_class, PHY_ResponseCallback callback, void *user) - { - } - virtual bool RequestCollisionCallback(PHY_IPhysicsController* ctrl) { return false; } - virtual bool RemoveCollisionCallback(PHY_IPhysicsController* ctrl) { return false;} - virtual PHY_IPhysicsController* CreateSphereController(float radius,const class MT_Vector3& position) {return 0;} - virtual PHY_IPhysicsController* CreateConeController(float coneradius,float coneheight) { return 0;} - - virtual void SetConstraintParam(int constraintId,int param,float value,float value1) - { - } - - virtual float GetConstraintParam(int constraintId,int param) - { - return 0.f; - } - - virtual void MergeEnvironment(PHY_IPhysicsEnvironment *other_env) - { - // Dummy, nothing to do here - } - - virtual void ConvertObject(KX_GameObject* gameobj, - RAS_MeshObject* meshobj, - DerivedMesh* dm, - KX_Scene* kxscene, - PHY_ShapeProps* shapeprops, - PHY_MaterialProps* smmaterial, - PHY_IMotionState *motionstate, - int activeLayerBitInfo, - bool isCompoundChild, - bool hasCompoundChildren) - { - // All we need to do is handle the motionstate (we're supposed to own it) - delete motionstate; - } - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:DummyPhysicsEnvironment") -#endif -}; - -#endif /* __DUMMYPHYSICSENVIRONMENT_H__ */ diff --git a/source/gameengine/Physics/common/PHY_DynamicTypes.h b/source/gameengine/Physics/common/PHY_DynamicTypes.h deleted file mode 100644 index d10f48ad7a4..00000000000 --- a/source/gameengine/Physics/common/PHY_DynamicTypes.h +++ /dev/null @@ -1,91 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -/** \file PHY_DynamicTypes.h - * \ingroup phys - */ - -#ifndef __PHY_DYNAMICTYPES_H__ -#define __PHY_DYNAMICTYPES_H__ - -#include "MT_Vector3.h" - -struct KX_ClientObjectInfo; - -enum -{ - PHY_FH_RESPONSE, - PHY_SENSOR_RESPONSE, /* Touch Sensors */ - PHY_CAMERA_RESPONSE, /* Visibility Culling */ - PHY_OBJECT_RESPONSE, /* Object Dynamic Geometry Response */ - PHY_STATIC_RESPONSE, /* Static Geometry Response */ - PHY_BROADPH_RESPONSE, /* broadphase Response */ - - PHY_NUM_RESPONSE -}; - -typedef struct PHY_CollData { - MT_Vector3 m_point1; /* Point in object1 in world coordinates */ - MT_Vector3 m_point2; /* Point in object2 in world coordinates */ - MT_Vector3 m_normal; /* point2 - point1 */ -} PHY_CollData; - - -typedef bool (*PHY_ResponseCallback)(void *client_data, - void *client_object1, - void *client_object2, - const PHY_CollData *coll_data); -typedef void (*PHY_CullingCallback)(KX_ClientObjectInfo* info, void* param); - - -/// PHY_PhysicsType enumerates all possible Physics Entities. -/// It is mainly used to create/add Physics Objects - -typedef enum PHY_PhysicsType { - PHY_CONVEX_RIGIDBODY=16386, - PHY_CONCAVE_RIGIDBODY=16399, - PHY_CONVEX_FIXEDBODY=16388,//'collision object' - PHY_CONCAVE_FIXEDBODY=16401, - PHY_CONVEX_KINEMATICBODY=16387,// - PHY_CONCAVE_KINEMATICBODY=16400, - PHY_CONVEX_PHANTOMBODY=16398, - PHY_CONCAVE_PHANTOMBODY=16402 -} PHY_PhysicsType; - -/// PHY_ConstraintType enumerates all supported Constraint Types -typedef enum PHY_ConstraintType { - PHY_POINT2POINT_CONSTRAINT=1, - PHY_LINEHINGE_CONSTRAINT=2, - PHY_ANGULAR_CONSTRAINT = 3,//hinge without ball socket - PHY_CONE_TWIST_CONSTRAINT = 4, - PHY_VEHICLE_CONSTRAINT=11,//complex 'constraint' that turns a rigidbody into a vehicle - PHY_GENERIC_6DOF_CONSTRAINT=12,//can leave any of the 6 degree of freedom 'free' or 'locked' - -} PHY_ConstraintType; - -typedef enum PHY_ShapeType { - PHY_SHAPE_NONE, - PHY_SHAPE_BOX, - PHY_SHAPE_SPHERE, - PHY_SHAPE_CYLINDER, - PHY_SHAPE_CONE, - PHY_SHAPE_CAPSULE, - PHY_SHAPE_MESH, - PHY_SHAPE_POLYTOPE, - PHY_SHAPE_COMPOUND, - PHY_SHAPE_PROXY -} PHY_ShapeType; - -#endif /* __PHY_DYNAMICTYPES_H__ */ diff --git a/source/gameengine/Physics/common/PHY_ICharacter.h b/source/gameengine/Physics/common/PHY_ICharacter.h deleted file mode 100644 index 1a924904b7d..00000000000 --- a/source/gameengine/Physics/common/PHY_ICharacter.h +++ /dev/null @@ -1,39 +0,0 @@ - -/** \file PHY_ICharacter.h - * \ingroup phys - */ - -#ifndef __PHY_ICHARACTER_H__ -#define __PHY_ICHARACTER_H__ - -//PHY_ICharacter provides a generic interface for "character" controllers - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -class PHY_ICharacter -{ -public: - virtual ~PHY_ICharacter() {}; - - virtual void Jump()= 0; - virtual bool OnGround()= 0; - - virtual float GetGravity()= 0; - virtual void SetGravity(float gravity)= 0; - - virtual unsigned char GetMaxJumps() = 0; - virtual void SetMaxJumps(unsigned char maxJumps) = 0; - - virtual unsigned char GetJumpCount() = 0; - - virtual void SetWalkDirection(const class MT_Vector3& dir)=0; - virtual MT_Vector3 GetWalkDirection()=0; - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:PHY_ICharacter") -#endif -}; - -#endif //__PHY_ICHARACTER_H__ diff --git a/source/gameengine/Physics/common/PHY_IController.h b/source/gameengine/Physics/common/PHY_IController.h deleted file mode 100644 index 741fae8d2ad..00000000000 --- a/source/gameengine/Physics/common/PHY_IController.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 PHY_IController.h - * \ingroup phys - */ - -#ifndef __PHY_ICONTROLLER_H__ -#define __PHY_ICONTROLLER_H__ - -#include "PHY_DynamicTypes.h" - -class PHY_IPhysicsEnvironment; - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -/** - * PHY_IController is the abstract simplified Interface to objects - * controlled by the physics engine. This includes the physics objects - * and the graphics object for view frustrum and occlusion culling. - */ -class PHY_IController -{ - public: - virtual ~PHY_IController() {}; - // clientinfo for raycasts for example - virtual void* GetNewClientInfo()=0; - virtual void SetNewClientInfo(void* clientinfo)=0; - virtual void SetPhysicsEnvironment(class PHY_IPhysicsEnvironment *env)=0; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:PHY_IController") -#endif -}; - -#endif /* __PHY_ICONTROLLER_H__ */ diff --git a/source/gameengine/Physics/common/PHY_IGraphicController.h b/source/gameengine/Physics/common/PHY_IGraphicController.h deleted file mode 100644 index b047edd93eb..00000000000 --- a/source/gameengine/Physics/common/PHY_IGraphicController.h +++ /dev/null @@ -1,60 +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 PHY_IGraphicController.h - * \ingroup phys - */ - -#ifndef __PHY_IGRAPHICCONTROLLER_H__ -#define __PHY_IGRAPHICCONTROLLER_H__ - -#include "PHY_IController.h" - - -/** - * PHY_IPhysicsController is the abstract simplified Interface to a physical object. - * It contains the IMotionState and IDeformableMesh Interfaces. - */ -class PHY_IGraphicController : public PHY_IController -{ - public: - /** - * SynchronizeMotionStates ynchronizes dynas, kinematic and deformable entities (and do 'late binding') - */ - virtual bool SetGraphicTransform()=0; - virtual void Activate(bool active=true)=0; - virtual void SetLocalAabb(const class MT_Vector3& aabbMin,const class MT_Vector3& aabbMax)=0; - virtual void SetLocalAabb(const float* aabbMin,const float* aabbMax)=0; - - virtual PHY_IGraphicController* GetReplica(class PHY_IMotionState* motionstate) {return 0;} - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:PHY_IController") -#endif -}; - -#endif /* __PHY_IGRAPHICCONTROLLER_H__ */ diff --git a/source/gameengine/Physics/common/PHY_IMotionState.h b/source/gameengine/Physics/common/PHY_IMotionState.h deleted file mode 100644 index e803d658713..00000000000 --- a/source/gameengine/Physics/common/PHY_IMotionState.h +++ /dev/null @@ -1,68 +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 PHY_IMotionState.h - * \ingroup phys - */ - -#ifndef __PHY_IMOTIONSTATE_H__ -#define __PHY_IMOTIONSTATE_H__ - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -/** - * PHY_IMotionState is the Interface to explicitly synchronize the world transformation. - * Default implementations for mayor graphics libraries like OpenGL and DirectX can be provided. - */ -class PHY_IMotionState - -{ - public: - virtual ~PHY_IMotionState() {}; - - virtual void GetWorldPosition(float& posX,float& posY,float& posZ)=0; - virtual void GetWorldScaling(float& scaleX,float& scaleY,float& scaleZ)=0; - virtual void GetWorldOrientation(float& quatIma0,float& quatIma1,float& quatIma2,float& quatReal)=0; - // ori = array 12 floats, [0..3] = first column + 0, [4..7] = second column, [8..11] = third column - virtual void GetWorldOrientation(float* ori)=0; - virtual void SetWorldOrientation(const float* ori)=0; - - virtual void SetWorldPosition(float posX,float posY,float posZ)=0; - virtual void SetWorldOrientation(float quatIma0,float quatIma1,float quatIma2,float quatReal)=0; - - - virtual void CalculateWorldTransformations()=0; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:PHY_IMotionState") -#endif -}; - -#endif /* __PHY_IMOTIONSTATE_H__ */ diff --git a/source/gameengine/Physics/common/PHY_IPhysicsController.h b/source/gameengine/Physics/common/PHY_IPhysicsController.h deleted file mode 100644 index 4c6e8c71ef7..00000000000 --- a/source/gameengine/Physics/common/PHY_IPhysicsController.h +++ /dev/null @@ -1,154 +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 PHY_IPhysicsController.h - * \ingroup phys - */ - -#ifndef __PHY_IPHYSICSCONTROLLER_H__ -#define __PHY_IPHYSICSCONTROLLER_H__ - -#include -#include "PHY_IController.h" - -class PHY_IMotionState; -class PHY_IPhysicsEnvironment; - -class MT_Vector3; -class MT_Point3; -class MT_Matrix3x3; - -class KX_GameObject; -class RAS_MeshObject; - -/** - * PHY_IPhysicsController is the abstract simplified Interface to a physical object. - * It contains the IMotionState and IDeformableMesh Interfaces. - */ -class PHY_IPhysicsController : public PHY_IController -{ - - public: - virtual ~PHY_IPhysicsController() {}; - /** - * SynchronizeMotionStates ynchronizes dynas, kinematic and deformable entities (and do 'late binding') - */ - virtual bool SynchronizeMotionStates(float time)=0; - /** - * WriteMotionStateToDynamics ynchronizes dynas, kinematic and deformable entities (and do 'late binding') - */ - - virtual void WriteMotionStateToDynamics(bool nondynaonly)=0; - virtual void WriteDynamicsToMotionState()=0; - virtual class PHY_IMotionState* GetMotionState() = 0; - // controller replication - virtual void PostProcessReplica(class PHY_IMotionState* motionstate,class PHY_IPhysicsController* parentctrl)=0; - virtual void SetPhysicsEnvironment(class PHY_IPhysicsEnvironment *env)=0; - - // kinematic methods - virtual void RelativeTranslate(const MT_Vector3& dloc,bool local)=0; - virtual void RelativeRotate(const MT_Matrix3x3&,bool local)=0; - virtual MT_Matrix3x3 GetOrientation()=0; - virtual void SetOrientation(const MT_Matrix3x3& orn)=0; - virtual void SetPosition(const MT_Vector3& pos)=0; - virtual void GetPosition(MT_Vector3& pos) const=0; - virtual void SetScaling(const MT_Vector3& scale)=0; - virtual void SetTransform()=0; - - virtual MT_Scalar GetMass()=0; - virtual void SetMass(MT_Scalar newmass)=0; - - // physics methods - virtual void ApplyImpulse(const MT_Point3& attach, const MT_Vector3& impulse,bool local)=0; - virtual void ApplyTorque(const MT_Vector3& torque,bool local)=0; - virtual void ApplyForce(const MT_Vector3& force,bool local)=0; - virtual void SetAngularVelocity(const MT_Vector3& ang_vel,bool local)=0; - virtual void SetLinearVelocity(const MT_Vector3& lin_vel,bool local)=0; - virtual void ResolveCombinedVelocities(float linvelX,float linvelY,float linvelZ,float angVelX,float angVelY,float angVelZ) = 0; - - virtual float GetLinearDamping() const=0; - virtual float GetAngularDamping() const=0; - virtual void SetLinearDamping(float damping)=0; - virtual void SetAngularDamping(float damping)=0; - virtual void SetDamping(float linear, float angular)=0; - - virtual void RefreshCollisions() = 0; - virtual void SuspendDynamics(bool ghost=false)=0; - virtual void RestoreDynamics()=0; - - virtual void SetActive(bool active)=0; - - // reading out information from physics - virtual MT_Vector3 GetLinearVelocity()=0; - virtual MT_Vector3 GetAngularVelocity()=0; - virtual MT_Vector3 GetVelocity(const MT_Point3& pos)=0; - virtual MT_Vector3 GetLocalInertia()=0; - - // dyna's that are rigidbody are free in orientation, dyna's with non-rigidbody are restricted - virtual void SetRigidBody(bool rigid)=0; - - virtual PHY_IPhysicsController* GetReplica() {return 0;} - virtual PHY_IPhysicsController* GetReplicaForSensors() {return 0;} - - virtual void CalcXform() =0; - virtual void SetMargin(float margin) =0; - virtual float GetMargin() const=0; - virtual float GetRadius() const=0; - virtual void SetRadius(float margin) = 0; - - virtual float GetLinVelocityMin() const=0; - virtual void SetLinVelocityMin(float val) = 0; - virtual float GetLinVelocityMax() const=0; - virtual void SetLinVelocityMax(float val) = 0; - - virtual void SetAngularVelocityMin(float val) = 0; - virtual float GetAngularVelocityMin() const = 0; - virtual void SetAngularVelocityMax(float val) = 0; - virtual float GetAngularVelocityMax() const = 0; - - MT_Vector3 GetWorldPosition(MT_Vector3& localpos); - - // Shape control - virtual void AddCompoundChild(PHY_IPhysicsController* child) = 0; - virtual void RemoveCompoundChild(PHY_IPhysicsController* child) = 0; - - - virtual bool IsDynamic() = 0; - virtual bool IsCompound() = 0; - virtual bool IsSuspended() const = 0; - - virtual bool ReinstancePhysicsShape(KX_GameObject *from_gameobj, RAS_MeshObject* from_meshobj) = 0; - - /* Method to replicate rigid body joint contraints for group instances. */ - virtual void ReplicateConstraints(KX_GameObject *gameobj, std::vector constobj) = 0; - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:PHY_IPhysicsController") -#endif -}; - -#endif /* __PHY_IPHYSICSCONTROLLER_H__ */ diff --git a/source/gameengine/Physics/common/PHY_IPhysicsEnvironment.h b/source/gameengine/Physics/common/PHY_IPhysicsEnvironment.h deleted file mode 100644 index 72ec7b1edd0..00000000000 --- a/source/gameengine/Physics/common/PHY_IPhysicsEnvironment.h +++ /dev/null @@ -1,226 +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 PHY_IPhysicsEnvironment.h - * \ingroup phys - */ - -#ifndef __PHY_IPHYSICSENVIRONMENT_H__ -#define __PHY_IPHYSICSENVIRONMENT_H__ - -#include "PHY_DynamicTypes.h" -#include "MT_Vector2.h" -#include "MT_Vector3.h" -#include "MT_Vector4.h" - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -class PHY_IVehicle; -class PHY_ICharacter; -class RAS_MeshObject; -class PHY_IPhysicsController; - - -class RAS_MeshObject; -struct DerivedMesh; -class KX_GameObject; -class KX_Scene; - -struct PHY_ShapeProps; -struct PHY_MaterialProps; -class PHY_IMotionState; -struct bRigidBodyJointConstraint; - -/** - * pass back information from rayTest - */ -struct PHY_RayCastResult -{ - PHY_IPhysicsController* m_controller; - MT_Vector3 m_hitPoint; - MT_Vector3 m_hitNormal; - const RAS_MeshObject* m_meshObject; // !=NULL for mesh object (only for Bullet controllers) - int m_polygon; // index of the polygon hit by the ray, - // only if m_meshObject != NULL - int m_hitUVOK; // !=0 if UV coordinate in m_hitUV is valid - MT_Vector2 m_hitUV; // UV coordinates of hit point -}; - -/** - * This class replaces the ignoreController parameter of rayTest function. - * It allows more sophisticated filtering on the physics controller before computing the ray intersection to save CPU. - * It is only used to its full extend by the Ccd physics environment (Bullet). - */ -class PHY_IRayCastFilterCallback -{ -public: - PHY_IPhysicsController* m_ignoreController; - bool m_faceNormal; - bool m_faceUV; - - virtual ~PHY_IRayCastFilterCallback() - { - } - - virtual bool needBroadphaseRayCast(PHY_IPhysicsController* controller) - { - return true; - } - - virtual void reportHit(PHY_RayCastResult* result) = 0; - - PHY_IRayCastFilterCallback(PHY_IPhysicsController* ignoreController, bool faceNormal=false, bool faceUV=false) - :m_ignoreController(ignoreController), - m_faceNormal(faceNormal), - m_faceUV(faceUV) - { - } - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:PHY_IRayCastFilterCallback") -#endif -}; - -/** - * Physics Environment takes care of stepping the simulation and is a container for physics entities - * (rigidbodies,constraints, materials etc.) - * A derived class may be able to 'construct' entities by loading and/or converting - */ -class PHY_IPhysicsEnvironment -{ - public: - virtual ~PHY_IPhysicsEnvironment() {} - virtual void BeginFrame() = 0; - virtual void EndFrame() = 0; - /// Perform an integration step of duration 'timeStep'. - virtual bool ProceedDeltaTime(double curTime,float timeStep,float interval)=0; - ///draw debug lines (make sure to call this during the render phase, otherwise lines are not drawn properly) - virtual void DebugDrawWorld() {} - virtual void SetFixedTimeStep(bool useFixedTimeStep,float fixedTimeStep)=0; - //returns 0.f if no fixed timestep is used - virtual float GetFixedTimeStep()=0; - - ///getDebugMode return the actual debug visualization state - virtual int GetDebugMode()const=0; - ///setDebugMode is used to support several ways of debug lines, contact point visualization - virtual void SetDebugMode(int debugMode) {} - ///setNumIterations set the number of iterations for iterative solvers - virtual void SetNumIterations(int numIter) {} - ///setNumTimeSubSteps set the number of divisions of the timestep. Tradeoff quality versus performance. - virtual void SetNumTimeSubSteps(int numTimeSubSteps) {} - virtual int GetNumTimeSubSteps() {return 0; } - ///setDeactivationTime sets the minimum time that an objects has to stay within the velocity tresholds until it gets fully deactivated - virtual void SetDeactivationTime(float dTime) {} - ///setDeactivationLinearTreshold sets the linear velocity treshold, see setDeactivationTime - virtual void SetDeactivationLinearTreshold(float linTresh) {} - ///setDeactivationAngularTreshold sets the angular velocity treshold, see setDeactivationTime - virtual void SetDeactivationAngularTreshold(float angTresh) {} - ///setContactBreakingTreshold sets tresholds to do with contact point management - virtual void SetContactBreakingTreshold(float contactBreakingTreshold) {} - ///continuous collision detection mode, very experimental for Bullet - virtual void SetCcdMode(int ccdMode) {} - ///successive overrelaxation constant, in case PSOR is used, values in between 1 and 2 guarantee converging behavior - virtual void SetSolverSorConstant(float sor) {} - ///setSolverType, internal setting, chooses solvertype, PSOR, Dantzig, impulse based, penalty based - virtual void SetSolverType(int solverType) {} - ///setTau sets the spring constant of a penalty based solver - virtual void SetSolverTau(float tau) {} - ///setDamping sets the damper constant of a penalty based solver - virtual void SetSolverDamping(float damping) {} - ///linear air damping for rigidbodies - virtual void SetLinearAirDamping(float damping) {} - /// penetrationdepth setting - virtual void SetUseEpa(bool epa) {} - - virtual void SetGravity(float x,float y,float z)=0; - virtual void GetGravity(MT_Vector3& grav) = 0; - - virtual int CreateConstraint(class PHY_IPhysicsController* ctrl,class PHY_IPhysicsController* ctrl2,PHY_ConstraintType type, - float pivotX,float pivotY,float pivotZ, - float axis0X,float axis0Y,float axis0Z, - float axis1X=0,float axis1Y=0,float axis1Z=0, - float axis2X=0,float axis2Y=0,float axis2Z=0,int flag=0 - )=0; - virtual void RemoveConstraintById(int constraintid) = 0; - virtual float GetAppliedImpulse(int constraintid) { return 0.0f; } - - - //complex constraint for vehicles - virtual PHY_IVehicle* GetVehicleConstraint(int constraintId) =0; - - // Character physics wrapper - virtual PHY_ICharacter* GetCharacterController(class KX_GameObject* ob) =0; - - virtual PHY_IPhysicsController* RayTest(PHY_IRayCastFilterCallback &filterCallback, float fromX,float fromY,float fromZ, float toX,float toY,float toZ)=0; - - //culling based on physical broad phase - // the plane number must be set as follow: near, far, left, right, top, botton - // the near plane must be the first one and must always be present, it is used to get the direction of the view - virtual bool CullingTest(PHY_CullingCallback callback, void *userData, MT_Vector4* planeNormals, int planeNumber, int occlusionRes, const int *viewport, float modelview[16], float projection[16]) = 0; - - //Methods for gamelogic collision/physics callbacks - //todo: - virtual void AddSensor(PHY_IPhysicsController* ctrl)=0; - virtual void RemoveSensor(PHY_IPhysicsController* ctrl)=0; - virtual void AddTouchCallback(int response_class, PHY_ResponseCallback callback, void *user)=0; - virtual bool RequestCollisionCallback(PHY_IPhysicsController* ctrl)=0; - virtual bool RemoveCollisionCallback(PHY_IPhysicsController* ctrl)=0; - //These two methods are *solely* used to create controllers for sensor! Don't use for anything else - virtual PHY_IPhysicsController* CreateSphereController(float radius,const MT_Vector3& position) =0; - virtual PHY_IPhysicsController* CreateConeController(float coneradius,float coneheight)=0; - - virtual void SetConstraintParam(int constraintId,int param,float value,float value1) = 0; - virtual float GetConstraintParam(int constraintId,int param) = 0; - - virtual void ExportFile(const char* filename) {}; - - virtual void MergeEnvironment(PHY_IPhysicsEnvironment *other_env) = 0; - - virtual void ConvertObject(KX_GameObject* gameobj, - RAS_MeshObject* meshobj, - DerivedMesh* dm, - KX_Scene* kxscene, - PHY_ShapeProps* shapeprops, - PHY_MaterialProps* smmaterial, - PHY_IMotionState *motionstate, - int activeLayerBitInfo, - bool isCompoundChild, - bool hasCompoundChildren) = 0; - - /* Set the rigid body joints constraints values for converted objects and replicated group instances. */ - virtual void SetupObjectConstraints(KX_GameObject *obj_src, KX_GameObject *obj_dest, - bRigidBodyJointConstraint *dat) {} - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:PHY_IPhysicsEnvironment") -#endif -}; - -#endif /* __PHY_IPHYSICSENVIRONMENT_H__ */ diff --git a/source/gameengine/Physics/common/PHY_IVehicle.h b/source/gameengine/Physics/common/PHY_IVehicle.h deleted file mode 100644 index 7e4a49e923e..00000000000 --- a/source/gameengine/Physics/common/PHY_IVehicle.h +++ /dev/null @@ -1,69 +0,0 @@ - -/** \file PHY_IVehicle.h - * \ingroup phys - */ - -#ifndef __PHY_IVEHICLE_H__ -#define __PHY_IVEHICLE_H__ - -//PHY_IVehicle provides a generic interface for (raycast based) vehicles. Mostly targetting 4 wheel cars and 2 wheel motorbikes. - -class PHY_IMotionState; -#include "PHY_DynamicTypes.h" - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -class PHY_IVehicle -{ -public: - virtual ~PHY_IVehicle() {}; - - virtual void AddWheel( - PHY_IMotionState* motionState, - MT_Vector3 connectionPoint, - MT_Vector3 downDirection, - MT_Vector3 axleDirection, - float suspensionRestLength, - float wheelRadius, - bool hasSteering - ) = 0; - - - virtual int GetNumWheels() const = 0; - - virtual void GetWheelPosition(int wheelIndex,float& posX,float& posY,float& posZ) const = 0; - virtual void GetWheelOrientationQuaternion(int wheelIndex,float& quatX,float& quatY,float& quatZ,float& quatW) const = 0; - virtual float GetWheelRotation(int wheelIndex) const = 0; - - virtual int GetUserConstraintId() const =0; - virtual int GetUserConstraintType() const =0; - - //some basic steering/braking/tuning/balancing (bikes) - - virtual void SetSteeringValue(float steering,int wheelIndex) = 0; - - virtual void ApplyEngineForce(float force,int wheelIndex) = 0; - - virtual void ApplyBraking(float braking,int wheelIndex) = 0; - - virtual void SetWheelFriction(float friction,int wheelIndex) = 0; - - virtual void SetSuspensionStiffness(float suspensionStiffness,int wheelIndex) = 0; - - virtual void SetSuspensionDamping(float suspensionStiffness,int wheelIndex) = 0; - - virtual void SetSuspensionCompression(float suspensionStiffness,int wheelIndex) = 0; - - virtual void SetRollInfluence(float rollInfluence,int wheelIndex) = 0; - - virtual void SetCoordinateSystem(int rightIndex,int upIndex,int forwardIndex) =0; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:PHY_IVehicle") -#endif -}; - -#endif /* __PHY_IVEHICLE_H__ */ diff --git a/source/gameengine/Physics/common/PHY_Pro.h b/source/gameengine/Physics/common/PHY_Pro.h deleted file mode 100644 index bfe574e73cb..00000000000 --- a/source/gameengine/Physics/common/PHY_Pro.h +++ /dev/null @@ -1,68 +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 PHY_Pro.h - * \ingroup phys - */ - -#ifndef __PHY_PRO_H__ -#define __PHY_PRO_H__ - -#include - -// Properties of dynamic objects -struct PHY_ShapeProps { - MT_Scalar m_mass; // Total mass - MT_Scalar m_inertia; // Inertia, should be a tensor some time - MT_Scalar m_lin_drag; // Linear drag (air, water) 0 = concrete, 1 = vacuum, inverted and called dampening in blenders UI - MT_Scalar m_ang_drag; // Angular drag, inverted and called dampening in blenders UI - MT_Scalar m_friction_scaling[3]; // Scaling for anisotropic friction. Component in range [0, 1] - MT_Scalar m_clamp_vel_min; // Clamp the minimum velocity, this ensures an object moves at a minimum speed unless its stationary - MT_Scalar m_clamp_vel_max; // Clamp max velocity - MT_Scalar m_clamp_angvel_min; // Clamp the minimum angular velocity. - MT_Scalar m_clamp_angvel_max; // Clamp the maximum angular velocity. - bool m_do_anisotropic; // Should I do anisotropic friction? - bool m_do_fh; // Should the object have a linear Fh spring? - bool m_do_rot_fh; // Should the object have an angular Fh spring? - MT_Scalar m_step_height; // Max height of climbable steps (Character) - MT_Scalar m_jump_speed; // Velocity of jumps (Character) - MT_Scalar m_fall_speed; // Max velocity of falling (Character) - unsigned char m_max_jumps; // Max ammount of jumps (Character) -}; - - -// Properties of collidable objects (non-ghost objects) -struct PHY_MaterialProps { - MT_Scalar m_restitution; // restitution of energie after a collision 0 = inelastic, 1 = elastic - MT_Scalar m_friction; // Coulomb friction (= ratio between the normal en maximum friction force) - MT_Scalar m_fh_spring; // Spring constant (both linear and angular) - MT_Scalar m_fh_damping; // Damping factor (linear and angular) in range [0, 1] - MT_Scalar m_fh_distance; // The range above the surface where Fh is active. - bool m_fh_normal; // Should the object slide off slopes? -}; - -#endif /* __PHY_PRO_H__ */ diff --git a/source/gameengine/Rasterizer/CMakeLists.txt b/source/gameengine/Rasterizer/CMakeLists.txt deleted file mode 100644 index fc7dc90e03b..00000000000 --- a/source/gameengine/Rasterizer/CMakeLists.txt +++ /dev/null @@ -1,92 +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 - ../Ketsji - ../SceneGraph - ../../blender/makesdna - ../../blender/blenlib - ../../blender/blenkernel - ../../blender/gpu - ../../blender/imbuf - ../../../intern/container - ../../../intern/glew-mx - ../../../intern/guardedalloc - ../../../intern/string -) - -set(INC_SYS - ../../../intern/moto/include - ${GLEW_INCLUDE_PATH} - ${PYTHON_INCLUDE_DIRS} -) - -set(SRC - RAS_2DFilterManager.cpp - RAS_BucketManager.cpp - RAS_FramingManager.cpp - RAS_IPolygonMaterial.cpp - RAS_MaterialBucket.cpp - RAS_MeshObject.cpp - RAS_Polygon.cpp - RAS_TexVert.cpp - RAS_texmatrix.cpp - RAS_ICanvas.cpp - - RAS_2DFilterManager.h - RAS_BucketManager.h - RAS_CameraData.h - RAS_Deformer.h - RAS_FramingManager.h - RAS_ICanvas.h - RAS_IPolygonMaterial.h - RAS_IRasterizer.h - RAS_ILightObject.h - RAS_IOffScreen.h - RAS_ISync.h - RAS_MaterialBucket.h - RAS_MeshObject.h - RAS_ObjectColor.h - RAS_Polygon.h - RAS_Rect.h - RAS_TexMatrix.h - RAS_TexVert.h - RAS_OpenGLFilters/RAS_Blur2DFilter.h - RAS_OpenGLFilters/RAS_Dilation2DFilter.h - RAS_OpenGLFilters/RAS_Erosion2DFilter.h - RAS_OpenGLFilters/RAS_GrayScale2DFilter.h - RAS_OpenGLFilters/RAS_Invert2DFilter.h - RAS_OpenGLFilters/RAS_Laplacian2DFilter.h - RAS_OpenGLFilters/RAS_Prewitt2DFilter.h - RAS_OpenGLFilters/RAS_Sepia2DFilter.h - RAS_OpenGLFilters/RAS_Sharpen2DFilter.h - RAS_OpenGLFilters/RAS_Sobel2DFilter.h -) - -add_definitions(${GL_DEFINITIONS}) - -blender_add_lib(ge_rasterizer "${SRC}" "${INC}" "${INC_SYS}") diff --git a/source/gameengine/Rasterizer/RAS_2DFilterManager.cpp b/source/gameengine/Rasterizer/RAS_2DFilterManager.cpp deleted file mode 100644 index f379e2eb486..00000000000 --- a/source/gameengine/Rasterizer/RAS_2DFilterManager.cpp +++ /dev/null @@ -1,562 +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/Rasterizer/RAS_2DFilterManager.cpp - * \ingroup bgerast - */ - -#include "BLI_utildefines.h" - -#include "RAS_OpenGLFilters/RAS_Blur2DFilter.h" -#include "RAS_OpenGLFilters/RAS_Sharpen2DFilter.h" -#include "RAS_OpenGLFilters/RAS_Dilation2DFilter.h" -#include "RAS_OpenGLFilters/RAS_Erosion2DFilter.h" -#include "RAS_OpenGLFilters/RAS_Laplacian2DFilter.h" -#include "RAS_OpenGLFilters/RAS_Sobel2DFilter.h" -#include "RAS_OpenGLFilters/RAS_Prewitt2DFilter.h" -#include "RAS_OpenGLFilters/RAS_GrayScale2DFilter.h" -#include "RAS_OpenGLFilters/RAS_Sepia2DFilter.h" -#include "RAS_OpenGLFilters/RAS_Invert2DFilter.h" - -#include "STR_String.h" -#include "RAS_ICanvas.h" -#include "RAS_Rect.h" -#include "RAS_2DFilterManager.h" -#include - -#include "GPU_glew.h" - -#include - -#include "EXP_Value.h" - -RAS_2DFilterManager::RAS_2DFilterManager(): -texturewidth(-1), textureheight(-1), -/* numberoffilters(0), */ /* UNUSED */ need_tex_update(true) -{ - isshadersupported = GLEW_ARB_shader_objects && - GLEW_ARB_fragment_shader && GLEW_ARB_multitexture; - - /* used to return before 2.49 but need to initialize values so don't */ - if (!isshadersupported) - std::cout<<"shaders not supported!" << std::endl; - - int passindex; - for (passindex =0; passindex& propNames) -{ - texflag[passindex] = 0; - if (glGetUniformLocationARB(m_filters[passindex], "bgl_DepthTexture") != -1) - { - if (GLEW_ARB_depth_texture) - texflag[passindex] |= 0x1; - } - if (glGetUniformLocationARB(m_filters[passindex], "bgl_LuminanceTexture") != -1) - { - texflag[passindex] |= 0x2; - } - - if (m_gameObjects[passindex]) - { - int objProperties = propNames.size(); - int i; - for (i=0; iGetProperty(m_properties[passindex][i]); - - if (!property) - continue; - - switch (property->GetValueType()) { - case VALUE_INT_TYPE: - glUniform1iARB(uniformLoc, property->GetNumber()); - break; - case VALUE_FLOAT_TYPE: - glUniform1fARB(uniformLoc, property->GetNumber()); - break; - default: - break; - } - } -} - -void RAS_2DFilterManager::EndShaderProgram() -{ - glUseProgramObjectARB(0); -} - -void RAS_2DFilterManager::FreeTextures() -{ - if (texname[0]!=(unsigned int)-1) - glDeleteTextures(1, (GLuint*)&texname[0]); - if (texname[1]!=(unsigned int)-1) - glDeleteTextures(1, (GLuint*)&texname[1]); - if (texname[2]!=(unsigned int)-1) - glDeleteTextures(1, (GLuint*)&texname[2]); -} - -void RAS_2DFilterManager::SetupTextures(bool depth, bool luminance) -{ - FreeTextures(); - - glGenTextures(1, (GLuint*)&texname[0]); - glBindTexture(GL_TEXTURE_2D, texname[0]); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texturewidth, textureheight, 0, GL_RGBA, - GL_UNSIGNED_BYTE, 0); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); - - if (depth) { - glGenTextures(1, (GLuint*)&texname[1]); - glBindTexture(GL_TEXTURE_2D, texname[1]); - glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, texturewidth,textureheight, - 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE,NULL); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, - GL_NONE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); - } - - if (luminance) { - glGenTextures(1, (GLuint*)&texname[2]); - glBindTexture(GL_TEXTURE_2D, texname[2]); - glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE16, texturewidth, textureheight, - 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, 0); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); - } -} - -void RAS_2DFilterManager::UpdateOffsetMatrix(RAS_ICanvas* canvas) -{ - /* RAS_Rect canvas_rect = canvas->GetWindowArea(); */ /* UNUSED */ - texturewidth = canvas->GetWidth()+1; - textureheight = canvas->GetHeight()+1; - GLint i,j; - - if (!GL_ARB_texture_non_power_of_two) - { - i = 0; - while ((1 << i) <= texturewidth) - i++; - texturewidth = (1 << (i)); - - // Now for height - i = 0; - while ((1 << i) <= textureheight) - i++; - textureheight = (1 << (i)); - } - - GLfloat xInc = 1.0f / (GLfloat)texturewidth; - GLfloat yInc = 1.0f / (GLfloat)textureheight; - - for (i = 0; i < 3; i++) - { - for (j = 0; j < 3; j++) - { - textureoffsets[(((i*3)+j)*2)+0] = (-1.0f * xInc) + ((GLfloat)i * xInc); - textureoffsets[(((i*3)+j)*2)+1] = (-1.0f * yInc) + ((GLfloat)j * yInc); - } - } -} - -void RAS_2DFilterManager::UpdateCanvasTextureCoord(const int viewport[4]) -{ - /* - * This function update canvascoord[]. - * These parameters are used to create texcoord[1] - * That way we can access the texcoord relative to the canvas: - * (0.0,0.0) bottom left, (1.0,1.0) top right, (0.5,0.5) center - */ - canvascoord[0] = (GLfloat) viewport[0] / -viewport[2]; - canvascoord[1] = (GLfloat) (texturewidth - viewport[0]) / viewport[2]; - - canvascoord[2] = (GLfloat) viewport[1] / -viewport[3]; - canvascoord[3] = (GLfloat)(textureheight - viewport[1]) / viewport[3]; -} - -void RAS_2DFilterManager::RenderFilters(RAS_ICanvas* canvas) -{ - bool need_depth=false; - bool need_luminance=false; - int num_filters = 0; - - int passindex; - - if (!isshadersupported) - return; - - for (passindex =0; passindexGetViewPort(); - - if (texturewidth != viewport[2] || textureheight != viewport[3]) - { - UpdateOffsetMatrix(canvas); - UpdateCanvasTextureCoord(viewport); - need_tex_update = true; - } - - if (need_tex_update) - { - SetupTextures(need_depth, need_luminance); - need_tex_update = false; - } - - if (need_depth) { - glActiveTextureARB(GL_TEXTURE1); - glBindTexture(GL_TEXTURE_2D, texname[1]); - glCopyTexImage2D(GL_TEXTURE_2D,0,GL_DEPTH_COMPONENT, viewport[0], viewport[1], viewport[2], viewport[3], 0); - } - - if (need_luminance) { - glActiveTextureARB(GL_TEXTURE2); - glBindTexture(GL_TEXTURE_2D, texname[2]); - glCopyTexImage2D(GL_TEXTURE_2D,0,GL_LUMINANCE16, viewport[0], viewport[1], viewport[2], viewport[3], 0); - } - - // reverting to texunit 0, without this we get bug [#28462] - glActiveTextureARB(GL_TEXTURE0); - - // We do this to make side-by-side stereo rendering work correctly with 2D filters. It would probably be nicer to just set the viewport, - // but it can be easier for writing shaders to have the coordinates for the whole screen instead of just part of the screen. - RAS_Rect scissor_rect = canvas->GetDisplayArea(); - - glScissor(scissor_rect.GetLeft() + viewport[0], - scissor_rect.GetBottom() + viewport[1], - scissor_rect.GetWidth() + 1, - scissor_rect.GetHeight() + 1); - - glDisable(GL_DEPTH_TEST); - // in case the previous material was wire - glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); - // if the last rendered face had alpha add it would messes with the color of the plane we apply 2DFilter to - glDisable(GL_BLEND); - // fix for [#34523] alpha buffer is now available for all OSs - glDisable(GL_ALPHA_TEST); - - glPushMatrix(); //GL_MODELVIEW - glLoadIdentity(); // GL_MODELVIEW - glMatrixMode(GL_TEXTURE); - glLoadIdentity(); - glMatrixMode(GL_PROJECTION); - glPushMatrix(); - glLoadIdentity(); - - for (passindex =0; passindex& propNames, void* gameObj, RAS_2DFILTER_MODE mode, int pass, STR_String& text) -{ - if (!isshadersupported) - return; - if (pass<0 || pass>=MAX_RENDER_PASS) - return; - need_tex_update = true; - if (mode == RAS_2DFILTER_DISABLED) - { - m_enabled[pass] = 0; - return; - } - - if (mode == RAS_2DFILTER_ENABLED) - { - m_enabled[pass] = 1; - return; - } - - if (mode == RAS_2DFILTER_NOFILTER) - { - if (m_filters[pass]) - glDeleteObjectARB(m_filters[pass]); - m_enabled[pass] = 0; - m_filters[pass] = 0; - m_gameObjects[pass] = NULL; - m_properties[pass].clear(); - texflag[pass] = 0; - return; - } - - if (mode == RAS_2DFILTER_CUSTOMFILTER) - { - if (m_filters[pass]) - glDeleteObjectARB(m_filters[pass]); - m_filters[pass] = CreateShaderProgram(text.Ptr()); - m_gameObjects[pass] = gameObj; - AnalyseShader(pass, propNames); - m_enabled[pass] = 1; - return; - } - - // We've checked all other cases, which means we must be dealing with a builtin filter - if (m_filters[pass]) - glDeleteObjectARB(m_filters[pass]); - m_filters[pass] = CreateShaderProgram(mode); - m_gameObjects[pass] = NULL; - AnalyseShader(pass, propNames); - m_enabled[pass] = 1; -} diff --git a/source/gameengine/Rasterizer/RAS_2DFilterManager.h b/source/gameengine/Rasterizer/RAS_2DFilterManager.h deleted file mode 100644 index bb727fe3b29..00000000000 --- a/source/gameengine/Rasterizer/RAS_2DFilterManager.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 RAS_2DFilterManager.h - * \ingroup bgerast - */ - -#ifndef __RAS_2DFILTERMANAGER_H__ -#define __RAS_2DFILTERMANAGER_H__ - -#define MAX_RENDER_PASS 100 - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -class RAS_ICanvas; - -class RAS_2DFilterManager -{ -private: - unsigned int CreateShaderProgram(const char* shadersource); - unsigned int CreateShaderProgram(int filtermode); - void AnalyseShader(int passindex, std::vector& propNames); - void StartShaderProgram(int passindex); - void EndShaderProgram(); - void PrintShaderErrors(unsigned int shader, const char *task, const char *code); - - void SetupTextures(bool depth, bool luminance); - void FreeTextures(); - - void UpdateOffsetMatrix(RAS_ICanvas* canvas); - void UpdateCanvasTextureCoord(const int viewport[4]); - - float canvascoord[4]; - float textureoffsets[18]; - /* float view[4]; */ /* UNUSED */ - /* texname[0] contains render to texture, texname[1] contains depth texture, texname[2] contains luminance texture*/ - unsigned int texname[3]; - int texturewidth; - int textureheight; - /* int numberoffilters; */ /* UNUSED */ - /* bit 0: enable/disable depth texture - * bit 1: enable/disable luminance texture*/ - short texflag[MAX_RENDER_PASS]; - - bool isshadersupported; - bool errorprinted; - bool need_tex_update; - - unsigned int m_filters[MAX_RENDER_PASS]; - short m_enabled[MAX_RENDER_PASS]; - - // stores object properties to send to shaders in each pass - std::vector m_properties[MAX_RENDER_PASS]; - void* m_gameObjects[MAX_RENDER_PASS]; -public: - enum RAS_2DFILTER_MODE { - RAS_2DFILTER_ENABLED = -2, - RAS_2DFILTER_DISABLED = -1, - RAS_2DFILTER_NOFILTER = 0, - RAS_2DFILTER_MOTIONBLUR, - RAS_2DFILTER_BLUR, - RAS_2DFILTER_SHARPEN, - RAS_2DFILTER_DILATION, - RAS_2DFILTER_EROSION, - RAS_2DFILTER_LAPLACIAN, - RAS_2DFILTER_SOBEL, - RAS_2DFILTER_PREWITT, - RAS_2DFILTER_GRAYSCALE, - RAS_2DFILTER_SEPIA, - RAS_2DFILTER_INVERT, - RAS_2DFILTER_CUSTOMFILTER, - RAS_2DFILTER_NUMBER_OF_FILTERS - }; - - RAS_2DFilterManager(); - - ~RAS_2DFilterManager(); - - void RenderFilters(RAS_ICanvas* canvas); - - void EnableFilter(std::vector& propNames, void* gameObj, RAS_2DFILTER_MODE mode, int pass, STR_String& text); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_2DFilterManager") -#endif -}; -#endif diff --git a/source/gameengine/Rasterizer/RAS_BucketManager.cpp b/source/gameengine/Rasterizer/RAS_BucketManager.cpp deleted file mode 100644 index deca7cbed9f..00000000000 --- a/source/gameengine/Rasterizer/RAS_BucketManager.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. - * - * 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/Rasterizer/RAS_BucketManager.cpp - * \ingroup bgerast - */ - -#ifdef _MSC_VER - /* don't show these anoying STL warnings */ -# pragma warning (disable:4786) -#endif - -#include "RAS_MaterialBucket.h" -#include "RAS_MeshObject.h" -#include "RAS_Polygon.h" -#include "RAS_IPolygonMaterial.h" -#include "RAS_IRasterizer.h" - -#include "RAS_BucketManager.h" - -#include -/* sorting */ - -struct RAS_BucketManager::sortedmeshslot -{ -public: - MT_Scalar m_z; /* depth */ - RAS_MeshSlot *m_ms; /* mesh slot */ - RAS_MaterialBucket *m_bucket; /* buck mesh slot came from */ - - sortedmeshslot() {} - - void set(RAS_MeshSlot *ms, RAS_MaterialBucket *bucket, const MT_Vector3& pnorm) - { - // would be good to use the actual bounding box center instead - MT_Point3 pos(ms->m_OpenGLMatrix[12], ms->m_OpenGLMatrix[13], ms->m_OpenGLMatrix[14]); - - m_z = MT_dot(pnorm, pos); - m_ms = ms; - m_bucket = bucket; - } -}; - -struct RAS_BucketManager::backtofront -{ - bool operator()(const sortedmeshslot &a, const sortedmeshslot &b) - { - return (a.m_z < b.m_z) || (a.m_z == b.m_z && a.m_ms < b.m_ms); - } -}; - -struct RAS_BucketManager::fronttoback -{ - bool operator()(const sortedmeshslot &a, const sortedmeshslot &b) - { - return (a.m_z > b.m_z) || (a.m_z == b.m_z && a.m_ms > b.m_ms); - } -}; - -/* bucket manager */ - -RAS_BucketManager::RAS_BucketManager() -{ - -} - -RAS_BucketManager::~RAS_BucketManager() -{ - BucketList::iterator it; - - for (it = m_SolidBuckets.begin(); it != m_SolidBuckets.end(); it++) - delete (*it); - - for (it = m_AlphaBuckets.begin(); it != m_AlphaBuckets.end(); it++) - delete(*it); - - m_SolidBuckets.clear(); - m_AlphaBuckets.clear(); -} - -void RAS_BucketManager::OrderBuckets(const MT_Transform& cameratrans, BucketList& buckets, vector& slots, bool alpha) -{ - BucketList::iterator bit; - list::iterator mit; - size_t size = 0, i = 0; - - /* Camera's near plane equation: pnorm.dot(point) + pval, - * but we leave out pval since it's constant anyway */ - const MT_Vector3 pnorm(cameratrans.getBasis()[2]); - - for (bit = buckets.begin(); bit != buckets.end(); ++bit) - { - SG_DList::iterator mit((*bit)->GetActiveMeshSlots()); - for (mit.begin(); !mit.end(); ++mit) - size++; - } - - slots.resize(size); - - for (bit = buckets.begin(); bit != buckets.end(); ++bit) - { - RAS_MaterialBucket* bucket = *bit; - RAS_MeshSlot* ms; - // remove the mesh slot from the list, it culls them automatically for next frame - while ((ms = bucket->GetNextActiveMeshSlot())) { - slots[i++].set(ms, bucket, pnorm); - } - } - - if (alpha) - sort(slots.begin(), slots.end(), backtofront()); - else - sort(slots.begin(), slots.end(), fronttoback()); -} - -void RAS_BucketManager::RenderAlphaBuckets(const MT_Transform& cameratrans, RAS_IRasterizer* rasty) -{ - vector slots; - vector::iterator sit; - - // Having depth masks disabled/enabled gives different artifacts in - // case no sorting is done or is done inexact. For compatibility, we - // disable it. - if (rasty->GetDrawingMode() != RAS_IRasterizer::KX_SHADOW) - rasty->SetDepthMask(RAS_IRasterizer::KX_DEPTHMASK_DISABLED); - - OrderBuckets(cameratrans, m_AlphaBuckets, slots, true); - - for (sit=slots.begin(); sit!=slots.end(); ++sit) { - rasty->SetClientObject(sit->m_ms->m_clientObj); - - while (sit->m_bucket->ActivateMaterial(cameratrans, rasty)) - sit->m_bucket->RenderMeshSlot(cameratrans, rasty, *(sit->m_ms)); - - // make this mesh slot culled automatically for next frame - // it will be culled out by frustum culling - sit->m_ms->SetCulled(true); - } - - rasty->SetDepthMask(RAS_IRasterizer::KX_DEPTHMASK_ENABLED); -} - -void RAS_BucketManager::RenderSolidBuckets(const MT_Transform& cameratrans, RAS_IRasterizer* rasty) -{ - BucketList::iterator bit; - - rasty->SetDepthMask(RAS_IRasterizer::KX_DEPTHMASK_ENABLED); - - for (bit = m_SolidBuckets.begin(); bit != m_SolidBuckets.end(); ++bit) { -#if 1 - RAS_MaterialBucket* bucket = *bit; - RAS_MeshSlot* ms; - // remove the mesh slot from the list, it culls them automatically for next frame - while ((ms = bucket->GetNextActiveMeshSlot())) { - rasty->SetClientObject(ms->m_clientObj); - while (bucket->ActivateMaterial(cameratrans, rasty)) - bucket->RenderMeshSlot(cameratrans, rasty, *ms); - - // make this mesh slot culled automatically for next frame - // it will be culled out by frustum culling - ms->SetCulled(true); - } -#else - list::iterator mit; - for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit) { - if (mit->IsCulled()) - continue; - - rasty->SetClientObject(rasty, mit->m_clientObj); - - while ((*bit)->ActivateMaterial(cameratrans, rasty)) - (*bit)->RenderMeshSlot(cameratrans, rasty, *mit); - - // make this mesh slot culled automatically for next frame - // it will be culled out by frustum culling - mit->SetCulled(true); - } -#endif - } - - /* this code draws meshes order front-to-back instead to reduce overdraw. - * it turned out slower due to much material state switching, a more clever - * algorithm might do better. */ -#if 0 - vector slots; - vector::iterator sit; - - OrderBuckets(cameratrans, m_SolidBuckets, slots, false); - - for (sit=slots.begin(); sit!=slots.end(); ++sit) { - rendertools->SetClientObject(rasty, sit->m_ms->m_clientObj); - - while (sit->m_bucket->ActivateMaterial(cameratrans, rasty)) - sit->m_bucket->RenderMeshSlot(cameratrans, rasty, *(sit->m_ms)); - } -#endif -} - -void RAS_BucketManager::Renderbuckets(const MT_Transform& cameratrans, RAS_IRasterizer* rasty) -{ - /* beginning each frame, clear (texture/material) caching information */ - rasty->ClearCachingInfo(); - - RenderSolidBuckets(cameratrans, rasty); - RenderAlphaBuckets(cameratrans, rasty); - - /* If we're drawing shadows and bucket wasn't rendered (outside of the lamp frustum or doesn't cast shadows) - * then the mesh is still modified, so we don't want to set MeshModified to false yet (it will mess up - * updating display lists). Just leave this step for the main render pass. - */ - if (rasty->GetDrawingMode() != RAS_IRasterizer::KX_SHADOW) { - /* All meshes should be up to date now */ - /* Don't do this while processing buckets because some meshes are split between buckets */ - BucketList::iterator bit; - list::iterator mit; - for (bit = m_SolidBuckets.begin(); bit != m_SolidBuckets.end(); ++bit) { - for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit) { - mit->m_mesh->SetMeshModified(false); - } - } - for (bit = m_AlphaBuckets.begin(); bit != m_AlphaBuckets.end(); ++bit) { - for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit) { - mit->m_mesh->SetMeshModified(false); - } - } - } - - - rasty->SetClientObject(NULL); -} - -RAS_MaterialBucket *RAS_BucketManager::FindBucket(RAS_IPolyMaterial *material, bool &bucketCreated) -{ - BucketList::iterator it; - - bucketCreated = false; - - for (it = m_SolidBuckets.begin(); it != m_SolidBuckets.end(); it++) - if (*(*it)->GetPolyMaterial() == *material) - return *it; - - for (it = m_AlphaBuckets.begin(); it != m_AlphaBuckets.end(); it++) - if (*(*it)->GetPolyMaterial() == *material) - return *it; - - RAS_MaterialBucket *bucket = new RAS_MaterialBucket(material); - bucketCreated = true; - - if (bucket->IsAlpha()) - m_AlphaBuckets.push_back(bucket); - else - m_SolidBuckets.push_back(bucket); - - return bucket; -} - -void RAS_BucketManager::OptimizeBuckets(MT_Scalar distance) -{ - BucketList::iterator bit; - - distance = 10.0f; - - for (bit = m_SolidBuckets.begin(); bit != m_SolidBuckets.end(); ++bit) - (*bit)->Optimize(distance); - for (bit = m_AlphaBuckets.begin(); bit != m_AlphaBuckets.end(); ++bit) - (*bit)->Optimize(distance); -} - -void RAS_BucketManager::ReleaseDisplayLists(RAS_IPolyMaterial *mat) -{ - BucketList::iterator bit; - list::iterator mit; - - for (bit = m_SolidBuckets.begin(); bit != m_SolidBuckets.end(); ++bit) { - if (mat == NULL || (mat == (*bit)->GetPolyMaterial())) { - for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit) { - if (mit->m_DisplayList) { - mit->m_DisplayList->Release(); - mit->m_DisplayList = NULL; - } - } - } - } - - for (bit = m_AlphaBuckets.begin(); bit != m_AlphaBuckets.end(); ++bit) { - if (mat == NULL || (mat == (*bit)->GetPolyMaterial())) { - for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit) { - if (mit->m_DisplayList) { - mit->m_DisplayList->Release(); - mit->m_DisplayList = NULL; - } - } - } - } -} - -void RAS_BucketManager::ReleaseMaterials(RAS_IPolyMaterial * mat) -{ - BucketList::iterator bit; - list::iterator mit; - - for (bit = m_SolidBuckets.begin(); bit != m_SolidBuckets.end(); ++bit) { - if (mat == NULL || (mat == (*bit)->GetPolyMaterial())) { - (*bit)->GetPolyMaterial()->ReleaseMaterial(); - } - } - - for (bit = m_AlphaBuckets.begin(); bit != m_AlphaBuckets.end(); ++bit) { - if (mat == NULL || (mat == (*bit)->GetPolyMaterial())) { - (*bit)->GetPolyMaterial()->ReleaseMaterial(); - } - } -} - -/* frees the bucket, only used when freeing scenes */ -void RAS_BucketManager::RemoveMaterial(RAS_IPolyMaterial * mat) -{ - BucketList::iterator bit, bitp; - list::iterator mit; - int i; - - - for (i=0; iGetPolyMaterial()) { - m_SolidBuckets.erase(m_SolidBuckets.begin()+i); - delete bucket; - i--; - } - } - - for (int i=0; iGetPolyMaterial()) { - m_AlphaBuckets.erase(m_AlphaBuckets.begin()+i); - delete bucket; - i--; - } - } -} - -//#include - -void RAS_BucketManager::MergeBucketManager(RAS_BucketManager *other, SCA_IScene *scene) -{ - /* concatenate lists */ - // printf("BEFORE %d %d\n", GetSolidBuckets().size(), GetAlphaBuckets().size()); - - GetSolidBuckets().insert( GetSolidBuckets().end(), other->GetSolidBuckets().begin(), other->GetSolidBuckets().end() ); - other->GetSolidBuckets().clear(); - - GetAlphaBuckets().insert( GetAlphaBuckets().end(), other->GetAlphaBuckets().begin(), other->GetAlphaBuckets().end() ); - other->GetAlphaBuckets().clear(); - //printf("AFTER %d %d\n", GetSolidBuckets().size(), GetAlphaBuckets().size()); -} - diff --git a/source/gameengine/Rasterizer/RAS_BucketManager.h b/source/gameengine/Rasterizer/RAS_BucketManager.h deleted file mode 100644 index 5ed212ebee0..00000000000 --- a/source/gameengine/Rasterizer/RAS_BucketManager.h +++ /dev/null @@ -1,93 +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 RAS_BucketManager.h - * \ingroup bgerast - */ - -#ifndef __RAS_BUCKETMANAGER_H__ -#define __RAS_BUCKETMANAGER_H__ - -#include "MT_Transform.h" -#include "RAS_MaterialBucket.h" - -#include - -class RAS_BucketManager -{ -public: - typedef std::vector BucketList; -private: - BucketList m_SolidBuckets; - BucketList m_AlphaBuckets; - - struct sortedmeshslot; - struct backtofront; - struct fronttoback; - -public: - RAS_BucketManager(); - virtual ~RAS_BucketManager(); - - void Renderbuckets(const MT_Transform & cameratrans, RAS_IRasterizer* rasty); - - RAS_MaterialBucket* FindBucket(RAS_IPolyMaterial *material, bool &bucketCreated); - void OptimizeBuckets(MT_Scalar distance); - - void ReleaseDisplayLists(RAS_IPolyMaterial *material = NULL); - void ReleaseMaterials(RAS_IPolyMaterial *material = NULL); - - void RemoveMaterial(RAS_IPolyMaterial *mat); // freeing scenes only - - /* for merging */ - void MergeBucketManager(RAS_BucketManager *other, SCA_IScene *scene); - BucketList & GetSolidBuckets() {return m_SolidBuckets;} - BucketList & GetAlphaBuckets() {return m_AlphaBuckets;} - - /*void PrintStats(int verbose_level) { - printf("\nMappings...\n"); - printf("\t m_SolidBuckets: %d\n", m_SolidBuckets.size()); - printf("\t\t m_SolidBuckets: %d\n", m_SolidBuckets.size()); - printf("\t m_AlphaBuckets: %d\n", m_AlphaBuckets.size()); - }*/ - - -private: - void OrderBuckets(const MT_Transform& cameratrans, BucketList& buckets, vector& slots, bool alpha); - - void RenderSolidBuckets(const MT_Transform& cameratrans, - RAS_IRasterizer* rasty); - void RenderAlphaBuckets(const MT_Transform& cameratrans, - RAS_IRasterizer* rasty); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_BucketManager") -#endif -}; - -#endif /* __RAS_BUCKETMANAGER_H__ */ diff --git a/source/gameengine/Rasterizer/RAS_CameraData.h b/source/gameengine/Rasterizer/RAS_CameraData.h deleted file mode 100644 index bc8433afd05..00000000000 --- a/source/gameengine/Rasterizer/RAS_CameraData.h +++ /dev/null @@ -1,79 +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 RAS_CameraData.h - * \ingroup bgerast - */ - -#ifndef __RAS_CAMERADATA_H__ -#define __RAS_CAMERADATA_H__ - -struct RAS_CameraData -{ - float m_lens; - float m_scale; - float m_sensor_x; - float m_sensor_y; - short m_sensor_fit; - float m_shift_x; - float m_shift_y; - float m_clipstart; - float m_clipend; - bool m_perspective; - bool m_viewport; - int m_viewportleft; - int m_viewportbottom; - int m_viewportright; - int m_viewporttop; - float m_focallength; - - RAS_CameraData(float lens = 35.0f, float scale = 6.0f, float sensor_x = 32.0f, float sensor_y = 18.0f, short sensor_fit = 0, - float shift_x = 0.0f, float shift_y = 0.0f, - float clipstart = 0.1f, float clipend = 5000.0f, bool perspective = true, - float focallength = 3.0f, bool viewport = false, int viewportleft = 0, int viewportbottom = 0, - int viewportright = 0, int viewporttop = 0) : - m_lens(lens), - m_scale(scale), - m_sensor_x(sensor_x), - m_sensor_y(sensor_y), - m_sensor_fit(sensor_fit), - m_shift_x(shift_x), - m_shift_y(shift_y), - m_clipstart(clipstart), - m_clipend(clipend), - m_perspective(perspective), - m_viewport(viewport), - m_viewportleft(viewportleft), - m_viewportbottom(viewportbottom), - m_viewportright(viewportright), - m_viewporttop(viewporttop), - m_focallength(focallength) - { - } -}; - -#endif /* __RAS_CAMERADATA_H__ */ diff --git a/source/gameengine/Rasterizer/RAS_Deformer.h b/source/gameengine/Rasterizer/RAS_Deformer.h deleted file mode 100644 index 058f2304f3d..00000000000 --- a/source/gameengine/Rasterizer/RAS_Deformer.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 RAS_Deformer.h - * \ingroup bgerast - */ - -#ifndef __RAS_DEFORMER_H__ -#define __RAS_DEFORMER_H__ - -#ifdef _MSC_VER -# pragma warning (disable:4786) /* get rid of stupid stl-visual compiler debug warning */ -#endif - -#include -#include "CTR_Map.h" - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -struct DerivedMesh; -class RAS_MeshObject; - -class RAS_Deformer -{ -public: - RAS_Deformer() : m_pMesh(NULL), m_bDynamic(false) {} - virtual ~RAS_Deformer() {} - virtual void Relink(CTR_Map*map)=0; - virtual bool Apply(class RAS_IPolyMaterial *polymat)=0; - virtual bool Update(void)=0; - virtual bool UpdateBuckets(void)=0; - virtual RAS_Deformer *GetReplica()=0; - virtual void ProcessReplica()=0; - virtual bool SkipVertexTransform() - { - return false; - } - virtual bool ShareVertexArray() - { - return true; - } - virtual bool UseVertexArray() - { - return true; - } - // true when deformer produces varying vertex (shape or armature) - bool IsDynamic() - { - return m_bDynamic; - } - virtual struct DerivedMesh* GetFinalMesh() - { - return NULL; - } - virtual struct DerivedMesh* GetPhysicsMesh() - { - return NULL; - } - virtual class RAS_MeshObject* GetRasMesh() - { - /* m_pMesh does not seem to be being used?? */ - return NULL; - } - virtual float (* GetTransVerts(int *tot))[3] { *tot= 0; return NULL; } - -protected: - class RAS_MeshObject *m_pMesh; - bool m_bDynamic; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_Deformer") -#endif -}; - -#endif - diff --git a/source/gameengine/Rasterizer/RAS_FramingManager.cpp b/source/gameengine/Rasterizer/RAS_FramingManager.cpp deleted file mode 100644 index 8b0ec22fde3..00000000000 --- a/source/gameengine/Rasterizer/RAS_FramingManager.cpp +++ /dev/null @@ -1,425 +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/Rasterizer/RAS_FramingManager.cpp - * \ingroup bgerast - */ - - -#include "RAS_FramingManager.h" -#include "RAS_Rect.h" - - void -RAS_FramingManager:: -ComputeDefaultFrustum( - const float camnear, - const float camfar, - const float lens, - const float sensor_x, const float sensor_y, - const short sensor_fit, - const float shift_x, - const float shift_y, - const float design_aspect_ratio, - RAS_FrameFrustum & frustum -) { - float size; - float halfSize; - float sizeX; - float sizeY; - float offsetX; - float offsetY; - - if (sensor_fit==RAS_SENSORFIT_AUTO) { - size = sensor_x * camnear / lens; - halfSize = size * 0.5f; - - if (design_aspect_ratio > 1.f) { - // halfsize defines the width - sizeX = halfSize; - sizeY = halfSize/design_aspect_ratio; - } else { - // halfsize defines the height - sizeX = halfSize * design_aspect_ratio; - sizeY = halfSize; - } - } - else if (sensor_fit==RAS_SENSORFIT_HOR) { - size = sensor_x * camnear / lens; - halfSize = size * 0.5f; - sizeX = halfSize; - sizeY = halfSize/design_aspect_ratio; - } - else { - size = sensor_y * camnear / lens; - halfSize = size * 0.5f; - sizeX = halfSize * design_aspect_ratio; - sizeY = halfSize; - } - - offsetX = size * shift_x; - offsetY = size * shift_y; - - frustum.x2 = sizeX + offsetX; - frustum.x1 = -sizeX + offsetX; - frustum.y2 = sizeY + offsetY; - frustum.y1 = -sizeY + offsetY; - frustum.camnear = camnear; - frustum.camfar = camfar; -} - - void -RAS_FramingManager:: -ComputeDefaultOrtho( - const float camnear, - const float camfar, - const float scale, - const float design_aspect_ratio, - const short sensor_fit, - const float shift_x, - const float shift_y, - RAS_FrameFrustum & frustum -) -{ - float halfSize = scale*0.5f; - float sizeX; - float sizeY; - float offsetX; - float offsetY; - - if (sensor_fit==RAS_SENSORFIT_AUTO) { - if (design_aspect_ratio > 1.f) { - // halfsize defines the width - sizeX = halfSize; - sizeY = halfSize/design_aspect_ratio; - } else { - // halfsize defines the height - sizeX = halfSize * design_aspect_ratio; - sizeY = halfSize; - } - } - else if (sensor_fit==RAS_SENSORFIT_HOR) { - sizeX = halfSize; - sizeY = halfSize/design_aspect_ratio; - } - else { - sizeX = halfSize * design_aspect_ratio; - sizeY = halfSize; - } - - offsetX = scale * shift_x; - offsetY = scale * shift_y; - - frustum.x2 = sizeX + offsetX; - frustum.x1 = -sizeX + offsetX; - frustum.y2 = sizeY + offsetY; - frustum.y1 = -sizeY + offsetY; - frustum.camnear = camnear; - frustum.camfar = camfar; -} - - - void -RAS_FramingManager:: -ComputeBestFitViewRect( - const RAS_Rect &availableViewport, - const float design_aspect_ratio, - RAS_Rect &viewport -) { - // try and honour the aspect ratio when setting the - // drawable area. If we don't do this we are liable - // to get a lot of distortion in the rendered image. - - int width = availableViewport.GetWidth(); - int height = availableViewport.GetHeight(); - float window_aspect = float(width)/float(height); - - if (window_aspect < design_aspect_ratio) { - int v_height = (int)(width / design_aspect_ratio); - int left_over = (height - v_height) / 2; - - viewport.SetLeft(availableViewport.GetLeft()); - viewport.SetBottom(availableViewport.GetBottom() + left_over); - viewport.SetRight(availableViewport.GetLeft() + width); - viewport.SetTop(availableViewport.GetBottom() + left_over + v_height); - - } else { - int v_width = (int)(height * design_aspect_ratio); - int left_over = (width - v_width) / 2; - - viewport.SetLeft(availableViewport.GetLeft() + left_over); - viewport.SetBottom(availableViewport.GetBottom()); - viewport.SetRight(availableViewport.GetLeft() + v_width + left_over); - viewport.SetTop(availableViewport.GetBottom() + height); - } -} - - void -RAS_FramingManager:: -ComputeViewport( - const RAS_FrameSettings &settings, - const RAS_Rect &availableViewport, - RAS_Rect &viewport -) { - - RAS_FrameSettings::RAS_FrameType type = settings.FrameType(); - const int winx = availableViewport.GetWidth(); - const int winy = availableViewport.GetHeight(); - - const float design_width = float(settings.DesignAspectWidth()); - const float design_height = float(settings.DesignAspectHeight()); - - float design_aspect_ratio = float(1); - - if (design_height == float(0)) { - // well this is ill defined - // lets just scale the thing - - type = RAS_FrameSettings::e_frame_scale; - } else { - design_aspect_ratio = design_width/design_height; - } - - switch (type) { - - case RAS_FrameSettings::e_frame_scale : - case RAS_FrameSettings::e_frame_extend: - { - viewport.SetLeft(availableViewport.GetLeft()); - viewport.SetBottom(availableViewport.GetBottom()); - viewport.SetRight(availableViewport.GetLeft() + int(winx)); - viewport.SetTop(availableViewport.GetBottom() + int(winy)); - - break; - } - - case RAS_FrameSettings::e_frame_bars: - { - ComputeBestFitViewRect( - availableViewport, - design_aspect_ratio, - viewport - ); - - break; - } - default : - break; - } -} - - void -RAS_FramingManager:: -ComputeFrustum( - const RAS_FrameSettings &settings, - const RAS_Rect &availableViewport, - const RAS_Rect &viewport, - const float lens, - const float sensor_x, const float sensor_y, const short sensor_fit, - const float shift_x, - const float shift_y, - const float camnear, - const float camfar, - RAS_FrameFrustum &frustum -) { - - RAS_FrameSettings::RAS_FrameType type = settings.FrameType(); - - const float design_width = float(settings.DesignAspectWidth()); - const float design_height = float(settings.DesignAspectHeight()); - - float design_aspect_ratio = float(1); - - if (design_height == float(0)) { - // well this is ill defined - // lets just scale the thing - - type = RAS_FrameSettings::e_frame_scale; - } else { - design_aspect_ratio = design_width/design_height; - } - - ComputeDefaultFrustum( - camnear, - camfar, - lens, - sensor_x, - sensor_y, - sensor_fit, - shift_x, - shift_y, - design_aspect_ratio, - frustum - ); - - switch (type) { - - case RAS_FrameSettings::e_frame_extend: - { - float x_scale, y_scale; - switch (sensor_fit) { - case RAS_SENSORFIT_HOR: - { - x_scale = 1.0f; - y_scale = float(viewport.GetHeight()) / float(viewport.GetWidth()); - break; - } - case RAS_SENSORFIT_VERT: - { - x_scale = float(viewport.GetWidth()) / float(viewport.GetHeight()); - y_scale = 1.0f; - break; - } - case RAS_SENSORFIT_AUTO: - default: - { - RAS_Rect vt; - ComputeBestFitViewRect( - availableViewport, - design_aspect_ratio, - vt - ); - - // now scale the calculated frustum by the difference - // between vt and the viewport in each axis. - // These are always > 1 - - x_scale = float(viewport.GetWidth())/float(vt.GetWidth()); - y_scale = float(viewport.GetHeight())/float(vt.GetHeight()); - break; - } - } - - frustum.x1 *= x_scale; - frustum.x2 *= x_scale; - frustum.y1 *= y_scale; - frustum.y2 *= y_scale; - - break; - } - case RAS_FrameSettings::e_frame_scale : - case RAS_FrameSettings::e_frame_bars: - default : - break; - } -} - - void -RAS_FramingManager:: - ComputeOrtho( - const RAS_FrameSettings &settings, - const RAS_Rect &availableViewport, - const RAS_Rect &viewport, - const float scale, - const float camnear, - const float camfar, - const short sensor_fit, - const float shift_x, - const float shift_y, - RAS_FrameFrustum &frustum - ) -{ - RAS_FrameSettings::RAS_FrameType type = settings.FrameType(); - - const float design_width = float(settings.DesignAspectWidth()); - const float design_height = float(settings.DesignAspectHeight()); - - float design_aspect_ratio = float(1); - - if (design_height == float(0)) { - // well this is ill defined - // lets just scale the thing - type = RAS_FrameSettings::e_frame_scale; - } else { - design_aspect_ratio = design_width/design_height; - } - - - ComputeDefaultOrtho( - camnear, - camfar, - scale, - design_aspect_ratio, - sensor_fit, - shift_x, - shift_y, - frustum - ); - - switch (type) { - - case RAS_FrameSettings::e_frame_extend: - { - float x_scale, y_scale; - switch (sensor_fit) { - case RAS_SENSORFIT_HOR: - { - x_scale = 1.0f; - y_scale = float(viewport.GetHeight()) / float(viewport.GetWidth()); - break; - } - case RAS_SENSORFIT_VERT: - { - x_scale = float(viewport.GetWidth()) / float(viewport.GetHeight()); - y_scale = 1.0f; - break; - } - case RAS_SENSORFIT_AUTO: - default: - { - RAS_Rect vt; - ComputeBestFitViewRect( - availableViewport, - design_aspect_ratio, - vt - ); - - // now scale the calculated frustum by the difference - // between vt and the viewport in each axis. - // These are always > 1 - - x_scale = float(viewport.GetWidth())/float(vt.GetWidth()); - y_scale = float(viewport.GetHeight())/float(vt.GetHeight()); - break; - } - } - - frustum.x1 *= x_scale; - frustum.x2 *= x_scale; - frustum.y1 *= y_scale; - frustum.y2 *= y_scale; - - break; - } - case RAS_FrameSettings::e_frame_scale : - case RAS_FrameSettings::e_frame_bars: - default : - break; - } - -} - - diff --git a/source/gameengine/Rasterizer/RAS_FramingManager.h b/source/gameengine/Rasterizer/RAS_FramingManager.h deleted file mode 100644 index cb86a7a4484..00000000000 --- a/source/gameengine/Rasterizer/RAS_FramingManager.h +++ /dev/null @@ -1,316 +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 RAS_FramingManager.h - * \ingroup bgerast - */ - -#ifndef __RAS_FRAMINGMANAGER_H__ -#define __RAS_FRAMINGMANAGER_H__ - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -class RAS_Rect; - -/** - * \section RAS_FrameSettings - * This is a value type describing the framing used - * by a particular scene in the game engine. - * Each KX_Scene contains a RAS_FrameSetting describing - * how the frustum and viewport are to be modified - * depending on the canvas size. - * - * e_frame_scale means that the viewport is set to the current - * canvas size. If the view frustum aspect ratio is different - * to the canvas aspect this will lead to stretching. - * - * e_frame_extend means that the best fit viewport will be - * computed based upon the design aspect ratio - * and the view frustum will be adjusted so that - * more of the scene is visible. - * - * e_frame_bars means that the best fit viewport will be - * be computed based upon the design aspect ratio. - */ - -class RAS_FrameSettings -{ -public : - /** - * enum defining the policy to use - * in each axis. - */ - enum RAS_FrameType { - e_frame_scale, - e_frame_extend, - e_frame_bars - }; - - /** - * Constructor - */ - - RAS_FrameSettings( - RAS_FrameType frame_type, - float bar_r, - float bar_g, - float bar_b, - unsigned int design_aspect_width, - unsigned int design_aspect_height - ): - m_frame_type(frame_type), - m_bar_r(bar_r), - m_bar_g(bar_g), - m_bar_b(bar_b), - m_design_aspect_width(design_aspect_width), - m_design_aspect_height(design_aspect_height) - { - }; - - RAS_FrameSettings( - ): - m_frame_type(e_frame_scale), - m_bar_r(0), - m_bar_g(0), - m_bar_b(0), - m_design_aspect_width(1), - m_design_aspect_height(1) - { - }; - - /** - * Accessors - */ - - const - RAS_FrameType & - FrameType( - ) const { - return m_frame_type; - }; - - void - SetFrameType( - RAS_FrameType type - ) { - m_frame_type = type; - }; - - float - BarRed( - ) const { - return m_bar_r; - }; - - float - BarGreen( - ) const { - return m_bar_g; - }; - - float - BarBlue( - ) const { - return m_bar_b; - }; - - unsigned int - DesignAspectWidth( - ) const { - return m_design_aspect_width; - }; - - unsigned int - DesignAspectHeight( - ) const { - return m_design_aspect_height; - }; - -private : - - RAS_FrameType m_frame_type; - float m_bar_r; - float m_bar_g; - float m_bar_b; - unsigned int m_design_aspect_width; - unsigned int m_design_aspect_height; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_FrameSettings") -#endif -}; - -struct RAS_FrameFrustum -{ - float camnear,camfar; - float x1,y1; - float x2,y2; -}; - -/* must match R_CULLING_... from DNA_scene_types.h */ -enum RAS_CullingMode -{ - RAS_CULLING_DBVT = 0, - RAS_CULLING_NORMAL, - RAS_CULLING_NONE -}; - -/* Should match CAMERA_SENSOR_FIT... from DNA_camera_types.h */ -enum RAS_SensorFit -{ - RAS_SENSORFIT_AUTO = 0, - RAS_SENSORFIT_HOR, - RAS_SENSORFIT_VERT -}; - -/** - * \section RAS_FramingManager - * This class helps to compute a view frustum - * and a viewport rectangle given the - * above settings and a description of the - * current canvas dimensions. - * - * You do not have to instantiate this class - * directly, it only contains static helper functions - */ - -class RAS_FramingManager -{ -public : - - /** - * Compute a viewport given - * a RAS_FrameSettings and a description of the - * canvas. - */ - - static - void - ComputeViewport( - const RAS_FrameSettings &settings, - const RAS_Rect &availableViewport, - RAS_Rect &viewport - ); - - - /** - * compute a frustum given a valid viewport, - * RAS_FrameSettings, canvas description - * and camera description - */ - - static - void - ComputeOrtho( - const RAS_FrameSettings &settings, - const RAS_Rect &availableViewport, - const RAS_Rect &viewport, - const float scale, - const float camnear, - const float camfar, - const short sensor_fit, - const float shift_x, - const float shift_y, - RAS_FrameFrustum &frustum - ); - - static - void - ComputeFrustum( - const RAS_FrameSettings &settings, - const RAS_Rect &availableViewport, - const RAS_Rect &viewport, - const float lens, - const float sensor_x, const float sensor_y, const short sensor_fit, - const float shift_x, - const float shift_y, - const float camnear, - const float camfar, - RAS_FrameFrustum &frustum - ); - - static - void - ComputeDefaultFrustum( - const float camnear, - const float camfar, - const float lens, - const float sensor_x, const float sensor_y, - const short sensor_fit, - const float shift_x, - const float shift_y, - const float design_aspect_ratio, - RAS_FrameFrustum & frustum - ); - - static - void - ComputeDefaultOrtho( - const float camnear, - const float camfar, - const float scale, - const float design_aspect_ratio, - const short sensor_fit, - const float shift_x, - const float shift_y, - RAS_FrameFrustum & frustum - ); - -private : - - static - void - ComputeBestFitViewRect( - const RAS_Rect &availableViewport, - const float design_aspect_ratio, - RAS_Rect &viewport - ); - - - - /** - * Private constructor - this class is not meant - * for instantiation. - */ - - RAS_FramingManager( - ); - - RAS_FramingManager( - const RAS_FramingManager & - ); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_FramingManager") -#endif -}; - -#endif diff --git a/source/gameengine/Rasterizer/RAS_ICanvas.cpp b/source/gameengine/Rasterizer/RAS_ICanvas.cpp deleted file mode 100644 index 808d257f8f0..00000000000 --- a/source/gameengine/Rasterizer/RAS_ICanvas.cpp +++ /dev/null @@ -1,128 +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/Rasterizer/RAS_ICanvas.cpp - * \ingroup bgerast - */ - -#include "RAS_ICanvas.h" -#include "DNA_scene_types.h" - -#include "BKE_image.h" -#include "BKE_global.h" -#include "BKE_main.h" - -#include "BLI_task.h" -#include "BLI_path_util.h" -#include "BLI_string.h" - -#include "MEM_guardedalloc.h" - -extern "C" { -#include "IMB_imbuf.h" -#include "IMB_imbuf_types.h" -} - - -// Task data for saving screenshots in a different thread. -struct ScreenshotTaskData -{ - unsigned int *dumprect; - int dumpsx; - int dumpsy; - char *path; - ImageFormatData *im_format; -}; - -/** - * Function that actually performs the image compression and saving to disk of a screenshot. - * Run in a separate thread by RAS_ICanvas::save_screenshot(). - * - * @param taskdata Must point to a ScreenshotTaskData object. This function takes ownership - * of all pointers in the ScreenshotTaskData, and frees them. - */ -void save_screenshot_thread_func(TaskPool *__restrict pool, void *taskdata, int threadid); - - -RAS_ICanvas::RAS_ICanvas() -{ - m_taskscheduler = BLI_task_scheduler_create(TASK_SCHEDULER_AUTO_THREADS); - m_taskpool = BLI_task_pool_create(m_taskscheduler, NULL); -} - -RAS_ICanvas::~RAS_ICanvas() -{ - if (m_taskpool) { - BLI_task_pool_work_and_wait(m_taskpool); - BLI_task_pool_free(m_taskpool); - m_taskpool = NULL; - } - - if (m_taskscheduler) { - BLI_task_scheduler_free(m_taskscheduler); - m_taskscheduler = NULL; - } -} - - -void save_screenshot_thread_func(TaskPool *__restrict UNUSED(pool), void *taskdata, int UNUSED(threadid)) -{ - ScreenshotTaskData *task = static_cast(taskdata); - - /* create and save imbuf */ - ImBuf *ibuf = IMB_allocImBuf(task->dumpsx, task->dumpsy, 24, 0); - ibuf->rect = task->dumprect; - - BKE_imbuf_write_as(ibuf, task->path, task->im_format, false); - - ibuf->rect = NULL; - IMB_freeImBuf(ibuf); - MEM_freeN(task->dumprect); - MEM_freeN(task->path); - MEM_freeN(task->im_format); -} - - -void RAS_ICanvas::save_screenshot(const char *filename, int dumpsx, int dumpsy, unsigned int *dumprect, - ImageFormatData * im_format) -{ - /* create file path */ - char *path = (char *)MEM_mallocN(FILE_MAX, "screenshot-path"); - BLI_strncpy(path, filename, FILE_MAX); - BLI_path_abs(path, G.main->name); - BLI_path_frame(path, m_frame, 0); - m_frame++; - BKE_image_path_ensure_ext_from_imtype(path, im_format->imtype); - - /* Save the actual file in a different thread, so that the - * game engine can keep running at full speed. */ - ScreenshotTaskData *task = (ScreenshotTaskData *)MEM_mallocN(sizeof(ScreenshotTaskData), "screenshot-data"); - task->dumprect = dumprect; - task->dumpsx = dumpsx; - task->dumpsy = dumpsy; - task->path = path; - task->im_format = im_format; - - BLI_task_pool_push(m_taskpool, - save_screenshot_thread_func, - task, - true, // free task data - TASK_PRIORITY_LOW); -} diff --git a/source/gameengine/Rasterizer/RAS_ICanvas.h b/source/gameengine/Rasterizer/RAS_ICanvas.h deleted file mode 100644 index 91cc13c8f85..00000000000 --- a/source/gameengine/Rasterizer/RAS_ICanvas.h +++ /dev/null @@ -1,287 +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 RAS_ICanvas.h - * \ingroup bgerast - */ - -#ifndef __RAS_ICANVAS_H__ -#define __RAS_ICANVAS_H__ - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -class RAS_Rect; -struct TaskScheduler; -struct TaskPool; -struct ImageFormatData; - -/** - * 2D rendering device context. The connection from 3d rendercontext to 2d surface. - */ -class RAS_ICanvas -{ -public: - enum BufferType { - COLOR_BUFFER=1, - DEPTH_BUFFER=2 - }; - - enum RAS_MouseState - { - MOUSE_INVISIBLE=1, - MOUSE_WAIT, - MOUSE_NORMAL - }; - - RAS_ICanvas(); - virtual ~RAS_ICanvas(); - - virtual - void - Init( - ) = 0; - - virtual - void - BeginFrame( - )=0; - - virtual - void - EndFrame( - )=0; - - /** - * Initializes the canvas for drawing. Drawing to the canvas is - * only allowed between BeginDraw() and EndDraw(). - * - * \retval false Acquiring the canvas failed. - * \retval true Acquiring the canvas succeeded. - * - */ - - virtual - bool - BeginDraw( - )=0; - - /** - * Unitializes the canvas for drawing. - */ - - virtual - void - EndDraw( - )=0; - - - /// probably needs some arguments for PS2 in future - virtual - void - SwapBuffers( - )=0; - - virtual - void - SetSwapInterval( - int interval - )=0; - - virtual - bool - GetSwapInterval( - int& intervalOut - )=0; - - virtual - void - ClearBuffer( - int type - )=0; - - virtual - void - ClearColor( - float r, - float g, - float b, - float a - )=0; - - virtual - int - GetWidth( - ) const = 0; - - virtual - int - GetHeight( - ) const = 0; - - virtual - int - GetMouseX(int x - )=0; - - virtual - int - GetMouseY(int y - )= 0; - - virtual - float - GetMouseNormalizedX(int x - )=0; - - virtual - float - GetMouseNormalizedY(int y - )= 0; - - virtual - const RAS_Rect & - GetDisplayArea( - ) const = 0; - - virtual - void - SetDisplayArea(RAS_Rect *rect - ) = 0; - - /** - * Used to get canvas area within blender. - */ - virtual - RAS_Rect & - GetWindowArea( - ) = 0; - - /** - * Set the visible view-port - */ - - virtual - void - SetViewPort( - int x1, int y1, - int x2, int y2 - ) = 0; - - /** - * Update the Canvas' viewport (used when the viewport changes without using SetViewPort() - * eg: Shadow buffers and FBOs - */ - - virtual - void - UpdateViewPort( - int x1, int y1, - int x2, int y2 - ) = 0; - - /** - * Get the visible viewport - */ - virtual - const int* - GetViewPort() = 0; - - virtual - void - SetMouseState( - RAS_MouseState mousestate - )=0; - - virtual - void - SetMousePosition( - int x, - int y - )=0; - - virtual - RAS_MouseState - GetMouseState() - { - return m_mousestate; - } - - virtual - void - MakeScreenShot( - const char* filename - )=0; - - virtual void GetDisplayDimensions(int &width, int &height) = 0; - - virtual - void - ResizeWindow( - int width, - int height - )=0; - - virtual - void - SetFullScreen( - bool enable - )=0; - - virtual - bool - GetFullScreen()=0; - - - -protected: - RAS_MouseState m_mousestate; - int m_frame; /// frame number for screenshots. - TaskScheduler *m_taskscheduler; - TaskPool *m_taskpool; - - /** - * Saves screenshot data to a file. The actual compression and disk I/O is performed in - * a separate thread. - * - * @param filename name of the file, can contain "###" for sequential numbering. A copy of the string - * is made, so the pointer can be freed by the caller. - * @param dumpsx width in pixels. - * @param dumpsy height in pixels. - * @param dumprect pixel data; ownership is passed to this function, which also frees the data. - * @param im_format image format for the file; ownership is passed to this function, which also frees the data. - */ - void save_screenshot(const char *filename, int dumpsx, int dumpsy, unsigned int *dumprect, - ImageFormatData * im_format); - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_ICanvas") -#endif -}; - -#endif /* __RAS_ICANVAS_H__ */ diff --git a/source/gameengine/Rasterizer/RAS_ILightObject.h b/source/gameengine/Rasterizer/RAS_ILightObject.h deleted file mode 100644 index a3d55c925d6..00000000000 --- a/source/gameengine/Rasterizer/RAS_ILightObject.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): Mitchell Stokes - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file RAS_ILightObject.h - * \ingroup bgerast - */ - -#ifndef __RAS_LIGHTOBJECT_H__ -#define __RAS_LIGHTOBJECT_H__ - -class RAS_ICanvas; - -class KX_Camera; -class KX_Scene; - -class MT_Transform; -class MT_Matrix4x4; - -struct Image; - -class RAS_ILightObject -{ -public: - enum LightType { - LIGHT_SPOT, - LIGHT_SUN, - LIGHT_NORMAL - }; - bool m_modified; - int m_layer; - void *m_scene; - void *m_light; - - float m_energy; - float m_distance; - float m_shadowclipstart; - float m_shadowfrustumsize; - float m_shadowclipend; - float m_shadowbias; - float m_shadowbleedbias; - short m_shadowmaptype; - float m_shadowcolor[3]; - - float m_color[3]; - - float m_att1; - float m_att2; - float m_coeff_const, m_coeff_lin, m_coeff_quad; - float m_spotsize; - float m_spotblend; - - LightType m_type; - - bool m_nodiffuse; - bool m_nospecular; - bool m_glsl; - - virtual ~RAS_ILightObject() {} - virtual RAS_ILightObject* Clone() = 0; - - virtual bool HasShadowBuffer() = 0; - virtual int GetShadowBindCode() = 0; - virtual MT_Matrix4x4 GetShadowMatrix() = 0; - virtual int GetShadowLayer() = 0; - virtual void BindShadowBuffer(RAS_ICanvas *canvas, KX_Camera *cam, MT_Transform& camtrans) = 0; - virtual void UnbindShadowBuffer() = 0; - virtual Image *GetTextureImage(short texslot) = 0; - virtual void Update() = 0; -}; - -#endif /* __RAS_LIGHTOBJECT_H__ */ diff --git a/source/gameengine/Rasterizer/RAS_IOffScreen.h b/source/gameengine/Rasterizer/RAS_IOffScreen.h deleted file mode 100644 index d61a31504b8..00000000000 --- a/source/gameengine/Rasterizer/RAS_IOffScreen.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) 2015, Blender Foundation - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): Blender Foundation. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file RAS_IOffScreen.h - * \ingroup bgerast - */ - -#ifndef __RAS_OFFSCREEN_H__ -#define __RAS_OFFSCREEN_H__ - -#include "EXP_Python.h" - -class RAS_ICanvas; - -class MT_Transform; - -struct Image; - -class RAS_IOffScreen -{ -public: - enum RAS_OFS_BIND_MODE { - RAS_OFS_BIND_RENDER = 0, - RAS_OFS_BIND_READ, - }; - enum RAS_OFS_RENDER_TARGET { - RAS_OFS_RENDER_BUFFER = 0, // use render buffer as render target - RAS_OFS_RENDER_TEXTURE, // use texture as render target - }; - - int m_width; - int m_height; - int m_samples; - int m_color; // if used, holds the texture object, 0 if not used - - virtual ~RAS_IOffScreen() {} - - virtual bool Create(int width, int height, int samples, RAS_OFS_RENDER_TARGET target) = 0; - virtual void Destroy() = 0; - virtual void Bind(RAS_OFS_BIND_MODE mode) = 0; - virtual void Blit() = 0; - virtual void Unbind() = 0; - virtual void MipMap() = 0; - - virtual int GetWidth() { return m_width; } - virtual int GetHeight() { return m_height; } - virtual int GetSamples() { return m_samples; } - virtual int GetColor() { return m_color; } -}; - -#ifdef WITH_PYTHON -typedef struct { - PyObject_HEAD - RAS_IOffScreen *ofs; -} PyRASOffScreen; - -extern PyTypeObject PyRASOffScreen_Type; -#endif - -#endif /* __RAS_OFFSCREEN_H__ */ diff --git a/source/gameengine/Rasterizer/RAS_IPolygonMaterial.cpp b/source/gameengine/Rasterizer/RAS_IPolygonMaterial.cpp deleted file mode 100644 index 1d22d2debf9..00000000000 --- a/source/gameengine/Rasterizer/RAS_IPolygonMaterial.cpp +++ /dev/null @@ -1,292 +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/Rasterizer/RAS_IPolygonMaterial.cpp - * \ingroup bgerast - */ - - -#include "RAS_IPolygonMaterial.h" -#include "RAS_IRasterizer.h" - -#include "DNA_material_types.h" - -void RAS_IPolyMaterial::Initialize( - const STR_String& texname, - const STR_String& matname, - int materialindex, - int tile, - int tilexrep, - int tileyrep, - int alphablend, - bool alpha, - bool zsort, - bool light, - bool image, - struct GameSettings* game) -{ - m_texturename = texname; - m_materialname = matname; - m_materialindex = materialindex; - m_tile = tile; - m_tilexrep = tilexrep; - m_tileyrep = tileyrep; - m_alphablend = alphablend; - m_alpha = alpha; - m_zsort = zsort; - m_light = light; - m_polymatid = m_newpolymatid++; - m_flag = 0; - m_multimode = 0; - m_shininess = 35.0f; - m_specular.setValue(0.5f,0.5f,0.5f); - m_specularity = 1.0f; - m_diffuse.setValue(0.5f,0.5f,0.5f); - m_drawingmode = ConvertFaceMode(game, image); -} - -RAS_IPolyMaterial::RAS_IPolyMaterial() - : m_texturename("__Dummy_Texture_Name__"), - m_materialname("__Dummy_Material_Name__"), - m_tile(0), - m_tilexrep(0), - m_tileyrep(0), - m_drawingmode (0), - m_alphablend(0), - m_alpha(false), - m_zsort(false), - m_light(false), - m_materialindex(0), - m_polymatid(0), - m_flag(0), - m_multimode(0) -{ - m_shininess = 35.0f; - m_specular = MT_Vector3(0.5f,0.5f,0.5f); - m_specularity = 1.0f; - m_diffuse = MT_Vector3(0.5f,0.5f,0.5f); -} - -RAS_IPolyMaterial::RAS_IPolyMaterial(const STR_String& texname, - const STR_String& matname, - int materialindex, - int tile, - int tilexrep, - int tileyrep, - int alphablend, - bool alpha, - bool zsort) - : m_texturename(texname), - m_materialname(matname), - m_tile(tile), - m_tilexrep(tilexrep), - m_tileyrep(tileyrep), - m_alphablend(alphablend), - m_alpha(alpha), - m_zsort(zsort), - m_materialindex(materialindex), - m_polymatid(m_newpolymatid++), - m_flag(0), - m_multimode(0) -{ - m_shininess = 35.0f; - m_specular = MT_Vector3(0.5f,0.5f,0.5f); - m_specularity = 1.0f; - m_diffuse = MT_Vector3(0.5f,0.5f,0.5f); -} - - -bool RAS_IPolyMaterial::Equals(const RAS_IPolyMaterial& lhs) const -{ - if (m_flag &RAS_BLENDERMAT) - { - bool test = ( - this->m_multimode == lhs.m_multimode && - this->m_flag == lhs.m_flag && - this->m_drawingmode == lhs.m_drawingmode && - this->m_alphablend == lhs.m_alphablend && - this->m_texturename.hash() == lhs.m_texturename.hash() && - this->m_materialname.hash() == lhs.m_materialname.hash() - ); - - return test; - } - else - { - return ( - this->m_tile == lhs.m_tile && - this->m_tilexrep == lhs.m_tilexrep && - this->m_tileyrep == lhs.m_tileyrep && - this->m_alphablend == lhs.m_alphablend && - this->m_alpha == lhs.m_alpha && - this->m_zsort == lhs.m_zsort && - this->m_light == lhs.m_light && - this->m_drawingmode == lhs.m_drawingmode && - this->m_texturename.hash() == lhs.m_texturename.hash() && - this->m_materialname.hash() == lhs.m_materialname.hash() - ); - } -} - -int RAS_IPolyMaterial::ConvertFaceMode(struct GameSettings *game, bool image) const -{ - if (!game) return (image?GEMAT_TEX:0); - - int modefinal = 0; - - int orimode = game->face_orientation; - int alpha_blend = game->alpha_blend; - int flags = game->flag & (GEMAT_TEXT | GEMAT_BACKCULL); - - modefinal = orimode | alpha_blend | flags; - modefinal |= (image ? GEMAT_TEX : 0); - - return modefinal; -} - -void RAS_IPolyMaterial::GetMaterialRGBAColor(unsigned char *rgba) const -{ - *rgba++ = 0xFF; - *rgba++ = 0xFF; - *rgba++ = 0xFF; - *rgba++ = 0xFF; -} - -bool RAS_IPolyMaterial::Less(const RAS_IPolyMaterial& rhs) const -{ - if (Equals(rhs)) - return false; - - return m_polymatid < rhs.m_polymatid; -} - -bool RAS_IPolyMaterial::IsAlpha() const -{ - return m_alpha || m_zsort; -} - -bool RAS_IPolyMaterial::IsZSort() const -{ - return m_zsort; -} - -unsigned int RAS_IPolyMaterial::hash() const -{ - return m_texturename.hash(); -} - -int RAS_IPolyMaterial::GetDrawingMode() const -{ - return m_drawingmode; -} - -const STR_String& RAS_IPolyMaterial::GetMaterialName() const -{ - return m_materialname; -} - -dword RAS_IPolyMaterial::GetMaterialNameHash() const -{ - return m_materialname.hash(); -} - -const STR_String& RAS_IPolyMaterial::GetTextureName() const -{ - return m_texturename; -} - -int RAS_IPolyMaterial::GetMaterialIndex() const -{ - return m_materialindex; -} - -Material *RAS_IPolyMaterial::GetBlenderMaterial() const -{ - return NULL; -} - -Image *RAS_IPolyMaterial::GetBlenderImage() const -{ - return NULL; -} - -unsigned int *RAS_IPolyMaterial::GetMCol() const -{ - return NULL; -} - -Scene* RAS_IPolyMaterial::GetBlenderScene() const -{ - return NULL; -} - -void RAS_IPolyMaterial::ReleaseMaterial() -{ -} - -unsigned int RAS_IPolyMaterial::GetFlag() const -{ - return m_flag; -} - -bool RAS_IPolyMaterial::UsesLighting(RAS_IRasterizer *rasty) const -{ - bool dolights = false; - - if (m_flag & RAS_BLENDERMAT) { - dolights = (m_flag & RAS_MULTILIGHT) != 0; - } - else if (rasty->GetDrawingMode() < RAS_IRasterizer::KX_SOLID) { - /* pass */ - } - else if (rasty->GetDrawingMode() == RAS_IRasterizer::KX_SHADOW) { - /* pass */ - } - else { - dolights = m_light; - } - - return dolights; -} - -bool RAS_IPolyMaterial::CastsShadows() const -{ - return (m_flag & RAS_CASTSHADOW) != 0; -} - -bool RAS_IPolyMaterial::OnlyShadow() const -{ - return (m_flag & RAS_ONLYSHADOW) != 0; -} - -bool RAS_IPolyMaterial::UsesObjectColor() const -{ - return !(m_flag & RAS_BLENDERGLSL); -} - -unsigned int RAS_IPolyMaterial::m_newpolymatid = 0; - diff --git a/source/gameengine/Rasterizer/RAS_IPolygonMaterial.h b/source/gameengine/Rasterizer/RAS_IPolygonMaterial.h deleted file mode 100644 index 7023d305510..00000000000 --- a/source/gameengine/Rasterizer/RAS_IPolygonMaterial.h +++ /dev/null @@ -1,206 +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 RAS_IPolygonMaterial.h - * \ingroup bgerast - */ - -#ifndef __RAS_IPOLYGONMATERIAL_H__ -#define __RAS_IPOLYGONMATERIAL_H__ - -#include "STR_HashedString.h" - -#include "MT_Vector3.h" - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -class RAS_IRasterizer; -struct Material; -struct Image; -struct Scene; -class SCA_IScene; -struct GameSettings; - -enum MaterialProps -{ - RAS_ZSORT =1, - RAS_TRANSPARENT =2, - RAS_TRIANGLE =4, - RAS_MULTITEX =8, - RAS_MULTILIGHT =16, - RAS_BLENDERMAT =32, - RAS_GLSHADER =64, - RAS_AUTOGEN =128, - RAS_NORMAL =256, - RAS_DEFMULTI =512, - RAS_BLENDERGLSL =1024, - RAS_CASTSHADOW =2048, - RAS_ONLYSHADOW =4096, -}; - -/** - * Polygon Material on which the material buckets are sorted - * - */ -class RAS_IPolyMaterial -{ - //todo: remove these variables from this interface/protocol class -protected: - STR_HashedString m_texturename; - STR_HashedString m_materialname; //also needed for touchsensor - int m_tile; - int m_tilexrep,m_tileyrep; - int m_drawingmode; - int m_alphablend; - bool m_alpha; - bool m_zsort; - bool m_light; - int m_materialindex; - - unsigned int m_polymatid; - static unsigned int m_newpolymatid; - - // will move... - unsigned int m_flag;//MaterialProps - int m_multimode; // sum of values -public: - MT_Vector3 m_diffuse; - float m_shininess; - MT_Vector3 m_specular; - float m_specularity; - - /** Used to store caching information for materials. */ - typedef void* TCachingInfo; - - // care! these are taken from blender polygonflags, see file DNA_mesh_types.h for #define TF_BILLBOARD etc. - enum MaterialFlags - { - BILLBOARD_SCREENALIGNED = 512, /* GEMAT_HALO */ - BILLBOARD_AXISALIGNED = 1024, /* GEMAT_BILLBOARD */ - SHADOW =2048 /* GEMAT_SHADOW */ - }; - - RAS_IPolyMaterial(); - RAS_IPolyMaterial(const STR_String& texname, - const STR_String& matname, - int materialindex, - int tile, - int tilexrep, - int tileyrep, - int transp, - bool alpha, - bool zsort); - void Initialize(const STR_String& texname, - const STR_String& matname, - int materialindex, - int tile, - int tilexrep, - int tileyrep, - int transp, - bool alpha, - bool zsort, - bool light, - bool image, - struct GameSettings* game); - - virtual ~RAS_IPolyMaterial() {} - - /** - * Returns the caching information for this material, - * This can be used to speed up the rasterizing process. - * \return The caching information. - */ - virtual TCachingInfo GetCachingInfo(void) const { return 0; } - - /** - * Activates the material in the rasterizer. - * On entry, the cachingInfo contains info about the last activated material. - * On exit, the cachingInfo should contain updated info about this material. - * \param rasty The rasterizer in which the material should be active. - * \param cachingInfo The information about the material used to speed up rasterizing. - */ - virtual bool Activate(RAS_IRasterizer* rasty, TCachingInfo& cachingInfo) const - { - return false; - } - virtual void ActivateMeshSlot(const class RAS_MeshSlot & ms, RAS_IRasterizer* rasty) const {} - - virtual bool Equals(const RAS_IPolyMaterial& lhs) const; - bool Less(const RAS_IPolyMaterial& rhs) const; - //int GetLightLayer() const; - bool IsAlpha() const; - bool IsZSort() const; - unsigned int hash() const; - int GetDrawingMode() const; - const STR_String& GetMaterialName() const; - dword GetMaterialNameHash() const; - const STR_String& GetTextureName() const; - unsigned int GetFlag() const; - int GetMaterialIndex() const; - - virtual Material* GetBlenderMaterial() const; - virtual Image* GetBlenderImage() const; - virtual unsigned int* GetMCol() const; - virtual Scene* GetBlenderScene() const; - virtual void ReleaseMaterial(); - virtual void GetMaterialRGBAColor(unsigned char *rgba) const; - virtual bool UsesLighting(RAS_IRasterizer *rasty) const; - virtual bool UsesObjectColor() const; - virtual bool CastsShadows() const; - virtual bool OnlyShadow() const; - - virtual void Replace_IScene(SCA_IScene *val) {} /* overridden by KX_BlenderMaterial */ - - /** - * \return the equivalent drawing mode for the material settings (equivalent to old TexFace tface->mode). - */ - int ConvertFaceMode(struct GameSettings *game, bool image) const; - - /* - * PreCalculate texture gen - */ - virtual void OnConstruction() {} - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_IPolyMaterial") -#endif -}; - -inline bool operator ==( const RAS_IPolyMaterial & rhs,const RAS_IPolyMaterial & lhs) -{ - return ( rhs.Equals(lhs)); -} - -inline bool operator < ( const RAS_IPolyMaterial & lhs, const RAS_IPolyMaterial & rhs) -{ - return lhs.Less(rhs); -} - -#endif /* __RAS_IPOLYGONMATERIAL_H__ */ diff --git a/source/gameengine/Rasterizer/RAS_IRasterizer.h b/source/gameengine/Rasterizer/RAS_IRasterizer.h deleted file mode 100644 index dc92408915b..00000000000 --- a/source/gameengine/Rasterizer/RAS_IRasterizer.h +++ /dev/null @@ -1,506 +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 RAS_IRasterizer.h - * \ingroup bgerast - */ - -#ifndef __RAS_IRASTERIZER_H__ -#define __RAS_IRASTERIZER_H__ - -#ifdef _MSC_VER -# pragma warning (disable:4786) -#endif - -#include "STR_HashedString.h" - -#include "MT_CmMatrix4x4.h" -#include "MT_Matrix4x4.h" - -#include "RAS_TexVert.h" - -#include -using namespace std; - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -class RAS_ICanvas; -class RAS_IPolyMaterial; -class RAS_MeshSlot; -class RAS_ILightObject; -class SCA_IScene; -class RAS_IOffScreen; -class RAS_ISync; - -typedef vector KX_IndexArray; -typedef vector KX_VertexArray; -typedef vector vecVertexArray; -typedef vector vecIndexArrays; - -/** - * 3D rendering device context interface. - */ -class RAS_IRasterizer -{ -public: - enum RAS_TEXT_RENDER_MODE { - RAS_TEXT_RENDER_NODEF = 0, - RAS_TEXT_NORMAL, - RAS_TEXT_PADDED, - RAS_TEXT_MAX, - }; - - RAS_IRasterizer(RAS_ICanvas* canv) {}; - virtual ~RAS_IRasterizer() {}; - - /** - * Drawing types - */ - enum DrawType { - KX_BOUNDINGBOX = 1, - KX_WIREFRAME, - KX_SOLID, - KX_SHADED, - KX_TEXTURED, - KX_SHADOW, - }; - - /** - * Drawing modes - */ - - enum DrawMode { - KX_MODE_LINES = 1, - KX_MODE_TRIANGLES, - KX_MODE_QUADS, - }; - - /** - * Valid SetDepthMask parameters - */ - enum DepthMask { - KX_DEPTHMASK_ENABLED = 1, - KX_DEPTHMASK_DISABLED, - }; - - /** - */ - enum { - RAS_RENDER_3DPOLYGON_TEXT = 64, /* GEMAT_TEXT */ - KX_BACKCULL = 16, /* GEMAT_BACKCULL */ - KX_TEX = 4096, /* GEMAT_TEX */ - KX_LINES = 32768, - }; - - /** - * Stereo mode types - */ - enum StereoMode { - RAS_STEREO_NOSTEREO = 1, - RAS_STEREO_QUADBUFFERED, - RAS_STEREO_ABOVEBELOW, - RAS_STEREO_INTERLACED, - RAS_STEREO_ANAGLYPH, - RAS_STEREO_SIDEBYSIDE, - RAS_STEREO_VINTERLACE, - RAS_STEREO_DOME, - RAS_STEREO_3DTVTOPBOTTOM, - - RAS_STEREO_MAXSTEREO - }; - - /** - * Texture gen modes. - */ - enum TexCoGen { - RAS_TEXCO_GEN, /* < GPU will generate texture coordinates */ - RAS_TEXCO_ORCO, /* < Vertex coordinates (object space) */ - RAS_TEXCO_GLOB, /* < Vertex coordinates (world space) */ - RAS_TEXCO_UV, /* < UV coordinates */ - RAS_TEXCO_OBJECT, /* < Use another object's position as coordinates */ - RAS_TEXCO_LAVECTOR, /* < Light vector as coordinates */ - RAS_TEXCO_VIEW, /* < View vector as coordinates */ - RAS_TEXCO_STICKY, /* < Sticky coordinates */ - RAS_TEXCO_WINDOW, /* < Window coordinates */ - RAS_TEXCO_NORM, /* < Normal coordinates */ - RAS_TEXTANGENT, /* < */ - RAS_TEXCO_VCOL, /* < Vertex Color */ - RAS_TEXCO_DISABLE, /* < Disable this texture unit (cached) */ - }; - - /** - * Render pass identifiers for stereo. - */ - enum StereoEye { - RAS_STEREO_LEFTEYE = 1, - RAS_STEREO_RIGHTEYE, - }; - - /** - * Mipmap options - */ - enum MipmapOption { - RAS_MIPMAP_NONE, - RAS_MIPMAP_NEAREST, - RAS_MIPMAP_LINEAR, - - RAS_MIPMAP_MAX, /* Should always be last */ - }; - - /** - * SetDepthMask enables or disables writing a fragment's depth value - * to the Z buffer. - */ - virtual void SetDepthMask(DepthMask depthmask) = 0; - - /** - * SetMaterial sets the material settings for subsequent primitives - * to be rendered with. - * The material will be cached. - */ - virtual bool SetMaterial(const RAS_IPolyMaterial &mat) = 0; - - /** - * Init initializes the renderer. - */ - virtual bool Init() = 0; - - /** - * Exit cleans up the renderer. - */ - virtual void Exit() = 0; - - /** - * BeginFrame is called at the start of each frame. - */ - virtual bool BeginFrame(double time) = 0; - - /** - * ClearColorBuffer clears the color buffer. - */ - virtual void ClearColorBuffer() = 0; - - /** - * ClearDepthBuffer clears the depth buffer. - */ - virtual void ClearDepthBuffer() = 0; - - /** - * ClearCachingInfo clears the currently cached material. - */ - virtual void ClearCachingInfo(void) = 0; - - /** - * EndFrame is called at the end of each frame. - */ - virtual void EndFrame() = 0; - - /** - * SetRenderArea sets the render area from the 2d canvas. - * Returns true if only of subset of the canvas is used. - */ - virtual void SetRenderArea() = 0; - - // Stereo Functions - /** - * SetStereoMode will set the stereo mode - */ - virtual void SetStereoMode(const StereoMode stereomode) = 0; - - /** - * Stereo can be used to query if the rasterizer is in stereo mode. - * \return true if stereo mode is enabled. - */ - virtual bool Stereo() = 0; - virtual StereoMode GetStereoMode() = 0; - virtual bool InterlacedStereo() = 0; - - /** - * Sets which eye buffer subsequent primitives will be rendered to. - */ - virtual void SetEye(const StereoEye eye) = 0; - virtual StereoEye GetEye() = 0; - - /** - * Sets the distance between eyes for stereo mode. - */ - virtual void SetEyeSeparation(const float eyeseparation) = 0; - virtual float GetEyeSeparation() = 0; - - /** - * Sets the focal length for stereo mode. - */ - virtual void SetFocalLength(const float focallength) = 0; - virtual float GetFocalLength() = 0; - - /** - * Create an offscreen render buffer that can be used as target for render. - * For the time being, it is only used in VideoTexture for custom render. - */ - virtual RAS_IOffScreen *CreateOffScreen(int width, int height, int samples, int target) = 0; - - /** - * Create a sync object - * For use with offscreen render - */ - virtual RAS_ISync *CreateSync(int type) = 0; - - /** - * SwapBuffers swaps the back buffer with the front buffer. - */ - virtual void SwapBuffers() = 0; - - // Drawing Functions - /** - * IndexPrimitives: Renders primitives from mesh slot. - */ - virtual void IndexPrimitives(class RAS_MeshSlot &ms) = 0; - - /** - * IndexPrimitives_3DText will render text into the polygons. - */ - virtual void IndexPrimitives_3DText(class RAS_MeshSlot &ms, class RAS_IPolyMaterial *polymat) = 0; - - virtual void SetProjectionMatrix(MT_CmMatrix4x4 &mat) = 0; - - /* This one should become our final version, methinks. */ - /** - * Set the projection matrix for the rasterizer. This projects - * from camera coordinates to window coordinates. - * \param mat The projection matrix. - */ - virtual void SetProjectionMatrix(const MT_Matrix4x4 &mat) = 0; - - /** - * Sets the modelview matrix. - */ - virtual void SetViewMatrix(const MT_Matrix4x4 &mat, const MT_Matrix3x3 &ori, - const MT_Point3 &pos, const MT_Vector3 &scale, bool perspective) = 0; - - /** - */ - virtual const MT_Point3& GetCameraPosition() = 0; - virtual bool GetCameraOrtho() = 0; - - /** - * Fog - */ - virtual void SetFog(short type, float start, float dist, float intensity, float color[3]) = 0; - virtual void DisplayFog() = 0; - virtual void EnableFog(bool enable) = 0; - - virtual void SetBackColor(float color[3]) = 0; - - /** - * \param drawingmode = KX_BOUNDINGBOX, KX_WIREFRAME, KX_SOLID, KX_SHADED or KX_TEXTURED. - */ - virtual void SetDrawingMode(int drawingmode) = 0; - - /** - * \return the current drawing mode: KX_BOUNDINGBOX, KX_WIREFRAME, KX_SOLID, KX_SHADED or KX_TEXTURED. - */ - virtual int GetDrawingMode() = 0; - - /** - * Sets face culling - */ - virtual void SetCullFace(bool enable) = 0; - - /** - * Sets wireframe mode. - */ - virtual void SetLines(bool enable) = 0; - - /** - */ - virtual double GetTime() = 0; - - /** - * Generates a projection matrix from the specified frustum. - * \param left the left clipping plane - * \param right the right clipping plane - * \param bottom the bottom clipping plane - * \param top the top clipping plane - * \param frustnear the near clipping plane - * \param frustfar the far clipping plane - * \return a 4x4 matrix representing the projection transform. - */ - virtual MT_Matrix4x4 GetFrustumMatrix( - float left, float right, float bottom, float top, - float frustnear, float frustfar, - float focallength = 0.0f, bool perspective = true) = 0; - - /** - * Generates a orthographic projection matrix from the specified frustum. - * \param left the left clipping plane - * \param right the right clipping plane - * \param bottom the bottom clipping plane - * \param top the top clipping plane - * \param frustnear the near clipping plane - * \param frustfar the far clipping plane - * \return a 4x4 matrix representing the projection transform. - */ - virtual MT_Matrix4x4 GetOrthoMatrix( - float left, float right, float bottom, float top, - float frustnear, float frustfar) = 0; - - /** - * Sets the specular color component of the lighting equation. - */ - virtual void SetSpecularity(float specX, float specY, float specZ, float specval) = 0; - - /** - * Sets the specular exponent component of the lighting equation. - */ - virtual void SetShinyness(float shiny) = 0; - - /** - * Sets the diffuse color component of the lighting equation. - */ - virtual void SetDiffuse(float difX,float difY, float difZ, float diffuse) = 0; - - /** - * Sets the emissive color component of the lighting equation. - */ - virtual void SetEmissive(float eX, float eY, float eZ, float e) = 0; - - virtual void SetAmbientColor(float color[3]) = 0; - virtual void SetAmbient(float factor) = 0; - - /** - * Sets a polygon offset. z depth will be: z1 = mult*z0 + add - */ - virtual void SetPolygonOffset(float mult, float add) = 0; - - virtual void DrawDebugLine(SCA_IScene *scene, const MT_Vector3 &from, const MT_Vector3 &to, const MT_Vector3& color) = 0; - virtual void DrawDebugCircle(SCA_IScene *scene, const MT_Vector3 ¢er, const MT_Scalar radius, - const MT_Vector3 &color, const MT_Vector3 &normal, int nsector) = 0; - virtual void FlushDebugShapes(SCA_IScene *scene) = 0; - - virtual void SetTexCoordNum(int num) = 0; - virtual void SetAttribNum(int num) = 0; - virtual void SetTexCoord(TexCoGen coords, int unit) = 0; - virtual void SetAttrib(TexCoGen coords, int unit, int layer = 0) = 0; - - virtual const MT_Matrix4x4 &GetViewMatrix() const = 0; - virtual const MT_Matrix4x4 &GetViewInvMatrix() const = 0; - - virtual bool QueryLists() { return false; } - virtual bool QueryArrays() { return false; } - - virtual void EnableMotionBlur(float motionblurvalue) = 0; - virtual void DisableMotionBlur() = 0; - - virtual float GetMotionBlurValue() = 0; - virtual int GetMotionBlurState() = 0; - virtual void SetMotionBlurState(int newstate) = 0; - - virtual void SetAlphaBlend(int alphablend) = 0; - virtual void SetFrontFace(bool ccw) = 0; - - virtual void SetAnisotropicFiltering(short level) = 0; - virtual short GetAnisotropicFiltering() = 0; - - virtual void SetMipmapping(MipmapOption val) = 0; - virtual MipmapOption GetMipmapping() = 0; - - virtual void SetUsingOverrideShader(bool val) = 0; - virtual bool GetUsingOverrideShader() = 0; - - /** - * Render Tools - */ - virtual void applyTransform(float *oglmatrix, int drawingmode) = 0; - - /** - * Renders 2D boxes. - * \param xco Position on the screen (origin in lower left corner). - * \param yco Position on the screen (origin in lower left corner). - * \param width Width of the canvas to draw to. - * \param height Height of the canvas to draw to. - * \param percentage Percentage of bar. - */ - virtual void RenderBox2D(int xco, int yco, int width, int height, float percentage) = 0; - - /** - * Renders 3D text string using BFL. - * \param fontid The id of the font. - * \param text The string to render. - * \param size The size of the text. - * \param dpi The resolution of the text. - * \param color The color of the object. - * \param mat The Matrix of the text object. - * \param aspect A scaling factor to compensate for the size. - */ - virtual void RenderText3D( - int fontid, const char *text, int size, int dpi, - const float color[4], const float mat[16], float aspect) = 0; - - /** - * Renders 2D text string. - * \param mode The type of text - * \param text The string to render. - * \param xco Position on the screen (origin in lower left corner). - * \param yco Position on the screen (origin in lower left corner). - * \param width Width of the canvas to draw to. - * \param height Height of the canvas to draw to. - */ - virtual void RenderText2D( - RAS_TEXT_RENDER_MODE mode, const char *text, - int xco, int yco, int width, int height) = 0; - - virtual void ProcessLighting(bool uselights, const MT_Transform &trans) = 0; - - virtual void PushMatrix() = 0; - - virtual void PopMatrix() = 0; - - virtual RAS_ILightObject *CreateLight() = 0; - - virtual void AddLight(RAS_ILightObject *lightobject) = 0; - - virtual void RemoveLight(RAS_ILightObject *lightobject) = 0; - - virtual void MotionBlur() = 0; - - virtual void SetClientObject(void *obj) = 0; - - virtual void SetAuxilaryClientInfo(void *inf) = 0; - - /** - * Prints information about what the hardware supports. - */ - virtual void PrintHardwareInfo() = 0; - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_IRasterizer") -#endif -}; - -#endif /* __RAS_IRASTERIZER_H__ */ diff --git a/source/gameengine/Rasterizer/RAS_ISync.h b/source/gameengine/Rasterizer/RAS_ISync.h deleted file mode 100644 index 7e34172c2a3..00000000000 --- a/source/gameengine/Rasterizer/RAS_ISync.h +++ /dev/null @@ -1,48 +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) 2015, Blender Foundation - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): Blender Foundation. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -/** \file RAS_ISync.h - * \ingroup bgerast - */ - -#ifndef __RAS_ISYNC_H__ -#define __RAS_ISYNC_H__ - -class RAS_ISync -{ -public: - enum RAS_SYNC_TYPE { - RAS_SYNC_TYPE_FENCE = 0, - }; - virtual ~RAS_ISync() {} - - virtual bool Create(RAS_SYNC_TYPE type) = 0; - virtual void Destroy() = 0; - virtual void Wait() = 0; -}; - -#endif /* __RAS_ISYNC_H__ */ diff --git a/source/gameengine/Rasterizer/RAS_MaterialBucket.cpp b/source/gameengine/Rasterizer/RAS_MaterialBucket.cpp deleted file mode 100644 index 9cd8f77adfd..00000000000 --- a/source/gameengine/Rasterizer/RAS_MaterialBucket.cpp +++ /dev/null @@ -1,679 +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/Rasterizer/RAS_MaterialBucket.cpp - * \ingroup bgerast - */ - - -#include "RAS_MaterialBucket.h" - -#ifdef _MSC_VER -# pragma warning (disable:4786) -#endif - -#ifdef WIN32 -#include -#endif // WIN32 - -#include "RAS_IPolygonMaterial.h" -#include "RAS_TexVert.h" -#include "RAS_IRasterizer.h" -#include "RAS_MeshObject.h" -#include "RAS_Deformer.h" // __NLA - -/* mesh slot */ - -RAS_MeshSlot::RAS_MeshSlot() : SG_QList() -{ - m_clientObj = NULL; - m_pDeformer = NULL; - m_OpenGLMatrix = NULL; - m_mesh = NULL; - m_bucket = NULL; - m_bVisible = false; - m_bCulled = true; - m_bObjectColor = false; - m_RGBAcolor = MT_Vector4(0.0f, 0.0f, 0.0f, 0.0f); - m_DisplayList = NULL; - m_bDisplayList = true; - m_joinSlot = NULL; - m_pDerivedMesh = NULL; -} - -RAS_MeshSlot::~RAS_MeshSlot() -{ - RAS_DisplayArrayList::iterator it; - -#ifdef USE_SPLIT - Split(true); - - while (m_joinedSlots.size()) - m_joinedSlots.front()->Split(true); -#endif - - for (it=m_displayArrays.begin(); it!=m_displayArrays.end(); it++) { - (*it)->m_users--; - if ((*it)->m_users == 0) - delete *it; - } - - if (m_DisplayList) { - m_DisplayList->Release(); - m_DisplayList = NULL; - } -} - -RAS_MeshSlot::RAS_MeshSlot(const RAS_MeshSlot& slot) : SG_QList() -{ - RAS_DisplayArrayList::iterator it; - - m_clientObj = NULL; - m_pDeformer = NULL; - m_pDerivedMesh = NULL; - m_OpenGLMatrix = NULL; - m_mesh = slot.m_mesh; - m_bucket = slot.m_bucket; - m_bVisible = slot.m_bVisible; - m_bCulled = slot.m_bCulled; - m_bObjectColor = slot.m_bObjectColor; - m_RGBAcolor = slot.m_RGBAcolor; - m_DisplayList = NULL; - m_bDisplayList = slot.m_bDisplayList; - m_joinSlot = NULL; - m_currentArray = slot.m_currentArray; - m_displayArrays = slot.m_displayArrays; - m_joinedSlots = slot.m_joinedSlots; - - m_startarray = slot.m_startarray; - m_startvertex = slot.m_startvertex; - m_startindex = slot.m_startindex; - m_endarray = slot.m_endarray; - m_endvertex = slot.m_endvertex; - m_endindex = slot.m_endindex; - - for (it=m_displayArrays.begin(); it!=m_displayArrays.end(); it++) { - // don't copy display arrays for now because it breaks python - // access to vertices, but we'll need a solution if we want to - // join display arrays for reducing draw calls. - //*it = new RAS_DisplayArray(**it); - //(*it)->m_users = 1; - - (*it)->m_users++; - } -} - -void RAS_MeshSlot::init(RAS_MaterialBucket *bucket, int numverts) -{ - m_bucket = bucket; - - SetDisplayArray(numverts); - - m_startarray = 0; - m_startvertex = 0; - m_startindex = 0; - m_endarray = 0; - m_endvertex = 0; - m_endindex = 0; -} - -void RAS_MeshSlot::begin(RAS_MeshSlot::iterator& it) -{ - int startvertex, endvertex; - int startindex, endindex; - - it.array = m_displayArrays.empty() ? NULL : m_displayArrays[m_startarray]; - - if (it.array == NULL || it.array->m_index.size() == 0 || it.array->m_vertex.size() == 0) { - it.array = NULL; - it.vertex = NULL; - it.index = NULL; - it.startvertex = 0; - it.endvertex = 0; - it.totindex = 0; - } - else { - startvertex = m_startvertex; - endvertex = (m_startarray == m_endarray)? m_endvertex: it.array->m_vertex.size(); - startindex = m_startindex; - endindex = (m_startarray == m_endarray)? m_endindex: it.array->m_index.size(); - - it.vertex = &it.array->m_vertex[0]; - it.index = &it.array->m_index[startindex]; - it.startvertex = startvertex; - it.endvertex = endvertex; - it.totindex = endindex-startindex; - it.arraynum = m_startarray; - } -} - -void RAS_MeshSlot::next(RAS_MeshSlot::iterator& it) -{ - int startvertex, endvertex; - int startindex, endindex; - - if (it.arraynum == (size_t)m_endarray) { - it.array = NULL; - it.vertex = NULL; - it.index = NULL; - it.startvertex = 0; - it.endvertex = 0; - it.totindex = 0; - } - else { - it.arraynum++; - it.array = m_displayArrays[it.arraynum]; - - startindex = 0; - endindex = (it.arraynum == (size_t)m_endarray)? m_endindex: it.array->m_index.size(); - startvertex = 0; - endvertex = (it.arraynum == (size_t)m_endarray)? m_endvertex: it.array->m_vertex.size(); - - it.vertex = &it.array->m_vertex[0]; - it.index = &it.array->m_index[startindex]; - it.startvertex = startvertex; - it.endvertex = endvertex; - it.totindex = endindex-startindex; - } -} - -bool RAS_MeshSlot::end(RAS_MeshSlot::iterator& it) -{ - return (it.array == NULL); -} - -RAS_DisplayArray *RAS_MeshSlot::CurrentDisplayArray() -{ - return m_currentArray; -} - -void RAS_MeshSlot::SetDisplayArray(int numverts) -{ - RAS_DisplayArrayList::iterator it; - RAS_DisplayArray *darray = NULL; - - for (it=m_displayArrays.begin(); it!=m_displayArrays.end(); it++) { - darray = *it; - - if (darray->m_type == numverts) { - if (darray->m_index.size()+numverts >= RAS_DisplayArray::BUCKET_MAX_INDEX) - darray = NULL; - else if (darray->m_vertex.size()+numverts >= RAS_DisplayArray::BUCKET_MAX_VERTEX) - darray = NULL; - else - break; - } - else - darray = NULL; - } - - if (!darray) { - darray = new RAS_DisplayArray(); - darray->m_users = 1; - - if (numverts == 2) darray->m_type = RAS_DisplayArray::LINE; - else if (numverts == 3) darray->m_type = RAS_DisplayArray::TRIANGLE; - else darray->m_type = RAS_DisplayArray::QUAD; - - m_displayArrays.push_back(darray); - - if (numverts == 2) - darray->m_type = RAS_DisplayArray::LINE; - else if (numverts == 3) - darray->m_type = RAS_DisplayArray::TRIANGLE; - else if (numverts == 4) - darray->m_type = RAS_DisplayArray::QUAD; - - m_endarray = m_displayArrays.size()-1; - m_endvertex = 0; - m_endindex = 0; - } - - m_currentArray = darray; -} - -void RAS_MeshSlot::AddPolygon(int numverts) -{ - SetDisplayArray(numverts); -} - -int RAS_MeshSlot::AddVertex(const RAS_TexVert& tv) -{ - RAS_DisplayArray *darray; - int offset; - - darray = m_currentArray; - darray->m_vertex.push_back(tv); - offset = darray->m_vertex.size()-1; - - if (darray == m_displayArrays[m_endarray]) - m_endvertex++; - - return offset; -} - -void RAS_MeshSlot::AddPolygonVertex(int offset) -{ - RAS_DisplayArray *darray; - - darray = m_currentArray; - darray->m_index.push_back(offset); - - if (darray == m_displayArrays[m_endarray]) - m_endindex++; -} - -void RAS_MeshSlot::UpdateDisplayArraysOffset() -{ - unsigned int offset = 0; - for (unsigned short i = 0; i < m_displayArrays.size(); ++i) { - RAS_DisplayArray *darray = m_displayArrays[i]; - darray->m_offset = offset; - offset += darray->m_vertex.size(); - } -} - -void RAS_MeshSlot::SetDeformer(RAS_Deformer* deformer) -{ - if (deformer && m_pDeformer != deformer) { - RAS_DisplayArrayList::iterator it; - if (deformer->ShareVertexArray()) { - // this deformer uses the base vertex array, first release the current ones - for (it=m_displayArrays.begin(); it!=m_displayArrays.end(); it++) { - (*it)->m_users--; - if ((*it)->m_users == 0) - delete *it; - } - m_displayArrays.clear(); - // then hook to the base ones - RAS_MeshMaterial *mmat = m_mesh->GetMeshMaterial(m_bucket->GetPolyMaterial()); - if (mmat && mmat->m_baseslot) { - m_displayArrays = mmat->m_baseslot->m_displayArrays; - for (it=m_displayArrays.begin(); it!=m_displayArrays.end(); it++) { - (*it)->m_users++; - } - } - } - else { - // no sharing - // we create local copy of RAS_DisplayArray when we have a deformer: - // this way we can avoid conflict between the vertex cache of duplicates - for (it=m_displayArrays.begin(); it!=m_displayArrays.end(); it++) { - if (deformer->UseVertexArray()) { - // the deformer makes use of vertex array, make sure we have our local copy - if ((*it)->m_users > 1) { - // only need to copy if there are other users - // note that this is the usual case as vertex arrays are held by the material base slot - RAS_DisplayArray *newarray = new RAS_DisplayArray(*(*it)); - newarray->m_users = 1; - (*it)->m_users--; - *it = newarray; - } - } else { - // the deformer is not using vertex array (Modifier), release them - (*it)->m_users--; - if ((*it)->m_users == 0) - delete *it; - } - } - if (!deformer->UseVertexArray()) { - m_displayArrays.clear(); - m_startarray = 0; - m_startvertex = 0; - m_startindex = 0; - m_endarray = 0; - m_endvertex = 0; - m_endindex = 0; - } - } - } - m_pDeformer = deformer; -} - -bool RAS_MeshSlot::Equals(RAS_MeshSlot *target) -{ - if (!m_OpenGLMatrix || !target->m_OpenGLMatrix) - return false; - if (m_pDeformer || target->m_pDeformer) - return false; - if (m_bVisible != target->m_bVisible) - return false; - if (m_bObjectColor != target->m_bObjectColor) - return false; - if (m_bObjectColor && !(m_RGBAcolor == target->m_RGBAcolor)) - return false; - - return true; -} - -bool RAS_MeshSlot::Join(RAS_MeshSlot *target, MT_Scalar distance) -{ - RAS_DisplayArrayList::iterator it; - iterator mit; - size_t i; - - // verify if we can join - if (m_joinSlot || (m_joinedSlots.empty() == false) || target->m_joinSlot) - return false; - - if (!Equals(target)) - return false; - - MT_Vector3 co(&m_OpenGLMatrix[12]); - MT_Vector3 targetco(&target->m_OpenGLMatrix[12]); - - if ((co - targetco).length() > distance) - return false; - - MT_Matrix4x4 mat(m_OpenGLMatrix); - MT_Matrix4x4 targetmat(target->m_OpenGLMatrix); - targetmat.invert(); - - MT_Matrix4x4 transform = targetmat*mat; - - // m_mesh, clientobj - m_joinSlot = target; - m_joinInvTransform = transform; - m_joinInvTransform.invert(); - target->m_joinedSlots.push_back(this); - - MT_Matrix4x4 ntransform = m_joinInvTransform.transposed(); - ntransform[0][3] = ntransform[1][3] = ntransform[2][3] = 0.0f; - - for (begin(mit); !end(mit); next(mit)) - for (i=mit.startvertex; im_displayArrays.reserve(target->m_displayArrays.size() + m_displayArrays.size()); - - for (it=m_displayArrays.begin(); it!=m_displayArrays.end(); it++) { - target->m_displayArrays.push_back(*it); - target->m_endarray++; - target->m_endvertex = target->m_displayArrays.back()->m_vertex.size(); - target->m_endindex = target->m_displayArrays.back()->m_index.size(); - } - - if (m_DisplayList) { - m_DisplayList->Release(); - m_DisplayList = NULL; - } - if (target->m_DisplayList) { - target->m_DisplayList->Release(); - target->m_DisplayList = NULL; - } - - return true; -#if 0 - return false; -#endif -} - -bool RAS_MeshSlot::Split(bool force) -{ - list::iterator jit; - RAS_MeshSlot *target = m_joinSlot; - RAS_DisplayArrayList::iterator it, jt; - iterator mit; - size_t i, found0 = 0, found1 = 0; - - if (target && (force || !Equals(target))) { - m_joinSlot = NULL; - - for (jit=target->m_joinedSlots.begin(); jit!=target->m_joinedSlots.end(); jit++) { - if (*jit == this) { - target->m_joinedSlots.erase(jit); - found0 = 1; - break; - } - } - - if (!found0) - abort(); - - for (it=m_displayArrays.begin(); it!=m_displayArrays.end(); it++) { - found1 = 0; - for (jt=target->m_displayArrays.begin(); jt!=target->m_displayArrays.end(); jt++) { - if (*jt == *it) { - target->m_displayArrays.erase(jt); - target->m_endarray--; - found1 = 1; - break; - } - } - - if (!found1) - abort(); - } - - if (target->m_displayArrays.empty() == false) { - target->m_endvertex = target->m_displayArrays.back()->m_vertex.size(); - target->m_endindex = target->m_displayArrays.back()->m_index.size(); - } - else { - target->m_endvertex = 0; - target->m_endindex = 0; - } - - MT_Matrix4x4 ntransform = m_joinInvTransform.inverse().transposed(); - ntransform[0][3] = ntransform[1][3] = ntransform[2][3] = 0.0f; - - for (begin(mit); !end(mit); next(mit)) - for (i=mit.startvertex; im_DisplayList) { - target->m_DisplayList->Release(); - target->m_DisplayList = NULL; - } - - return true; - } - - return false; -} - - -#ifdef USE_SPLIT -bool RAS_MeshSlot::IsCulled() -{ - if (m_joinSlot) - return true; - if (!m_bCulled) - return false; - list::iterator it; - for (it=m_joinedSlots.begin(); it!=m_joinedSlots.end(); it++) - if (!(*it)->m_bCulled) - return false; - return true; -} -#endif - -/* material bucket sorting */ - -struct RAS_MaterialBucket::less -{ - bool operator()(const RAS_MaterialBucket* x, const RAS_MaterialBucket* y) const - { - return *x->GetPolyMaterial() < *y->GetPolyMaterial(); - } -}; - -/* material bucket */ - -RAS_MaterialBucket::RAS_MaterialBucket(RAS_IPolyMaterial* mat) -{ - m_material = mat; -} - -RAS_MaterialBucket::~RAS_MaterialBucket() -{ -} - -RAS_IPolyMaterial* RAS_MaterialBucket::GetPolyMaterial() const -{ - return m_material; -} - -bool RAS_MaterialBucket::IsAlpha() const -{ - return (m_material->IsAlpha()); -} - -bool RAS_MaterialBucket::IsZSort() const -{ - return (m_material->IsZSort()); -} - -RAS_MeshSlot* RAS_MaterialBucket::AddMesh(int numverts) -{ - RAS_MeshSlot *ms; - - m_meshSlots.push_back(RAS_MeshSlot()); - - ms = &m_meshSlots.back(); - ms->init(this, numverts); - - return ms; -} - -RAS_MeshSlot* RAS_MaterialBucket::CopyMesh(RAS_MeshSlot *ms) -{ - m_meshSlots.push_back(RAS_MeshSlot(*ms)); - - return &m_meshSlots.back(); -} - -void RAS_MaterialBucket::RemoveMesh(RAS_MeshSlot* ms) -{ - list::iterator it; - - for (it=m_meshSlots.begin(); it!=m_meshSlots.end(); it++) { - if (&*it == ms) { - m_meshSlots.erase(it); - return; - } - } -} - -list::iterator RAS_MaterialBucket::msBegin() -{ - return m_meshSlots.begin(); -} - -list::iterator RAS_MaterialBucket::msEnd() -{ - return m_meshSlots.end(); -} - -bool RAS_MaterialBucket::ActivateMaterial(const MT_Transform& cameratrans, RAS_IRasterizer* rasty) -{ - bool uselights; - - if (rasty->GetDrawingMode() == RAS_IRasterizer::KX_SHADOW && !m_material->CastsShadows()) - return false; - - if (rasty->GetDrawingMode() != RAS_IRasterizer::KX_SHADOW && m_material->OnlyShadow()) - return false; - - if (!rasty->SetMaterial(*m_material)) - return false; - - uselights= m_material->UsesLighting(rasty); - rasty->ProcessLighting(uselights, cameratrans); - - return true; -} - -void RAS_MaterialBucket::RenderMeshSlot(const MT_Transform& cameratrans, RAS_IRasterizer* rasty, RAS_MeshSlot &ms) -{ - m_material->ActivateMeshSlot(ms, rasty); - - if (ms.m_pDeformer) - { - if (ms.m_pDeformer->Apply(m_material)) - ms.m_mesh->SetMeshModified(true); - // KX_ReInstanceShapeFromMesh(ms.m_mesh); // Recompute the physics mesh. (Can't call KX_* from RAS_) - } - - if (IsZSort() && rasty->GetDrawingMode() >= RAS_IRasterizer::KX_SOLID) - ms.m_mesh->SortPolygons(ms, cameratrans*MT_Transform(ms.m_OpenGLMatrix)); - - rasty->PushMatrix(); - if (!ms.m_pDeformer || !ms.m_pDeformer->SkipVertexTransform()) - { - rasty->applyTransform(ms.m_OpenGLMatrix,m_material->GetDrawingMode()); - } - - if (rasty->QueryLists()) - if (ms.m_DisplayList) - ms.m_DisplayList->SetModified(ms.m_mesh->MeshModified()); - - // verify if we can use display list, not for deformed object, and - // also don't create a new display list when drawing shadow buffers, - // then it won't have texture coordinates for actual drawing. also - // for zsort we can't make a display list, since the polygon order - // changes all the time. - if (ms.m_pDeformer && ms.m_pDeformer->IsDynamic()) - ms.m_bDisplayList = false; - else if (!ms.m_DisplayList && rasty->GetDrawingMode() == RAS_IRasterizer::KX_SHADOW) - ms.m_bDisplayList = false; - else if (IsZSort()) - ms.m_bDisplayList = false; - else if (m_material->UsesObjectColor() && ms.m_bObjectColor) - ms.m_bDisplayList = false; - else - ms.m_bDisplayList = true; - - if (m_material->GetDrawingMode() & RAS_IRasterizer::RAS_RENDER_3DPOLYGON_TEXT) { - // for text drawing using faces - rasty->IndexPrimitives_3DText(ms, m_material); - } - else { - rasty->IndexPrimitives(ms); - } - - rasty->PopMatrix(); -} - -void RAS_MaterialBucket::Optimize(MT_Scalar distance) -{ - /* TODO: still have to check before this works correct: - * - lightlayer, frontface, text, billboard - * - make it work with physics */ - -#if 0 - list::iterator it; - list::iterator jt; - - // greed joining on all following buckets - for (it=m_meshSlots.begin(); it!=m_meshSlots.end(); it++) - for (jt=it, jt++; jt!=m_meshSlots.end(); jt++) - jt->Join(&*it, distance); -#endif -} - diff --git a/source/gameengine/Rasterizer/RAS_MaterialBucket.h b/source/gameengine/Rasterizer/RAS_MaterialBucket.h deleted file mode 100644 index 75cc382c78c..00000000000 --- a/source/gameengine/Rasterizer/RAS_MaterialBucket.h +++ /dev/null @@ -1,267 +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 RAS_MaterialBucket.h - * \ingroup bgerast - */ - -#ifndef __RAS_MATERIALBUCKET_H__ -#define __RAS_MATERIALBUCKET_H__ - -#include "RAS_TexVert.h" -#include "CTR_Map.h" -#include "SG_QList.h" - -#include "MT_Transform.h" -#include "MT_Matrix4x4.h" - -#include -#include -#include - -class RAS_MaterialBucket; -struct DerivedMesh; -class CTR_HashedPtr; -class RAS_Deformer; -class RAS_IPolyMaterial; -class RAS_IRasterizer; -class RAS_MeshObject; - -using namespace std; - -/* Display List Slot */ - -class KX_ListSlot -{ -protected: - int m_refcount; -public: - KX_ListSlot() { m_refcount = 1; } - virtual ~KX_ListSlot() {} - virtual int Release() { - if (--m_refcount > 0) - return m_refcount; - delete this; - return 0; - } - virtual KX_ListSlot* AddRef() { - m_refcount++; - return this; - } - virtual void SetModified(bool mod)=0; -}; - -/* An array with data used for OpenGL drawing */ - -class RAS_DisplayArray -{ -public: - /** The offset relation to the previous RAS_DisplayArray. - * For the user vertex are one big list but in C++ source - * it's two different lists if we use quads and triangles. - * So to fix that we add an offset. - * This value is set in UpdateDisplayArraysOffset(). - */ - unsigned int m_offset; - vector m_vertex; - vector m_index; - /* LINE currently isn't used */ - enum { LINE = 2, TRIANGLE = 3, QUAD = 4 } m_type; - //RAS_MeshSlot *m_origSlot; - - /* Number of RAS_MeshSlot using this array */ - int m_users; - - enum { BUCKET_MAX_INDEX = 65535 }; - enum { BUCKET_MAX_VERTEX = 65535 }; -}; - -/* Entry of a RAS_MeshObject into RAS_MaterialBucket */ -typedef std::vector RAS_DisplayArrayList; - -// The QList is used to link the mesh slots to the object -// The DList is used to link the visible mesh slots to the material bucket -class RAS_MeshSlot : public SG_QList -{ - friend class RAS_ListRasterizer; -private: - // indices into display arrays - int m_startarray; - int m_endarray; - int m_startindex; - int m_endindex; - int m_startvertex; - int m_endvertex; - RAS_DisplayArrayList m_displayArrays; - - // for construction only - RAS_DisplayArray* m_currentArray; - -public: - // for rendering - RAS_MaterialBucket* m_bucket; - RAS_MeshObject* m_mesh; - void* m_clientObj; - RAS_Deformer* m_pDeformer; - DerivedMesh* m_pDerivedMesh; - float* m_OpenGLMatrix; - // visibility - bool m_bVisible; - bool m_bCulled; - // object color - bool m_bObjectColor; - MT_Vector4 m_RGBAcolor; - // display lists - KX_ListSlot* m_DisplayList; - bool m_bDisplayList; - // joined mesh slots - RAS_MeshSlot* m_joinSlot; - MT_Matrix4x4 m_joinInvTransform; - list m_joinedSlots; - - RAS_MeshSlot(); - RAS_MeshSlot(const RAS_MeshSlot& slot); - virtual ~RAS_MeshSlot(); - - void init(RAS_MaterialBucket *bucket, int numverts); - - struct iterator { - RAS_DisplayArray *array; - RAS_TexVert *vertex; - unsigned short *index; - size_t startvertex; - size_t endvertex; - size_t totindex; - size_t arraynum; - }; - - void begin(iterator& it); - void next(iterator& it); - bool end(iterator& it); - - /* used during construction */ - void SetDisplayArray(int numverts); - RAS_DisplayArray *CurrentDisplayArray(); - void SetDeformer(RAS_Deformer* deformer); - - void AddPolygon(int numverts); - int AddVertex(const RAS_TexVert& tv); - void AddPolygonVertex(int offset); - - /// Update offset of each display array - void UpdateDisplayArraysOffset(); - - /* optimization */ - bool Split(bool force=false); - bool Join(RAS_MeshSlot *target, MT_Scalar distance); - bool Equals(RAS_MeshSlot *target); -#ifdef USE_SPLIT - bool IsCulled(); -#else - bool IsCulled() { return m_bCulled; } -#endif - void SetCulled(bool culled) { m_bCulled = culled; } - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_MeshSlot") -#endif -}; - -/* Used by RAS_MeshObject, to point to it's slots in a bucket */ - -class RAS_MeshMaterial -{ -public: - RAS_MeshSlot *m_baseslot; - class RAS_MaterialBucket *m_bucket; - - /* the KX_GameObject is used as a key here */ - CTR_Map m_slots; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_MeshMaterial") -#endif -}; - -/* Contains a list of display arrays with the same material, - * and a mesh slot for each mesh that uses display arrays in - * this bucket */ - -class RAS_MaterialBucket -{ -public: - RAS_MaterialBucket(RAS_IPolyMaterial* mat); - virtual ~RAS_MaterialBucket(); - - /* Bucket Sorting */ - struct less; - typedef set Set; - - /* Material Properties */ - RAS_IPolyMaterial* GetPolyMaterial() const; - bool IsAlpha() const; - bool IsZSort() const; - - /* Rendering */ - bool ActivateMaterial(const MT_Transform& cameratrans, RAS_IRasterizer* rasty); - void RenderMeshSlot(const MT_Transform& cameratrans, RAS_IRasterizer* rasty, RAS_MeshSlot &ms); - - /* Mesh Slot Access */ - list::iterator msBegin(); - list::iterator msEnd(); - - class RAS_MeshSlot* AddMesh(int numverts); - class RAS_MeshSlot* CopyMesh(class RAS_MeshSlot *ms); - void RemoveMesh(class RAS_MeshSlot* ms); - void Optimize(MT_Scalar distance); - void ActivateMesh(RAS_MeshSlot* slot) - { - m_activeMeshSlotsHead.AddBack(slot); - } - SG_DList& GetActiveMeshSlots() - { - return m_activeMeshSlotsHead; - } - RAS_MeshSlot* GetNextActiveMeshSlot() - { - return (RAS_MeshSlot*)m_activeMeshSlotsHead.Remove(); - } - -private: - list m_meshSlots; // all the mesh slots - RAS_IPolyMaterial* m_material; - SG_DList m_activeMeshSlotsHead; // only those which must be rendered - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_MaterialBucket") -#endif -}; - -#endif /* __RAS_MATERIAL_BUCKET */ diff --git a/source/gameengine/Rasterizer/RAS_MeshObject.cpp b/source/gameengine/Rasterizer/RAS_MeshObject.cpp deleted file mode 100644 index 4360464ed32..00000000000 --- a/source/gameengine/Rasterizer/RAS_MeshObject.cpp +++ /dev/null @@ -1,573 +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/Rasterizer/RAS_MeshObject.cpp - * \ingroup bgerast - */ - -#include "DNA_key_types.h" -#include "DNA_mesh_types.h" - -#include "CTR_HashedPtr.h" - -#include "RAS_MeshObject.h" -#include "RAS_Polygon.h" -#include "RAS_IPolygonMaterial.h" -#include "RAS_Deformer.h" -#include "MT_Point3.h" - -#include - - -/* polygon sorting */ - -struct RAS_MeshObject::polygonSlot -{ - float m_z; - int m_index[4]; - - polygonSlot() {} - - /* pnorm is the normal from the plane equation that the distance from is - * used to sort again. */ - void get(const RAS_TexVert *vertexarray, const unsigned short *indexarray, - int offset, int nvert, const MT_Vector3& pnorm) - { - MT_Vector3 center(0, 0, 0); - int i; - - for (i=0; i b.m_z; - } -}; - -/* mesh object */ - -STR_String RAS_MeshObject::s_emptyname = ""; - -RAS_MeshObject::RAS_MeshObject(Mesh* mesh) - : m_bModified(true), - m_bMeshModified(true), - m_mesh(mesh) -{ - if (m_mesh && m_mesh->key) - { - KeyBlock *kb; - int count=0; - // initialize weight cache for shape objects - // count how many keys in this mesh - for (kb= (KeyBlock *)m_mesh->key->block.first; kb; kb= (KeyBlock *)kb->next) - count++; - m_cacheWeightIndex.resize(count,-1); - } -} - -RAS_MeshObject::~RAS_MeshObject() -{ - vector::iterator it; - - for (it=m_Polygons.begin(); it!=m_Polygons.end(); it++) - delete (*it); - - m_sharedvertex_map.clear(); - m_Polygons.clear(); - m_materials.clear(); -} - -bool RAS_MeshObject::MeshModified() -{ - return m_bMeshModified; -} - -//unsigned int RAS_MeshObject::GetLightLayer() -//{ -// return m_lightlayer; -//} - - - -int RAS_MeshObject::NumMaterials() -{ - return m_materials.size(); -} - -const STR_String& RAS_MeshObject::GetMaterialName(unsigned int matid) -{ - RAS_MeshMaterial* mmat = GetMeshMaterial(matid); - - if (mmat) - return mmat->m_bucket->GetPolyMaterial()->GetMaterialName(); - - return s_emptyname; -} - -RAS_MeshMaterial* RAS_MeshObject::GetMeshMaterial(unsigned int matid) -{ - if ((m_materials.empty() == false) && (matid < m_materials.size())) - { - list::iterator it = m_materials.begin(); - while (matid--) ++it; - return &*it; - } - - return NULL; -} - - - -int RAS_MeshObject::NumPolygons() -{ - return m_Polygons.size(); -} - - - -RAS_Polygon* RAS_MeshObject::GetPolygon(int num) const -{ - return m_Polygons[num]; -} - - - - - list::iterator GetFirstMaterial(); - list::iterator GetLastMaterial(); -list::iterator RAS_MeshObject::GetFirstMaterial() -{ - return m_materials.begin(); -} - - - -list::iterator RAS_MeshObject::GetLastMaterial() -{ - return m_materials.end(); -} - - - -void RAS_MeshObject::SetName(const char *name) -{ - m_name = name; -} - - - -STR_String& RAS_MeshObject::GetName() -{ - return m_name; -} - - - -const STR_String& RAS_MeshObject::GetTextureName(unsigned int matid) -{ - RAS_MeshMaterial* mmat = GetMeshMaterial(matid); - - if (mmat) - return mmat->m_bucket->GetPolyMaterial()->GetTextureName(); - - return s_emptyname; -} - -RAS_MeshMaterial *RAS_MeshObject::GetMeshMaterial(RAS_IPolyMaterial *mat) -{ - list::iterator mit; - - /* find a mesh material */ - for (mit = m_materials.begin(); mit != m_materials.end(); mit++) - if (mit->m_bucket->GetPolyMaterial() == mat) - return &*mit; - - return NULL; -} - -int RAS_MeshObject::GetMaterialId(RAS_IPolyMaterial *mat) -{ - list::iterator mit; - int imat; - - /* find a mesh material */ - for (imat=0, mit = m_materials.begin(); mit != m_materials.end(); mit++, imat++) - if (mit->m_bucket->GetPolyMaterial() == mat) - return imat; - - return -1; -} - -RAS_Polygon* RAS_MeshObject::AddPolygon(RAS_MaterialBucket *bucket, int numverts) -{ - RAS_MeshMaterial *mmat; - RAS_Polygon *poly; - RAS_MeshSlot *slot; - - /* find a mesh material */ - mmat = GetMeshMaterial(bucket->GetPolyMaterial()); - - /* none found, create a new one */ - if (!mmat) { - RAS_MeshMaterial meshmat; - meshmat.m_bucket = bucket; - meshmat.m_baseslot = meshmat.m_bucket->AddMesh(numverts); - meshmat.m_baseslot->m_mesh = this; - m_materials.push_back(meshmat); - mmat = &m_materials.back(); - } - - /* add it to the bucket, this also adds new display arrays */ - slot = mmat->m_baseslot; - slot->AddPolygon(numverts); - - /* create a new polygon */ - RAS_DisplayArray *darray = slot->CurrentDisplayArray(); - poly = new RAS_Polygon(bucket, darray, numverts); - m_Polygons.push_back(poly); - - return poly; -} - -void RAS_MeshObject::DebugColor(unsigned int abgr) -{ - /*int numpolys = NumPolygons(); - - for (int i=0;iVertexCount();v++) - RAS_TexVert* vtx = poly->GetVertex(v)->setDebugRGBA(abgr); - } - */ - - /* m_debugcolor = abgr; */ -} - -void RAS_MeshObject::SetVertexColor(RAS_IPolyMaterial* mat,MT_Vector4 rgba) -{ - RAS_MeshMaterial *mmat = GetMeshMaterial(mat); - RAS_MeshSlot *slot = mmat->m_baseslot; - RAS_MeshSlot::iterator it; - size_t i; - - for (slot->begin(it); !slot->end(it); slot->next(it)) - for (i=it.startvertex; iGetMaterial()->GetPolyMaterial()); - slot = mmat->m_baseslot; - darray = slot->CurrentDisplayArray(); - - { /* Shared Vertex! */ - /* find vertices shared between faces, with the restriction - * that they exist in the same display array, and have the - * same uv coordinate etc */ - vector& sharedmap = m_sharedvertex_map[origindex]; - vector::iterator it; - - for (it = sharedmap.begin(); it != sharedmap.end(); it++) - { - if (it->m_darray != darray) - continue; - if (!it->m_darray->m_vertex[it->m_offset].closeTo(&texvert)) - continue; - - /* found one, add it and we're done */ - if (poly->IsVisible()) - slot->AddPolygonVertex(it->m_offset); - poly->SetVertexOffset(i, it->m_offset); - return; - } - } - - /* no shared vertex found, add a new one */ - offset = slot->AddVertex(texvert); - if (poly->IsVisible()) - slot->AddPolygonVertex(offset); - poly->SetVertexOffset(i, offset); - - { /* Shared Vertex! */ - SharedVertex shared; - shared.m_darray = darray; - shared.m_offset = offset; - m_sharedvertex_map[origindex].push_back(shared); - } -} - -int RAS_MeshObject::NumVertices(RAS_IPolyMaterial* mat) -{ - RAS_MeshMaterial *mmat; - RAS_MeshSlot *slot; - RAS_MeshSlot::iterator it; - size_t len = 0; - - mmat = GetMeshMaterial(mat); - slot = mmat->m_baseslot; - for (slot->begin(it); !slot->end(it); slot->next(it)) - len += it.endvertex - it.startvertex; - - return len; -} - - -RAS_TexVert* RAS_MeshObject::GetVertex(unsigned int matid, - unsigned int index) -{ - RAS_MeshMaterial *mmat; - RAS_MeshSlot *slot; - RAS_MeshSlot::iterator it; - size_t len; - - mmat = GetMeshMaterial(matid); - - if (!mmat) - return NULL; - - slot = mmat->m_baseslot; - len = 0; - for (slot->begin(it); !slot->end(it); slot->next(it)) { - if (index >= len + it.endvertex - it.startvertex) - len += it.endvertex - it.startvertex; - else - return &it.vertex[index - len]; - } - - return NULL; -} - -const float* RAS_MeshObject::GetVertexLocation(unsigned int orig_index) -{ - vector& sharedmap = m_sharedvertex_map[orig_index]; - vector::iterator it= sharedmap.begin(); - return it->m_darray->m_vertex[it->m_offset].getXYZ(); -} - -void RAS_MeshObject::AddMeshUser(void *clientobj, SG_QList *head, RAS_Deformer* deformer) -{ - list::iterator it; - list::iterator mit; - - for (it = m_materials.begin();it!=m_materials.end();++it) { - /* always copy from the base slot, which is never removed - * since new objects can be created with the same mesh data */ - if (deformer && !deformer->UseVertexArray()) - { - // HACK! - // this deformer doesn't use vertex array => derive mesh - // we must keep only the mesh slots that have unique material id - // this is to match the derived mesh drawing function - // Need a better solution in the future: scan the derive mesh and create vertex array - RAS_IPolyMaterial* curmat = it->m_bucket->GetPolyMaterial(); - if (curmat->GetFlag() & RAS_BLENDERGLSL) - { - for (mit = m_materials.begin(); mit != it; ++mit) - { - RAS_IPolyMaterial* mat = mit->m_bucket->GetPolyMaterial(); - if ((mat->GetFlag() & RAS_BLENDERGLSL) && - mat->GetMaterialIndex() == curmat->GetMaterialIndex()) - // no need to convert current mesh slot - break; - } - if (mit != it) - continue; - } - } - RAS_MeshSlot *ms = it->m_bucket->CopyMesh(it->m_baseslot); - ms->m_clientObj = clientobj; - ms->SetDeformer(deformer); - it->m_slots.insert(clientobj, ms); - head->QAddBack(ms); - } -} - -void RAS_MeshObject::RemoveFromBuckets(void *clientobj) -{ - list::iterator it; - - for (it = m_materials.begin();it!=m_materials.end();++it) { - RAS_MeshSlot **msp = it->m_slots[clientobj]; - - if (!msp) - continue; - - RAS_MeshSlot *ms = *msp; - - it->m_bucket->RemoveMesh(ms); - it->m_slots.remove(clientobj); - } -} - -void RAS_MeshObject::EndConversion() -{ -#if 0 - m_sharedvertex_map.clear(); // SharedVertex - vector > shared_null(0); - shared_null.swap( m_sharedvertex_map ); /* really free the memory */ -#endif - - for (std::list::iterator it = m_materials.begin(); - it != m_materials.end(); - ++it) - { - RAS_MeshSlot *ms = it->m_baseslot; - ms->UpdateDisplayArraysOffset(); - } -} - -//void RAS_MeshObject::Transform(const MT_Transform& trans) -//{ - //m_trans.translate(MT_Vector3(0,0,1));//.operator *=(trans); - -// for (int i=0;iTransform(trans); -// } -//} - - -/* -void RAS_MeshObject::RelativeTransform(const MT_Vector3& vec) -{ - for (int i=0;iRelativeTransform(vec); - } -} -*/ - -void RAS_MeshObject::SortPolygons(RAS_MeshSlot& ms, const MT_Transform &transform) -{ - // Limitations: sorting is quite simple, and handles many - // cases wrong, partially due to polygons being sorted per - // bucket. - // - // a) mixed triangles/quads are sorted wrong - // b) mixed materials are sorted wrong - // c) more than 65k faces are sorted wrong - // d) intersecting objects are sorted wrong - // e) intersecting polygons are sorted wrong - // - // a) can be solved by making all faces either triangles or quads - // if they need to be z-sorted. c) could be solved by allowing - // larger buckets, b) and d) cannot be solved easily if we want - // to avoid excessive state changes while drawing. e) would - // require splitting polygons. - - RAS_MeshSlot::iterator it; - size_t j; - - for (ms.begin(it); !ms.end(it); ms.next(it)) { - unsigned int nvert = (int)it.array->m_type; - unsigned int totpoly = it.totindex/nvert; - - if (totpoly <= 1) - continue; - if (it.array->m_type == RAS_DisplayArray::LINE) - continue; - - // Extract camera Z plane... - const MT_Vector3 pnorm(transform.getBasis()[2]); - // unneeded: const MT_Scalar pval = transform.getOrigin()[2]; - - vector poly_slots(totpoly); - - /* get indices and z into temporary array */ - for (j=0; jIsCollider()) - return true; - - return false; -} - -void RAS_MeshObject::SchedulePolygons(int drawingmode) -{ - if (m_bModified) - { - m_bModified = false; - m_bMeshModified = true; - } -} diff --git a/source/gameengine/Rasterizer/RAS_MeshObject.h b/source/gameengine/Rasterizer/RAS_MeshObject.h deleted file mode 100644 index a6f1a1cafc6..00000000000 --- a/source/gameengine/Rasterizer/RAS_MeshObject.h +++ /dev/null @@ -1,161 +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 RAS_MeshObject.h - * \ingroup bgerast - */ - -#ifndef __RAS_MESHOBJECT_H__ -#define __RAS_MESHOBJECT_H__ - -#ifdef _MSC_VER - /* disable the STL warnings ("debug information length > 255") */ -# pragma warning (disable:4786) -#endif - -#include -#include - -#include "RAS_MaterialBucket.h" -#include "MT_Transform.h" -#include "STR_String.h" - -struct Mesh; -class RAS_Deformer; -class RAS_Polygon; - -/* RAS_MeshObject is a mesh used for rendering. It stores polygons, - * but the actual vertices and index arrays are stored in material - * buckets, referenced by the list of RAS_MeshMaterials. */ - -class RAS_MeshObject -{ -private: - /* unsigned int m_debugcolor; */ /* UNUSED */ - - bool m_bModified; - bool m_bMeshModified; - - STR_String m_name; - static STR_String s_emptyname; - - vector m_Polygons; - - /* polygon sorting */ - struct polygonSlot; - struct backtofront; - struct fronttoback; - -protected: - vector m_cacheWeightIndex; - list m_materials; - Mesh* m_mesh; - -public: - // for now, meshes need to be in a certain layer (to avoid sorting on lights in realtime) - RAS_MeshObject(Mesh* mesh); - virtual ~RAS_MeshObject(); - - - /* materials */ - int NumMaterials(); - const STR_String& GetMaterialName(unsigned int matid); - const STR_String& GetTextureName(unsigned int matid); - - RAS_MeshMaterial* GetMeshMaterial(unsigned int matid); - RAS_MeshMaterial* GetMeshMaterial(RAS_IPolyMaterial *mat); - int GetMaterialId(RAS_IPolyMaterial *mat); - - list::iterator GetFirstMaterial(); - list::iterator GetLastMaterial(); - - //unsigned int GetLightLayer(); - - /* name */ - void SetName(const char *name); - STR_String& GetName(); - - /* modification state */ - bool MeshModified(); - void SetMeshModified(bool v) { m_bMeshModified = v; } - - /* original blender mesh */ - Mesh* GetMesh() { return m_mesh; } - - /* mesh construction */ - - virtual RAS_Polygon* AddPolygon(RAS_MaterialBucket *bucket, int numverts); - virtual void AddVertex(RAS_Polygon *poly, int i, - const MT_Point3& xyz, - const MT_Point2 uvs[RAS_TexVert::MAX_UNIT], - const MT_Vector4& tangent, - const unsigned int rgbacolor, - const MT_Vector3& normal, - bool flat, - int origindex); - - void SchedulePolygons(int drawingmode); - - /* vertex and polygon acces */ - int NumVertices(RAS_IPolyMaterial* mat); - RAS_TexVert* GetVertex(unsigned int matid, unsigned int index); - const float* GetVertexLocation(unsigned int orig_index); - - int NumPolygons(); - RAS_Polygon* GetPolygon(int num) const; - - /* buckets */ - virtual void AddMeshUser(void *clientobj, SG_QList *head, RAS_Deformer* deformer); - - void RemoveFromBuckets(void *clientobj); - void EndConversion(); - - /* colors */ - void DebugColor(unsigned int abgr); - void SetVertexColor(RAS_IPolyMaterial* mat,MT_Vector4 rgba); - - /* polygon sorting by Z for alpha */ - void SortPolygons(RAS_MeshSlot& ms, const MT_Transform &transform); - - - bool HasColliderPolygon(); - - /* for construction to find shared vertices */ - struct SharedVertex { - RAS_DisplayArray *m_darray; - int m_offset; - }; - - vector > m_sharedvertex_map; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_MeshObject") -#endif -}; - -#endif /* __RAS_MESHOBJECT_H__ */ diff --git a/source/gameengine/Rasterizer/RAS_ObjectColor.h b/source/gameengine/Rasterizer/RAS_ObjectColor.h deleted file mode 100644 index 77feffccffc..00000000000 --- a/source/gameengine/Rasterizer/RAS_ObjectColor.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 RAS_ObjectColor.h - * \ingroup bgerast - */ - -#ifndef __RAS_OBJECTCOLOR_H__ -#define __RAS_OBJECTCOLOR_H__ - -struct RAS_ObjectColor { - float m_red; - float m_green; - float m_blue; -}; - -#endif /* __RAS_OBJECTCOLOR_H__ */ diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Blur2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Blur2DFilter.h deleted file mode 100644 index 3f1644a5c60..00000000000 --- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Blur2DFilter.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 RAS_Blur2DFilter.h - * \ingroup bgerastoglfilters - */ - -#ifndef __RAS_BLUR2DFILTER_H__ -#define __RAS_BLUR2DFILTER_H__ - -static const char *BlurFragmentShader = STRINGIFY( -uniform sampler2D bgl_RenderedTexture; -uniform vec2 bgl_TextureCoordinateOffset[9]; - -void main(void) -{ - vec4 sample[9]; - - for (int i = 0; i < 9; i++) - { - sample[i] = texture2D(bgl_RenderedTexture, - gl_TexCoord[0].st + bgl_TextureCoordinateOffset[i]); - } - - gl_FragColor = (sample[0] + (2.0*sample[1]) + sample[2] + - (2.0*sample[3]) + sample[4] + (2.0*sample[5]) + - sample[6] + (2.0*sample[7]) + sample[8]) / 13.0; -} -); -#endif - diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Dilation2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Dilation2DFilter.h deleted file mode 100644 index 4e863cb6f8d..00000000000 --- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Dilation2DFilter.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 RAS_Dilation2DFilter.h - * \ingroup bgerastoglfilters - */ - -#ifndef __RAS_DILATION2DFILTER_H__ -#define __RAS_DILATION2DFILTER_H__ - -static const char *DilationFragmentShader = STRINGIFY( -uniform sampler2D bgl_RenderedTexture; -uniform vec2 bgl_TextureCoordinateOffset[9]; - -void main(void) -{ - vec4 sample[9]; - vec4 maxValue = vec4(0.0); - - for (int i = 0; i < 9; i++) - { - sample[i] = texture2D(bgl_RenderedTexture, - gl_TexCoord[0].st + bgl_TextureCoordinateOffset[i]); - maxValue = max(sample[i], maxValue); - } - - gl_FragColor = maxValue; -} -); -#endif - diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Erosion2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Erosion2DFilter.h deleted file mode 100644 index 56e2c22fe2e..00000000000 --- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Erosion2DFilter.h +++ /dev/null @@ -1,54 +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 RAS_Erosion2DFilter.h - * \ingroup bgerastoglfilters - */ - -#ifndef __RAS_EROSION2DFILTER_H__ -#define __RAS_EROSION2DFILTER_H__ - -static const char *ErosionFragmentShader = STRINGIFY( -uniform sampler2D bgl_RenderedTexture; -uniform vec2 bgl_TextureCoordinateOffset[9]; - -void main(void) -{ - vec4 sample[9]; - vec4 minValue = vec4(1.0); - - for (int i = 0; i < 9; i++) - { - sample[i] = texture2D(bgl_RenderedTexture, - gl_TexCoord[0].st + bgl_TextureCoordinateOffset[i]); - minValue = min(sample[i], minValue); - } - - gl_FragColor = minValue; -} -); -#endif diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_GrayScale2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_GrayScale2DFilter.h deleted file mode 100644 index 932d5b16fed..00000000000 --- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_GrayScale2DFilter.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 RAS_GrayScale2DFilter.h - * \ingroup bgerastoglfilters - */ - -#ifndef __RAS_GRAYSCALE2DFILTER_H__ -#define __RAS_GRAYSCALE2DFILTER_H__ - -static const char *GrayScaleFragmentShader = STRINGIFY( -uniform sampler2D bgl_RenderedTexture; - -void main(void) -{ - vec4 texcolor = texture2D(bgl_RenderedTexture, gl_TexCoord[0].st); - float gray = dot(texcolor.rgb, vec3(0.299, 0.587, 0.114)); - gl_FragColor = vec4(gray, gray, gray, texcolor.a); -} -); -#endif diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Invert2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Invert2DFilter.h deleted file mode 100644 index dce303916ea..00000000000 --- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Invert2DFilter.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 RAS_Invert2DFilter.h - * \ingroup bgerastoglfilters - */ - -#ifndef __RAS_INVERT2DFILTER_H__ -#define __RAS_INVERT2DFILTER_H__ - -static const char *InvertFragmentShader = STRINGIFY( -uniform sampler2D bgl_RenderedTexture; - -void main(void) -{ - vec4 texcolor = texture2D(bgl_RenderedTexture, gl_TexCoord[0].st); - gl_FragColor.rgb = 1.0 - texcolor.rgb; - gl_FragColor.a = texcolor.a; -} -); -#endif diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Laplacian2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Laplacian2DFilter.h deleted file mode 100644 index 9ec5092817d..00000000000 --- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Laplacian2DFilter.h +++ /dev/null @@ -1,57 +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 RAS_Laplacian2DFilter.h - * \ingroup bgerastoglfilters - */ - -#ifndef __RAS_LAPLACIAN2DFILTER_H__ -#define __RAS_LAPLACIAN2DFILTER_H__ - -static const char *LaplacionFragmentShader = STRINGIFY( -uniform sampler2D bgl_RenderedTexture; -uniform vec2 bgl_TextureCoordinateOffset[9]; - -void main(void) -{ - vec4 sample[9]; - - for (int i = 0; i < 9; i++) - { - sample[i] = texture2D(bgl_RenderedTexture, - gl_TexCoord[0].st + bgl_TextureCoordinateOffset[i]); - } - - gl_FragColor = (sample[4] * 8.0) - - (sample[0] + sample[1] + sample[2] + - sample[3] + sample[5] + - sample[6] + sample[7] + sample[8]); - gl_FragColor = vec4(gl_FragColor.rgb, 1.0); -} -); -#endif - diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Prewitt2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Prewitt2DFilter.h deleted file mode 100644 index 4ae6009fdeb..00000000000 --- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Prewitt2DFilter.h +++ /dev/null @@ -1,62 +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 RAS_Prewitt2DFilter.h - * \ingroup bgerastoglfilters - */ - -#ifndef __RAS_PREWITT2DFILTER_H__ -#define __RAS_PREWITT2DFILTER_H__ - -static const char *PrewittFragmentShader = STRINGIFY( -uniform sampler2D bgl_RenderedTexture; -uniform vec2 bgl_TextureCoordinateOffset[9]; - -void main(void) -{ - vec4 sample[9]; - - for (int i = 0; i < 9; i++) - { - sample[i] = texture2D(bgl_RenderedTexture, - gl_TexCoord[0].st + bgl_TextureCoordinateOffset[i]); - } - - vec4 horizEdge = sample[2] + sample[5] + sample[8] - - (sample[0] + sample[3] + sample[6]); - - vec4 vertEdge = sample[0] + sample[1] + sample[2] - - (sample[6] + sample[7] + sample[8]); - - gl_FragColor.rgb = sqrt((horizEdge.rgb * horizEdge.rgb) + - (vertEdge.rgb * vertEdge.rgb)); - gl_FragColor.a = 1.0; -} - -); -#endif - diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sepia2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sepia2DFilter.h deleted file mode 100644 index 16b4e71dfdb..00000000000 --- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sepia2DFilter.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 RAS_Sepia2DFilter.h - * \ingroup bgerastoglfilters - */ - -#ifndef __RAS_SEPIA2DFILTER_H__ -#define __RAS_SEPIA2DFILTER_H__ - -static const char *SepiaFragmentShader = STRINGIFY( -uniform sampler2D bgl_RenderedTexture; - -void main(void) -{ - vec4 texcolor = texture2D(bgl_RenderedTexture, gl_TexCoord[0].st); - float gray = dot(texcolor.rgb, vec3(0.299, 0.587, 0.114)); - gl_FragColor = vec4(gray * vec3(1.2, 1.0, 0.8), texcolor.a); -} -); -#endif diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sharpen2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sharpen2DFilter.h deleted file mode 100644 index 7512393815b..00000000000 --- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sharpen2DFilter.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 RAS_Sharpen2DFilter.h - * \ingroup bgerastoglfilters - */ - -#ifndef __RAS_SHARPEN2DFILTER_H__ -#define __RAS_SHARPEN2DFILTER_H__ - -static const char *SharpenFragmentShader = STRINGIFY( -uniform sampler2D bgl_RenderedTexture; -uniform vec2 bgl_TextureCoordinateOffset[9]; - -void main(void) -{ - vec4 sample[9]; - - for (int i = 0; i < 9; i++) - { - sample[i] = texture2D(bgl_RenderedTexture, - gl_TexCoord[0].st + bgl_TextureCoordinateOffset[i]); - } - - gl_FragColor = (sample[4] * 9.0) - - (sample[0] + sample[1] + sample[2] + - sample[3] + sample[5] + - sample[6] + sample[7] + sample[8]); -} -); -#endif diff --git a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sobel2DFilter.h b/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sobel2DFilter.h deleted file mode 100644 index 088ac10a56a..00000000000 --- a/source/gameengine/Rasterizer/RAS_OpenGLFilters/RAS_Sobel2DFilter.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 RAS_Sobel2DFilter.h - * \ingroup bgerastoglfilters - */ - -#ifndef __RAS_SOBEL2DFILTER_H__ -#define __RAS_SOBEL2DFILTER_H__ - -static const char *SobelFragmentShader = STRINGIFY( -uniform sampler2D bgl_RenderedTexture; -uniform vec2 bgl_TextureCoordinateOffset[9]; - -void main(void) -{ - vec4 sample[9]; - - for (int i = 0; i < 9; i++) - { - sample[i] = texture2D(bgl_RenderedTexture, - gl_TexCoord[0].st + bgl_TextureCoordinateOffset[i]); - } - - vec4 horizEdge = sample[2] + (2.0*sample[5]) + sample[8] - - (sample[0] + (2.0*sample[3]) + sample[6]); - - vec4 vertEdge = sample[0] + (2.0*sample[1]) + sample[2] - - (sample[6] + (2.0*sample[7]) + sample[8]); - - gl_FragColor.rgb = sqrt((horizEdge.rgb * horizEdge.rgb) + - (vertEdge.rgb * vertEdge.rgb)); - gl_FragColor.a = 1.0; -} -); -#endif - diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/CMakeLists.txt b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/CMakeLists.txt deleted file mode 100644 index 89e31b62b41..00000000000 --- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/CMakeLists.txt +++ /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) 2006, Blender Foundation -# All rights reserved. -# -# The Original Code is: all of this file. -# -# Contributor(s): Jacques Beaurain. -# -# ***** END GPL LICENSE BLOCK ***** - -set(INC - .. - # XXX Remove these <<< - ../../BlenderRoutines - ../../Expressions - ../../GameLogic - ../../Ketsji - ../../Physics/common - # >>> - ../../SceneGraph - ../../../blender/blenfont - ../../../blender/blenkernel - ../../../blender/blenlib - ../../../blender/gpu - ../../../blender/makesdna - ../../../../intern/container - ../../../../intern/glew-mx - ../../../../intern/string -) - -set(INC_SYS - ../../../../intern/moto/include - ${GLEW_INCLUDE_PATH} -) - -set(SRC - RAS_ListRasterizer.cpp - RAS_OpenGLLight.cpp - RAS_OpenGLOffScreen.cpp - RAS_OpenGLSync.cpp - RAS_OpenGLRasterizer.cpp - RAS_StorageVA.cpp - RAS_StorageVBO.cpp - - RAS_IStorage.h - RAS_ListRasterizer.h - RAS_OpenGLLight.h - RAS_OpenGLOffScreen.h - RAS_OpenGLSync.h - RAS_OpenGLRasterizer.h - RAS_StorageVA.h - RAS_StorageVBO.h -) - -add_definitions(${GL_DEFINITIONS}) - -blender_add_lib(ge_oglrasterizer "${SRC}" "${INC}" "${INC_SYS}") diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_IStorage.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_IStorage.h deleted file mode 100644 index ae0cdcd84af..00000000000 --- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_IStorage.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 ***** - */ - -#ifndef __KX_STORAGE -#define __KX_STORAGE - -#ifdef WITH_CXX_GUARDEDALLOC - #include "MEM_guardedalloc.h" -#endif - -class RAS_MeshSlot; - -class RAS_IStorage -{ - -public: - virtual ~RAS_IStorage() {}; - - virtual bool Init()=0; - virtual void Exit()=0; - - virtual void IndexPrimitives(RAS_MeshSlot& ms)=0; - - virtual void SetDrawingMode(int drawingmode)=0; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_IStorage") -#endif -}; - -#endif //__KX_STORAGE diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp deleted file mode 100644 index 71c8cfe745f..00000000000 --- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp +++ /dev/null @@ -1,278 +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/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp - * \ingroup bgerastogl - */ - -#include - -#include "RAS_ListRasterizer.h" - -#ifdef WIN32 -#include -#endif // WIN32 - -#include "GPU_glew.h" - -#include "RAS_MaterialBucket.h" -#include "RAS_TexVert.h" -#include "MT_assert.h" - -//#if defined(DEBUG) -//#ifdef WIN32 -//#define spit(x) std::cout << x << std::endl; -//#endif //WIN32 -//#else -#define spit(x) -//#endif - -RAS_ListSlot::RAS_ListSlot(RAS_ListRasterizer* rasty) -: KX_ListSlot(), - m_list(0), - m_flag(LIST_MODIFY|LIST_CREATE), - m_matnr(0), - m_rasty(rasty) -{ -} - -int RAS_ListSlot::Release() -{ - if (--m_refcount > 0) - return m_refcount; - m_rasty->RemoveListSlot(this); - delete this; - return 0; -} - -RAS_ListSlot::~RAS_ListSlot() -{ - RemoveList(); -} - - -void RAS_ListSlot::RemoveList() -{ - if (m_list != 0) { - spit("Releasing display list (" << m_list << ")"); - glDeleteLists((GLuint)m_list, 1); - m_list =0; - } -} - -void RAS_ListSlot::DrawList() -{ - if (m_flag &LIST_MODIFY) { - if (m_flag &LIST_CREATE) { - if (m_list == 0) { - m_list = (unsigned int)glGenLists(1); - m_flag = m_flag &~ LIST_CREATE; - spit("Created display list (" << m_list << ")"); - } - } - if (m_list != 0) - glNewList((GLuint)m_list, GL_COMPILE); - - m_flag |= LIST_BEGIN; - return; - } - glCallList(m_list); -} - -void RAS_ListSlot::EndList() -{ - if (m_flag & LIST_BEGIN) { - glEndList(); - m_flag = m_flag &~(LIST_BEGIN|LIST_MODIFY); - m_flag |= LIST_END; - glCallList(m_list); - } -} - -void RAS_ListSlot::SetModified(bool mod) -{ - if (mod && !(m_flag & LIST_MODIFY)) { - spit("Modifying list (" << m_list << ")"); - m_flag = m_flag &~ LIST_END; - m_flag |= LIST_MODIFY; - } -} - -bool RAS_ListSlot::End() -{ - return (m_flag &LIST_END)!=0; -} - - - -RAS_ListRasterizer::RAS_ListRasterizer(RAS_ICanvas* canvas, bool lock, RAS_STORAGE_TYPE storage) -: RAS_OpenGLRasterizer(canvas, storage) -{ -} - -RAS_ListRasterizer::~RAS_ListRasterizer() -{ - ReleaseAlloc(); -} - -void RAS_ListRasterizer::RemoveListSlot(RAS_ListSlot* list) -{ - if (list->m_flag & LIST_DERIVEDMESH) { - RAS_DerivedMeshLists::iterator it = mDerivedMeshLists.begin(); - while (it != mDerivedMeshLists.end()) { - RAS_ListSlots *slots = it->second; - if (slots->size() > list->m_matnr && slots->at(list->m_matnr) == list) { - (*slots)[list->m_matnr] = NULL; - // check if all slots are NULL and if yes, delete the entry - int i; - for (i=slots->size(); i-- > 0; ) { - if (slots->at(i) != NULL) - break; - } - if (i < 0) { - slots->clear(); - delete slots; - mDerivedMeshLists.erase(it); - } - break; - } - ++it; - } - } else { - RAS_ArrayLists::iterator it = mArrayLists.begin(); - while (it != mArrayLists.end()) { - if (it->second == list) { - mArrayLists.erase(it); - break; - } - it++; - } - } -} - -RAS_ListSlot* RAS_ListRasterizer::FindOrAdd(RAS_MeshSlot& ms) -{ - /* - * Keep a copy of constant lists submitted for rendering, - * this guards against (replicated)new...delete every frame, - * and we can reuse lists! - * :: sorted by mesh slot - */ - RAS_ListSlot* localSlot = (RAS_ListSlot*)ms.m_DisplayList; - if (!localSlot) { - if (ms.m_pDerivedMesh) { - // that means that we draw based on derived mesh, a display list is possible - // Note that we come here only for static derived mesh - int matnr = ms.m_bucket->GetPolyMaterial()->GetMaterialIndex(); - RAS_ListSlot* nullSlot = NULL; - RAS_ListSlots *listVector; - RAS_DerivedMeshLists::iterator it = mDerivedMeshLists.find(ms.m_pDerivedMesh); - if (it == mDerivedMeshLists.end()) { - listVector = new RAS_ListSlots(matnr+4, nullSlot); - localSlot = new RAS_ListSlot(this); - localSlot->m_flag |= LIST_DERIVEDMESH; - localSlot->m_matnr = matnr; - listVector->at(matnr) = localSlot; - mDerivedMeshLists.insert(std::pair(ms.m_pDerivedMesh, listVector)); - } else { - listVector = it->second; - if (listVector->size() <= matnr) - listVector->resize(matnr+4, nullSlot); - if ((localSlot = listVector->at(matnr)) == NULL) { - localSlot = new RAS_ListSlot(this); - localSlot->m_flag |= LIST_DERIVEDMESH; - localSlot->m_matnr = matnr; - listVector->at(matnr) = localSlot; - } else { - localSlot->AddRef(); - } - } - } else { - RAS_ArrayLists::iterator it = mArrayLists.find(ms.m_displayArrays); - if (it == mArrayLists.end()) { - localSlot = new RAS_ListSlot(this); - mArrayLists.insert(std::pair(ms.m_displayArrays, localSlot)); - } else { - localSlot = static_cast(it->second->AddRef()); - } - } - } - MT_assert(localSlot); - return localSlot; -} - -void RAS_ListRasterizer::ReleaseAlloc() -{ - for (RAS_ArrayLists::iterator it = mArrayLists.begin();it != mArrayLists.end();++it) - delete it->second; - mArrayLists.clear(); - for (RAS_DerivedMeshLists::iterator it = mDerivedMeshLists.begin();it != mDerivedMeshLists.end();++it) { - RAS_ListSlots* slots = it->second; - for (int i=slots->size(); i-- > 0; ) { - RAS_ListSlot* slot = slots->at(i); - if (slot) - delete slot; - } - slots->clear(); - delete slots; - } - mDerivedMeshLists.clear(); -} - -void RAS_ListRasterizer::IndexPrimitives(RAS_MeshSlot& ms) -{ - RAS_ListSlot* localSlot =0; - - if (ms.m_bDisplayList) { - localSlot = FindOrAdd(ms); - localSlot->DrawList(); - - if (localSlot->End()) { - // save slot here too, needed for replicas and object using same mesh - // => they have the same vertexarray but different mesh slot - ms.m_DisplayList = localSlot; - return; - } - } - - RAS_OpenGLRasterizer::IndexPrimitives(ms); - - if (ms.m_bDisplayList) { - localSlot->EndList(); - ms.m_DisplayList = localSlot; - } -} - -bool RAS_ListRasterizer::Init(void) -{ - return RAS_OpenGLRasterizer::Init(); -} - -void RAS_ListRasterizer::SetDrawingMode(int drawingmode) -{ - RAS_OpenGLRasterizer::SetDrawingMode(drawingmode); -} - -void RAS_ListRasterizer::Exit() -{ - RAS_OpenGLRasterizer::Exit(); -} - -// eof diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.h deleted file mode 100644 index e3e6931311b..00000000000 --- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.h +++ /dev/null @@ -1,77 +0,0 @@ - -/** \file RAS_ListRasterizer.h - * \ingroup bgerastogl - */ - -#ifndef __RAS_LISTRASTERIZER_H__ -#define __RAS_LISTRASTERIZER_H__ - -#include "RAS_MaterialBucket.h" -#include "RAS_OpenGLRasterizer.h" -#include -#include - -class RAS_ListRasterizer; -class RAS_ListSlot : public KX_ListSlot -{ - friend class RAS_ListRasterizer; - unsigned int m_list; - unsigned int m_flag; - unsigned int m_matnr; - RAS_ListRasterizer* m_rasty; -public: - RAS_ListSlot(RAS_ListRasterizer* rasty); - virtual ~RAS_ListSlot(); - virtual void SetModified(bool mod); - virtual int Release(); - - void RemoveList(); - void DrawList(); - void EndList(); - bool End(); - -}; - -enum RAS_ListSlotFlags { - LIST_CREATE =1, - LIST_MODIFY =2, - LIST_BEGIN =4, - LIST_END =8, - LIST_DERIVEDMESH=16, -}; - -struct DerivedMesh; - -typedef std::map RAS_ArrayLists; -typedef std::vector RAS_ListSlots; // indexed by material slot number -typedef std::map RAS_DerivedMeshLists; - -class RAS_ListRasterizer : public RAS_OpenGLRasterizer -{ - RAS_ArrayLists mArrayLists; - RAS_DerivedMeshLists mDerivedMeshLists; - - RAS_ListSlot* FindOrAdd(class RAS_MeshSlot& ms); - void ReleaseAlloc(); - -public: - void RemoveListSlot(RAS_ListSlot* list); - RAS_ListRasterizer(RAS_ICanvas* canvas, bool lock, RAS_STORAGE_TYPE storage); - virtual ~RAS_ListRasterizer(); - - virtual void IndexPrimitives(class RAS_MeshSlot& ms); - - virtual bool Init(); - virtual void Exit(); - - virtual void SetDrawingMode(int drawingmode); - - virtual bool QueryLists() {return true;} - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_ListRasterizer") -#endif -}; - -#endif diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLLight.cpp b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLLight.cpp deleted file mode 100644 index 18254357f85..00000000000 --- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLLight.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): Mitchell Stokes - * - * ***** END GPL LICENSE BLOCK ***** - */ - -#include "GPU_glew.h" - -#include - - -#include "RAS_OpenGLLight.h" -#include "RAS_OpenGLRasterizer.h" -#include "RAS_ICanvas.h" - -#include "MT_CmMatrix4x4.h" - -#include "KX_Camera.h" -#include "KX_Light.h" -#include "KX_Scene.h" - -#include "DNA_lamp_types.h" -#include "DNA_scene_types.h" - -#include "GPU_lamp.h" -#include "GPU_material.h" - -RAS_OpenGLLight::RAS_OpenGLLight(RAS_OpenGLRasterizer *ras) - :m_rasterizer(ras) -{ -} - -RAS_OpenGLLight::~RAS_OpenGLLight() -{ - GPULamp *lamp; - KX_LightObject* kxlight = (KX_LightObject*)m_light; - Lamp *la = (Lamp*)kxlight->GetBlenderObject()->data; - - if ((lamp = GetGPULamp())) { - float obmat[4][4] = {{0}}; - GPU_lamp_update(lamp, 0, 0, obmat); - GPU_lamp_update_distance(lamp, la->dist, la->att1, la->att2, la->coeff_const, la->coeff_lin, la->coeff_quad); - GPU_lamp_update_spot(lamp, la->spotsize, la->spotblend); - } -} - -bool RAS_OpenGLLight::ApplyFixedFunctionLighting(KX_Scene *kxscene, int oblayer, int slot) -{ - KX_Scene* lightscene = (KX_Scene*)m_scene; - KX_LightObject* kxlight = (KX_LightObject*)m_light; - float vec[4]; - int scenelayer = ~0; - - if (kxscene && kxscene->GetBlenderScene()) - scenelayer = kxscene->GetBlenderScene()->lay; - - /* only use lights in the same layer as the object */ - if (!(m_layer & oblayer)) - return false; - /* only use lights in the same scene, and in a visible layer */ - if (kxscene != lightscene || !(m_layer & scenelayer)) - return false; - - // lights don't get their openGL matrix updated, do it now - if (kxlight->GetSGNode()->IsDirty()) - kxlight->GetOpenGLMatrix(); - - MT_CmMatrix4x4& worldmatrix= *kxlight->GetOpenGLMatrixPtr(); - - vec[0] = worldmatrix(0,3); - vec[1] = worldmatrix(1,3); - vec[2] = worldmatrix(2,3); - vec[3] = 1.0f; - - if (m_type==RAS_ILightObject::LIGHT_SUN) { - - vec[0] = worldmatrix(0,2); - vec[1] = worldmatrix(1,2); - vec[2] = worldmatrix(2,2); - //vec[0] = base->object->obmat[2][0]; - //vec[1] = base->object->obmat[2][1]; - //vec[2] = base->object->obmat[2][2]; - vec[3] = 0.0f; - glLightfv((GLenum)(GL_LIGHT0+slot), GL_POSITION, vec); - } - else { - //vec[3] = 1.0f; - glLightfv((GLenum)(GL_LIGHT0+slot), GL_POSITION, vec); - glLightf((GLenum)(GL_LIGHT0+slot), GL_CONSTANT_ATTENUATION, 1.0f); - glLightf((GLenum)(GL_LIGHT0+slot), GL_LINEAR_ATTENUATION, m_att1/m_distance); - // without this next line it looks backward compatible. - //attennuation still is acceptable - glLightf((GLenum)(GL_LIGHT0+slot), GL_QUADRATIC_ATTENUATION, m_att2/(m_distance*m_distance)); - - if (m_type==RAS_ILightObject::LIGHT_SPOT) { - vec[0] = -worldmatrix(0,2); - vec[1] = -worldmatrix(1,2); - vec[2] = -worldmatrix(2,2); - //vec[0] = -base->object->obmat[2][0]; - //vec[1] = -base->object->obmat[2][1]; - //vec[2] = -base->object->obmat[2][2]; - glLightfv((GLenum)(GL_LIGHT0+slot), GL_SPOT_DIRECTION, vec); - glLightf((GLenum)(GL_LIGHT0+slot), GL_SPOT_CUTOFF, m_spotsize / 2.0f); - glLightf((GLenum)(GL_LIGHT0+slot), GL_SPOT_EXPONENT, 128.0f * m_spotblend); - } - else { - glLightf((GLenum)(GL_LIGHT0+slot), GL_SPOT_CUTOFF, 180.0f); - } - } - - if (m_nodiffuse) { - vec[0] = vec[1] = vec[2] = vec[3] = 0.0f; - } - else { - vec[0] = m_energy*m_color[0]; - vec[1] = m_energy*m_color[1]; - vec[2] = m_energy*m_color[2]; - vec[3] = 1.0f; - } - - glLightfv((GLenum)(GL_LIGHT0+slot), GL_DIFFUSE, vec); - if (m_nospecular) - { - vec[0] = vec[1] = vec[2] = vec[3] = 0.0f; - } - else if (m_nodiffuse) { - vec[0] = m_energy*m_color[0]; - vec[1] = m_energy*m_color[1]; - vec[2] = m_energy*m_color[2]; - vec[3] = 1.0f; - } - - glLightfv((GLenum)(GL_LIGHT0+slot), GL_SPECULAR, vec); - glEnable((GLenum)(GL_LIGHT0+slot)); - - return true; -} - -GPULamp *RAS_OpenGLLight::GetGPULamp() -{ - KX_LightObject* kxlight = (KX_LightObject*)m_light; - - if (m_glsl) - return GPU_lamp_from_blender(kxlight->GetScene()->GetBlenderScene(), kxlight->GetBlenderObject(), kxlight->GetBlenderGroupObject()); - else - return NULL; -} - - -bool RAS_OpenGLLight::HasShadowBuffer() -{ - GPULamp *lamp; - - if ((lamp = GetGPULamp())) - return GPU_lamp_has_shadow_buffer(lamp); - else - return false; -} - -int RAS_OpenGLLight::GetShadowBindCode() -{ - GPULamp *lamp; - - if ((lamp = GetGPULamp())) - return GPU_lamp_shadow_bind_code(lamp); - return -1; -} - -MT_Matrix4x4 RAS_OpenGLLight::GetShadowMatrix() -{ - GPULamp *lamp; - - if ((lamp = GetGPULamp())) - return MT_Matrix4x4(GPU_lamp_dynpersmat(lamp)); - MT_Matrix4x4 mat; - mat.setIdentity(); - return mat; -} - -int RAS_OpenGLLight::GetShadowLayer() -{ - GPULamp *lamp; - - if ((lamp = GetGPULamp())) - return GPU_lamp_shadow_layer(lamp); - else - return 0; -} - -void RAS_OpenGLLight::BindShadowBuffer(RAS_ICanvas *canvas, KX_Camera *cam, MT_Transform& camtrans) -{ - GPULamp *lamp; - float viewmat[4][4], winmat[4][4]; - int winsize; - - /* bind framebuffer */ - lamp = GetGPULamp(); - GPU_lamp_shadow_buffer_bind(lamp, viewmat, &winsize, winmat); - - if (GPU_lamp_shadow_buffer_type(lamp) == LA_SHADMAP_VARIANCE) - m_rasterizer->SetUsingOverrideShader(true); - - /* GPU_lamp_shadow_buffer_bind() changes the viewport, so update the canvas */ - canvas->UpdateViewPort(0, 0, winsize, winsize); - - /* setup camera transformation */ - MT_Matrix4x4 modelviewmat((float*)viewmat); - MT_Matrix4x4 projectionmat((float*)winmat); - - MT_Transform trans = MT_Transform((float*)viewmat); - camtrans.invert(trans); - - cam->SetModelviewMatrix(modelviewmat); - cam->SetProjectionMatrix(projectionmat); - - cam->NodeSetLocalPosition(camtrans.getOrigin()); - cam->NodeSetLocalOrientation(camtrans.getBasis()); - cam->NodeUpdateGS(0); - - /* setup rasterizer transformations */ - /* SetViewMatrix may use stereomode which we temporarily disable here */ - RAS_IRasterizer::StereoMode stereomode = m_rasterizer->GetStereoMode(); - m_rasterizer->SetStereoMode(RAS_IRasterizer::RAS_STEREO_NOSTEREO); - m_rasterizer->SetProjectionMatrix(projectionmat); - m_rasterizer->SetViewMatrix(modelviewmat, cam->NodeGetWorldOrientation(), cam->NodeGetWorldPosition(), cam->NodeGetLocalScaling(), cam->GetCameraData()->m_perspective); - m_rasterizer->SetStereoMode(stereomode); -} - -void RAS_OpenGLLight::UnbindShadowBuffer() -{ - GPULamp *lamp = GetGPULamp(); - GPU_lamp_shadow_buffer_unbind(lamp); - - if (GPU_lamp_shadow_buffer_type(lamp) == LA_SHADMAP_VARIANCE) - m_rasterizer->SetUsingOverrideShader(false); -} - -Image *RAS_OpenGLLight::GetTextureImage(short texslot) -{ - KX_LightObject* kxlight = (KX_LightObject*)m_light; - Lamp *la = (Lamp*)kxlight->GetBlenderObject()->data; - - if (texslot >= MAX_MTEX || texslot < 0) - { - printf("KX_LightObject::GetTextureImage(): texslot exceeds slot bounds (0-%d)\n", MAX_MTEX-1); - return NULL; - } - - if (la->mtex[texslot]) - return la->mtex[texslot]->tex->ima; - - return NULL; -} - -void RAS_OpenGLLight::Update() -{ - GPULamp *lamp; - KX_LightObject* kxlight = (KX_LightObject*)m_light; - - if ((lamp = GetGPULamp()) != NULL && kxlight->GetSGNode()) { - float obmat[4][4]; - // lights don't get their openGL matrix updated, do it now - if (kxlight->GetSGNode()->IsDirty()) - kxlight->GetOpenGLMatrix(); - float *dobmat = kxlight->GetOpenGLMatrixPtr()->getPointer(); - - for (int i=0; i<4; i++) - for (int j=0; j<4; j++, dobmat++) - obmat[i][j] = (float)*dobmat; - int hide = kxlight->GetVisible() ? 0 : 1; - GPU_lamp_update(lamp, m_layer, hide, obmat); - GPU_lamp_update_colors(lamp, m_color[0], m_color[1], - m_color[2], m_energy); - GPU_lamp_update_distance(lamp, m_distance, m_att1, m_att2, m_coeff_const, m_coeff_lin, m_coeff_quad); - GPU_lamp_update_spot(lamp, m_spotsize, m_spotblend); - } -} - - diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLLight.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLLight.h deleted file mode 100644 index a520b18c434..00000000000 --- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLLight.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): Mitchell Stokes - * - * ***** END GPL LICENSE BLOCK ***** - */ - -#include "RAS_ILightObject.h" - -class RAS_OpenGLRasterizer; -struct GPULamp; -struct Image; - -class RAS_OpenGLLight : public RAS_ILightObject -{ - - RAS_OpenGLRasterizer *m_rasterizer; - - GPULamp *GetGPULamp(); -public: - RAS_OpenGLLight(RAS_OpenGLRasterizer *ras); - ~RAS_OpenGLLight(); - - bool ApplyFixedFunctionLighting(KX_Scene *kxscene, int oblayer, int slot); - - RAS_OpenGLLight* Clone() { return new RAS_OpenGLLight(*this); } - - bool HasShadowBuffer(); - int GetShadowBindCode(); - MT_Matrix4x4 GetShadowMatrix(); - int GetShadowLayer(); - void BindShadowBuffer(RAS_ICanvas *canvas, KX_Camera *cam, MT_Transform& camtrans); - void UnbindShadowBuffer(); - Image *GetTextureImage(short texslot); - void Update(); -}; diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLOffScreen.cpp b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLOffScreen.cpp deleted file mode 100644 index 58b3c61bd05..00000000000 --- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLOffScreen.cpp +++ /dev/null @@ -1,347 +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) 2015, Blender Foundation - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): Blender Foundation. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -#include "GPU_glew.h" - -#include - -#include "RAS_OpenGLOffScreen.h" -#include "RAS_ICanvas.h" - -RAS_OpenGLOffScreen::RAS_OpenGLOffScreen(RAS_ICanvas *canvas) - :m_canvas(canvas), m_depthrb(0), m_colorrb(0), m_depthtx(0), m_colortx(0), - m_fbo(0), m_blitfbo(0), m_blitrbo(0), m_blittex(0), m_target(RAS_OFS_RENDER_BUFFER), m_bound(false) -{ - m_width = 0; - m_height = 0; - m_samples = 0; - m_color = 0; -} - -RAS_OpenGLOffScreen::~RAS_OpenGLOffScreen() -{ - Destroy(); -} - -bool RAS_OpenGLOffScreen::Create(int width, int height, int samples, RAS_OFS_RENDER_TARGET target) -{ - GLenum status; - GLuint glo[2], fbo; - GLint max_samples; - GLenum textarget; - - if (m_fbo) { - printf("RAS_OpenGLOffScreen::Create(): buffer exists already, destroy first\n"); - return false; - } - if (target != RAS_IOffScreen::RAS_OFS_RENDER_BUFFER && - target != RAS_IOffScreen::RAS_OFS_RENDER_TEXTURE) - { - printf("RAS_OpenGLOffScreen::Create(): invalid offscren target\n"); - return false; - } - if (!GLEW_EXT_framebuffer_object) { - printf("RAS_OpenGLOffScreen::Create(): frame buffer not supported\n"); - return false; - } - if (samples) { - if (!GLEW_EXT_framebuffer_multisample || - !GLEW_EXT_framebuffer_blit) - { - samples = 0; - } - } - if (samples && target == RAS_OFS_RENDER_TEXTURE) { - // we need this in addition if we use multisample textures - if (!GLEW_ARB_texture_multisample || - !GLEW_EXT_framebuffer_multisample_blit_scaled) - { - samples = 0; - } - } - if (samples) { - max_samples = 0; - glGetIntegerv(GL_MAX_SAMPLES_EXT , &max_samples); - if (samples > max_samples) - samples = max_samples; - } - m_target = target; - fbo = 0; - glGenFramebuffersEXT(1, &fbo); - if (fbo == 0) { - printf("RAS_OpenGLOffScreen::Create(): frame buffer creation failed: %d\n", (int)glGetError()); - return false; - } - m_fbo = fbo; - glo[0] = glo[1] = 0; - if (target == RAS_OFS_RENDER_TEXTURE) { - glGenTextures(2, glo); - if (glo[0] == 0 || glo[1] == 0) { - printf("RAS_OpenGLOffScreen::Create(): texture creation failed: %d\n", (int)glGetError()); - goto L_ERROR; - } - m_depthtx = glo[0]; - m_color = m_colortx = glo[1]; - if (samples) { - textarget = GL_TEXTURE_2D_MULTISAMPLE; - glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, m_depthtx); - glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, samples, GL_DEPTH_COMPONENT, width, height, true); - glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, m_colortx); - glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, samples, GL_RGBA8, width, height, true); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0); - } - else { - textarget = GL_TEXTURE_2D; - glBindTexture(GL_TEXTURE_2D, m_depthtx); - glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL); - glBindTexture(GL_TEXTURE_2D, m_colortx); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); - glBindTexture(GL_TEXTURE_2D, 0); - } - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo); - glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, textarget, m_depthtx, 0); - glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, textarget, m_colortx, 0); - } - else { - glGenRenderbuffersEXT(2, glo); - if (glo[0] == 0 || glo[1] == 0) { - printf("RAS_OpenGLOffScreen::Create(): render buffer creation failed: %d\n", (int)glGetError()); - goto L_ERROR; - } - m_depthrb = glo[0]; - m_colorrb = glo[1]; - glBindRenderbufferEXT(GL_RENDERBUFFER, m_depthrb); - glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER, samples, GL_DEPTH_COMPONENT, width, height); - glBindRenderbufferEXT(GL_RENDERBUFFER, m_colorrb); - glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER, samples, GL_RGBA8, width, height); - glBindRenderbufferEXT(GL_RENDERBUFFER, 0); - - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo); - glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER, m_depthrb); - glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER, m_colorrb); - } - status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); - - if (status != GL_FRAMEBUFFER_COMPLETE_EXT) { - printf("RAS_OpenGLOffScreen::Create(): frame buffer incomplete: %d\n", (int)status); - goto L_ERROR; - } - m_width = width; - m_height = height; - - if (samples > 0) { - GLuint blit_tex; - GLuint blit_fbo; - // create a secondary FBO to blit to before the pixel can be read - - /* write into new single-sample buffer */ - glGenFramebuffersEXT(1, &blit_fbo); - if (!blit_fbo) { - printf("RAS_OpenGLOffScreen::Create(): failed creating a FBO for multi-sample offscreen buffer\n"); - goto L_ERROR; - } - m_blitfbo = blit_fbo; - blit_tex = 0; - if (target == RAS_OFS_RENDER_TEXTURE) { - glGenTextures(1, &blit_tex); - if (!blit_tex) { - printf("RAS_OpenGLOffScreen::Create(): failed creating a texture for multi-sample offscreen buffer\n"); - goto L_ERROR; - } - // m_color is the texture where the final render goes, the blit texture in this case - m_color = m_blittex = blit_tex; - glBindTexture(GL_TEXTURE_2D, m_blittex); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glBindTexture(GL_TEXTURE_2D, 0); - glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, m_blitfbo); - glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, m_blittex, 0); - } - else { - /* create render buffer for new 'fbo_blit' */ - glGenRenderbuffersEXT(1, &blit_tex); - if (!blit_tex) { - printf("RAS_OpenGLOffScreen::Create(): failed creating a render buffer for multi-sample offscreen buffer\n"); - goto L_ERROR; - } - m_blitrbo = blit_tex; - glBindRenderbufferEXT(GL_RENDERBUFFER, m_blitrbo); - glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER, 0, GL_RGBA8, width, height); - glBindRenderbufferEXT(GL_RENDERBUFFER, 0); - glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, m_blitfbo); - glFramebufferRenderbufferEXT(GL_DRAW_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER, m_blitrbo); - } - status = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER_EXT); - glBindFramebuffer(GL_DRAW_FRAMEBUFFER_EXT, 0); - if (status != GL_FRAMEBUFFER_COMPLETE) { - printf("RAS_OpenGLOffScreen::Create(): frame buffer for multi-sample offscreen buffer incomplete: %d\n", (int)status); - goto L_ERROR; - } - // remember that multisample is enabled - m_samples = 1; - } - return true; - -L_ERROR: - Destroy(); - return false; -} - -void RAS_OpenGLOffScreen::Destroy() -{ - GLuint globj; - Unbind(); - if (m_fbo) { - globj = m_fbo; - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo); - if (m_target == RAS_OFS_RENDER_TEXTURE) { - GLenum textarget = (m_samples) ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D; - glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, textarget, 0, 0); - glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, textarget, 0, 0); - } - else { - glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0); - glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, 0); - } - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); - glDeleteFramebuffersEXT(1, &globj); - m_fbo = 0; - } - if (m_depthrb) { - globj = m_depthrb; - glDeleteRenderbuffers(1, &globj); - m_depthrb = 0; - } - if (m_colorrb) { - globj = m_colorrb; - glDeleteRenderbuffers(1, &globj); - m_colorrb = 0; - } - if (m_depthtx) { - globj = m_depthtx; - glDeleteTextures(1, &globj); - m_depthtx = 0; - } - if (m_colortx) { - globj = m_colortx; - glDeleteTextures(1, &globj); - m_colortx = 0; - } - if (m_blitfbo) { - globj = m_blitfbo; - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_blitfbo); - if (m_target == RAS_OFS_RENDER_TEXTURE) { - glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, 0, 0); - } - else { - glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, 0); - } - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); - glDeleteFramebuffersEXT(1, &globj); - m_blitfbo = 0; - } - if (m_blitrbo) { - globj = m_blitrbo; - glDeleteRenderbuffers(1, &globj); - m_blitrbo = 0; - } - if (m_blittex) { - globj = m_blittex; - glDeleteTextures(1, &globj); - m_blittex = 0; - } - m_width = 0; - m_height = 0; - m_samples = 0; - m_color = 0; - m_target = RAS_OFS_RENDER_BUFFER; -} - -void RAS_OpenGLOffScreen::Bind(RAS_OFS_BIND_MODE mode) -{ - if (m_fbo) { - if (mode == RAS_OFS_BIND_RENDER) { - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo); - glReadBuffer(GL_COLOR_ATTACHMENT0_EXT); - glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT); - glViewport(0, 0, m_width, m_height); - glDisable(GL_SCISSOR_TEST); - } - else if (!m_blitfbo) { - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo); - glReadBuffer(GL_COLOR_ATTACHMENT0_EXT); - } - else { - glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, m_blitfbo); - glReadBuffer(GL_COLOR_ATTACHMENT0_EXT); - } - m_bound = true; - } -} - -void RAS_OpenGLOffScreen::Unbind() -{ - if (!m_bound) - return; - - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); - glEnable(GL_SCISSOR_TEST); - glReadBuffer(GL_BACK); - glDrawBuffer(GL_BACK); - m_bound = false; -} - -void RAS_OpenGLOffScreen::MipMap() -{ - if (m_color) { - glBindTexture(GL_TEXTURE_2D, m_color); - glGenerateMipmap(GL_TEXTURE_2D); - glBindTexture(GL_TEXTURE_2D, 0); - } -} - -void RAS_OpenGLOffScreen::Blit() -{ - if (m_bound && m_blitfbo) { - // set the draw target to the secondary FBO, the read target is still the multisample FBO - glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER, m_blitfbo); - - // sample the primary - glBlitFramebufferEXT(0, 0, m_width, m_height, 0, 0, m_width, m_height, GL_COLOR_BUFFER_BIT, GL_NEAREST); - - // make sure the next glReadPixels will read from the secondary buffer - glBindFramebufferEXT(GL_READ_FRAMEBUFFER, m_blitfbo); - } -} diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLOffScreen.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLOffScreen.h deleted file mode 100644 index 3f6845f1e21..00000000000 --- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLOffScreen.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) 2015, Blender Foundation - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): Blender Foundation. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -#ifndef __RAS_OPENGLOFFSCREEN__ -#define __RAS_OPENGLOFFSCREEN__ - -#include "RAS_IOffScreen.h" -#include "GPU_extensions.h" - -class RAS_ICanvas; - -class RAS_OpenGLOffScreen : public RAS_IOffScreen -{ - RAS_ICanvas *m_canvas; - // these are GL objects - unsigned int m_depthrb; - unsigned int m_colorrb; - unsigned int m_depthtx; - unsigned int m_colortx; - unsigned int m_fbo; - unsigned int m_blitfbo; - unsigned int m_blitrbo; - unsigned int m_blittex; - RAS_OFS_RENDER_TARGET m_target; - bool m_bound; - - -public: - RAS_OpenGLOffScreen(RAS_ICanvas *canvas); - ~RAS_OpenGLOffScreen(); - - bool Create(int width, int height, int samples, RAS_OFS_RENDER_TARGET target); - void Destroy(); - void Bind(RAS_OFS_BIND_MODE mode); - void Blit(); - void Unbind(); - void MipMap(); -}; - -#endif /* __RAS_OPENGLOFFSCREEN__ */ - diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp deleted file mode 100644 index d1c3162f752..00000000000 --- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp +++ /dev/null @@ -1,1694 +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/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp - * \ingroup bgerastogl - */ - - -#include -#include - -#include "RAS_OpenGLRasterizer.h" - -#include "GPU_glew.h" - -#include "RAS_ICanvas.h" -#include "RAS_Rect.h" -#include "RAS_TexVert.h" -#include "RAS_MeshObject.h" -#include "RAS_Polygon.h" -#include "RAS_ILightObject.h" -#include "MT_CmMatrix4x4.h" - -#include "RAS_OpenGLLight.h" -#include "RAS_OpenGLOffScreen.h" -#include "RAS_OpenGLSync.h" - -#include "RAS_StorageVA.h" -#include "RAS_StorageVBO.h" - -#include "GPU_draw.h" -#include "GPU_extensions.h" -#include "GPU_material.h" -#include "GPU_shader.h" - -extern "C"{ - #include "BLF_api.h" - #include "BKE_DerivedMesh.h" - #include "DNA_material_types.h" -} - - -// XXX Clean these up <<< -#include "EXP_Value.h" -#include "KX_Scene.h" -#include "KX_RayCast.h" -#include "KX_GameObject.h" -// >>> - -#ifndef M_PI -#define M_PI 3.14159265358979323846 -#endif - -/** - * 32x32 bit masks for vinterlace stereo mode - */ -static GLuint left_eye_vinterlace_mask[32]; -static GLuint right_eye_vinterlace_mask[32]; - -/** - * 32x32 bit masks for hinterlace stereo mode. - * Left eye = &hinterlace_mask[0] - * Right eye = &hinterlace_mask[1] - */ -static GLuint hinterlace_mask[33]; - -RAS_OpenGLRasterizer::RAS_OpenGLRasterizer(RAS_ICanvas* canvas, RAS_STORAGE_TYPE storage) - :RAS_IRasterizer(canvas), - m_2DCanvas(canvas), - m_fogenabled(false), - m_time(0.0f), - m_campos(0.0f, 0.0f, 0.0f), - m_camortho(false), - m_camnegscale(false), - m_stereomode(RAS_STEREO_NOSTEREO), - m_curreye(RAS_STEREO_LEFTEYE), - m_eyeseparation(0.0f), - m_focallength(0.0f), - m_setfocallength(false), - m_noOfScanlines(32), - m_motionblur(0), - m_motionblurvalue(-1.0f), - m_usingoverrideshader(false), - m_clientobject(NULL), - m_auxilaryClientInfo(NULL), - m_drawingmode(KX_TEXTURED), - m_texco_num(0), - m_attrib_num(0), - //m_last_alphablend(GPU_BLEND_SOLID), - m_last_frontface(true), - m_materialCachingInfo(0), - m_storage_type(storage) -{ - m_viewmatrix.setIdentity(); - m_viewinvmatrix.setIdentity(); - - for (int i = 0; i < 32; i++) - { - left_eye_vinterlace_mask[i] = 0x55555555; - right_eye_vinterlace_mask[i] = 0xAAAAAAAA; - hinterlace_mask[i] = (i&1)*0xFFFFFFFF; - } - hinterlace_mask[32] = 0; - - m_prevafvalue = GPU_get_anisotropic(); - - if (m_storage_type == RAS_VBO /*|| m_storage_type == RAS_AUTO_STORAGE && GLEW_ARB_vertex_buffer_object*/) { - m_storage = new RAS_StorageVBO(&m_texco_num, m_texco, &m_attrib_num, m_attrib, m_attrib_layer); - } - else if ((m_storage_type == RAS_VA) || (m_storage_type == RAS_AUTO_STORAGE)) { - m_storage = new RAS_StorageVA(&m_texco_num, m_texco, &m_attrib_num, m_attrib, m_attrib_layer); - } - else { - printf("Unknown rasterizer storage type, falling back to vertex arrays\n"); - m_storage = new RAS_StorageVA(&m_texco_num, m_texco, &m_attrib_num, m_attrib, m_attrib_layer); - } - - glGetIntegerv(GL_MAX_LIGHTS, (GLint *) &m_numgllights); - if (m_numgllights < 8) - m_numgllights = 8; -} - - - -RAS_OpenGLRasterizer::~RAS_OpenGLRasterizer() -{ - // Restore the previous AF value - GPU_set_anisotropic(m_prevafvalue); - - if (m_storage) - delete m_storage; -} - -bool RAS_OpenGLRasterizer::Init() -{ - bool storage_init; - GPU_state_init(); - - - m_ambr = 0.0f; - m_ambg = 0.0f; - m_ambb = 0.0f; - - glDisable(GL_BLEND); - glDisable(GL_ALPHA_TEST); - //m_last_alphablend = GPU_BLEND_SOLID; - GPU_set_material_alpha_blend(GPU_BLEND_SOLID); - - glFrontFace(GL_CCW); - m_last_frontface = true; - - m_redback = 0.4375f; - m_greenback = 0.4375f; - m_blueback = 0.4375f; - m_alphaback = 0.0f; - - glClearColor(m_redback,m_greenback,m_blueback,m_alphaback); - glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - - - glShadeModel(GL_SMOOTH); - - storage_init = m_storage->Init(); - - return true && storage_init; -} - - -void RAS_OpenGLRasterizer::SetAmbientColor(float color[3]) -{ - m_ambr = color[0]; - m_ambg = color[1]; - m_ambb = color[2]; -} - -void RAS_OpenGLRasterizer::SetAmbient(float factor) -{ - float ambient[] = {m_ambr * factor, m_ambg * factor, m_ambb * factor, 1.0f}; - glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient); -} - -void RAS_OpenGLRasterizer::SetBackColor(float color[3]) -{ - m_redback = color[0]; - m_greenback = color[1]; - m_blueback = color[2]; - m_alphaback = 0.0f; -} - -void RAS_OpenGLRasterizer::SetFog(short type, float start, float dist, float intensity, float color[3]) -{ - float params[4] = {color[0], color[1], color[2], 1.0f}; - glFogi(GL_FOG_MODE, GL_LINEAR); - glFogf(GL_FOG_DENSITY, intensity / 10.0f); - glFogf(GL_FOG_START, start); - glFogf(GL_FOG_END, start + dist); - glFogfv(GL_FOG_COLOR, params); -} - -void RAS_OpenGLRasterizer::EnableFog(bool enable) -{ - m_fogenabled = enable; -} - -void RAS_OpenGLRasterizer::DisplayFog() -{ - if ((m_drawingmode >= KX_SOLID) && m_fogenabled) { - glEnable(GL_FOG); - } - else { - glDisable(GL_FOG); - } -} - -bool RAS_OpenGLRasterizer::SetMaterial(const RAS_IPolyMaterial& mat) -{ - return mat.Activate(this, m_materialCachingInfo); -} - - - -void RAS_OpenGLRasterizer::Exit() -{ - m_storage->Exit(); - - glEnable(GL_CULL_FACE); - glEnable(GL_DEPTH_TEST); - glClearDepth(1.0f); - glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); - glClearColor(m_redback, m_greenback, m_blueback, m_alphaback); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - glDepthMask (GL_TRUE); - glDepthFunc(GL_LEQUAL); - glBlendFunc(GL_ONE, GL_ZERO); - - glDisable(GL_POLYGON_STIPPLE); - - glDisable(GL_LIGHTING); - if (GLEW_EXT_separate_specular_color || GLEW_VERSION_1_2) - glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR); - - EndFrame(); -} - -bool RAS_OpenGLRasterizer::BeginFrame(double time) -{ - m_time = time; - - // Blender camera routine destroys the settings - if (m_drawingmode < KX_SOLID) - { - glDisable(GL_CULL_FACE); - glDisable(GL_DEPTH_TEST); - } - else - { - glEnable(GL_DEPTH_TEST); - glEnable(GL_CULL_FACE); - } - - glDisable(GL_BLEND); - glDisable(GL_ALPHA_TEST); - //m_last_alphablend = GPU_BLEND_SOLID; - GPU_set_material_alpha_blend(GPU_BLEND_SOLID); - - glFrontFace(GL_CCW); - m_last_frontface = true; - - glShadeModel(GL_SMOOTH); - - glEnable(GL_MULTISAMPLE_ARB); - - m_2DCanvas->BeginFrame(); - - // Render Tools - m_clientobject = NULL; - m_lastlightlayer = -1; - m_lastauxinfo = NULL; - m_lastlighting = true; /* force disable in DisableOpenGLLights() */ - DisableOpenGLLights(); - - return true; -} - - - -void RAS_OpenGLRasterizer::SetDrawingMode(int drawingmode) -{ - m_drawingmode = drawingmode; - - if (m_drawingmode == KX_WIREFRAME) - glDisable(GL_CULL_FACE); - - m_storage->SetDrawingMode(drawingmode); -} - -int RAS_OpenGLRasterizer::GetDrawingMode() -{ - return m_drawingmode; -} - - -void RAS_OpenGLRasterizer::SetDepthMask(DepthMask depthmask) -{ - glDepthMask(depthmask == KX_DEPTHMASK_DISABLED ? GL_FALSE : GL_TRUE); -} - - -void RAS_OpenGLRasterizer::ClearColorBuffer() -{ - m_2DCanvas->ClearColor(m_redback,m_greenback,m_blueback,m_alphaback); - m_2DCanvas->ClearBuffer(RAS_ICanvas::COLOR_BUFFER); -} - - -void RAS_OpenGLRasterizer::ClearDepthBuffer() -{ - m_2DCanvas->ClearBuffer(RAS_ICanvas::DEPTH_BUFFER); -} - - -void RAS_OpenGLRasterizer::ClearCachingInfo(void) -{ - m_materialCachingInfo = 0; -} - -void RAS_OpenGLRasterizer::FlushDebugShapes(SCA_IScene *scene) -{ - std::vector &debugShapes = m_debugShapes[scene]; - if (debugShapes.empty()) - return; - - // DrawDebugLines - GLboolean light, tex; - - light= glIsEnabled(GL_LIGHTING); - tex= glIsEnabled(GL_TEXTURE_2D); - - if (light) glDisable(GL_LIGHTING); - if (tex) glDisable(GL_TEXTURE_2D); - - // draw lines - glBegin(GL_LINES); - for (unsigned int i = 0; i < debugShapes.size(); i++) { - if (debugShapes[i].m_type != OglDebugShape::LINE) - continue; - glColor4f(debugShapes[i].m_color[0], debugShapes[i].m_color[1], debugShapes[i].m_color[2], 1.0f); - const MT_Scalar *fromPtr = &debugShapes[i].m_pos.x(); - const MT_Scalar *toPtr= &debugShapes[i].m_param.x(); - glVertex3fv(fromPtr); - glVertex3fv(toPtr); - } - glEnd(); - - // draw circles - for (unsigned int i = 0; i < debugShapes.size(); i++) { - if (debugShapes[i].m_type != OglDebugShape::CIRCLE) - continue; - glBegin(GL_LINE_LOOP); - glColor4f(debugShapes[i].m_color[0], debugShapes[i].m_color[1], debugShapes[i].m_color[2], 1.0f); - - static const MT_Vector3 worldUp(0.0f, 0.0f, 1.0f); - MT_Vector3 norm = debugShapes[i].m_param; - MT_Matrix3x3 tr; - if (norm.fuzzyZero() || norm == worldUp) - { - tr.setIdentity(); - } - else - { - MT_Vector3 xaxis, yaxis; - xaxis = MT_cross(norm, worldUp); - yaxis = MT_cross(xaxis, norm); - tr.setValue(xaxis.x(), xaxis.y(), xaxis.z(), - yaxis.x(), yaxis.y(), yaxis.z(), - norm.x(), norm.y(), norm.z()); - } - MT_Scalar rad = debugShapes[i].m_param2.x(); - int n = (int)debugShapes[i].m_param2.y(); - for (int j = 0; jEndFrame(); -} - -void RAS_OpenGLRasterizer::SetRenderArea() -{ - RAS_Rect area; - // only above/below stereo method needs viewport adjustment - switch (m_stereomode) - { - case RAS_STEREO_ABOVEBELOW: - switch (m_curreye) { - case RAS_STEREO_LEFTEYE: - // upper half of window - area.SetLeft(0); - area.SetBottom(m_2DCanvas->GetHeight() - - int(m_2DCanvas->GetHeight() - m_noOfScanlines) / 2); - - area.SetRight(int(m_2DCanvas->GetWidth())); - area.SetTop(int(m_2DCanvas->GetHeight())); - m_2DCanvas->SetDisplayArea(&area); - break; - case RAS_STEREO_RIGHTEYE: - // lower half of window - area.SetLeft(0); - area.SetBottom(0); - area.SetRight(int(m_2DCanvas->GetWidth())); - area.SetTop(int(m_2DCanvas->GetHeight() - m_noOfScanlines) / 2); - m_2DCanvas->SetDisplayArea(&area); - break; - } - break; - case RAS_STEREO_3DTVTOPBOTTOM: - switch (m_curreye) { - case RAS_STEREO_LEFTEYE: - // upper half of window - area.SetLeft(0); - area.SetBottom(m_2DCanvas->GetHeight() - - m_2DCanvas->GetHeight() / 2); - - area.SetRight(m_2DCanvas->GetWidth()); - area.SetTop(m_2DCanvas->GetHeight()); - m_2DCanvas->SetDisplayArea(&area); - break; - case RAS_STEREO_RIGHTEYE: - // lower half of window - area.SetLeft(0); - area.SetBottom(0); - area.SetRight(m_2DCanvas->GetWidth()); - area.SetTop(m_2DCanvas->GetHeight() / 2); - m_2DCanvas->SetDisplayArea(&area); - break; - } - break; - case RAS_STEREO_SIDEBYSIDE: - switch (m_curreye) - { - case RAS_STEREO_LEFTEYE: - // Left half of window - area.SetLeft(0); - area.SetBottom(0); - area.SetRight(m_2DCanvas->GetWidth()/2); - area.SetTop(m_2DCanvas->GetHeight()); - m_2DCanvas->SetDisplayArea(&area); - break; - case RAS_STEREO_RIGHTEYE: - // Right half of window - area.SetLeft(m_2DCanvas->GetWidth()/2); - area.SetBottom(0); - area.SetRight(m_2DCanvas->GetWidth()); - area.SetTop(m_2DCanvas->GetHeight()); - m_2DCanvas->SetDisplayArea(&area); - break; - } - break; - default: - // every available pixel - area.SetLeft(0); - area.SetBottom(0); - area.SetRight(int(m_2DCanvas->GetWidth())); - area.SetTop(int(m_2DCanvas->GetHeight())); - m_2DCanvas->SetDisplayArea(&area); - break; - } -} - -void RAS_OpenGLRasterizer::SetStereoMode(const StereoMode stereomode) -{ - m_stereomode = stereomode; -} - -RAS_IRasterizer::StereoMode RAS_OpenGLRasterizer::GetStereoMode() -{ - return m_stereomode; -} - -bool RAS_OpenGLRasterizer::Stereo() -{ - if (m_stereomode > RAS_STEREO_NOSTEREO) // > 0 - return true; - else - return false; -} - -bool RAS_OpenGLRasterizer::InterlacedStereo() -{ - return m_stereomode == RAS_STEREO_VINTERLACE || m_stereomode == RAS_STEREO_INTERLACED; -} - -void RAS_OpenGLRasterizer::SetEye(const StereoEye eye) -{ - m_curreye = eye; - switch (m_stereomode) - { - case RAS_STEREO_QUADBUFFERED: - glDrawBuffer(m_curreye == RAS_STEREO_LEFTEYE ? GL_BACK_LEFT : GL_BACK_RIGHT); - break; - case RAS_STEREO_ANAGLYPH: - if (m_curreye == RAS_STEREO_LEFTEYE) { - glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_FALSE); - } - else { - //glAccum(GL_LOAD, 1.0f); - glColorMask(GL_FALSE, GL_TRUE, GL_TRUE, GL_FALSE); - ClearDepthBuffer(); - } - break; - case RAS_STEREO_VINTERLACE: - { - // OpenGL stippling is deprecated, it is no longer possible to affect all shaders - // this way, offscreen rendering and then compositing may be the better solution - glEnable(GL_POLYGON_STIPPLE); - glPolygonStipple((const GLubyte*) ((m_curreye == RAS_STEREO_LEFTEYE) ? left_eye_vinterlace_mask : right_eye_vinterlace_mask)); - if (m_curreye == RAS_STEREO_RIGHTEYE) - ClearDepthBuffer(); - break; - } - case RAS_STEREO_INTERLACED: - { - glEnable(GL_POLYGON_STIPPLE); - glPolygonStipple((const GLubyte*) &hinterlace_mask[m_curreye == RAS_STEREO_LEFTEYE?0:1]); - if (m_curreye == RAS_STEREO_RIGHTEYE) - ClearDepthBuffer(); - break; - } - default: - break; - } -} - -RAS_IRasterizer::StereoEye RAS_OpenGLRasterizer::GetEye() -{ - return m_curreye; -} - - -void RAS_OpenGLRasterizer::SetEyeSeparation(const float eyeseparation) -{ - m_eyeseparation = eyeseparation; -} - -float RAS_OpenGLRasterizer::GetEyeSeparation() -{ - return m_eyeseparation; -} - -void RAS_OpenGLRasterizer::SetFocalLength(const float focallength) -{ - m_focallength = focallength; - m_setfocallength = true; -} - -float RAS_OpenGLRasterizer::GetFocalLength() -{ - return m_focallength; -} - -RAS_IOffScreen *RAS_OpenGLRasterizer::CreateOffScreen(int width, int height, int samples, int target) -{ - RAS_IOffScreen *ofs; - - ofs = new RAS_OpenGLOffScreen(m_2DCanvas); - - if (!ofs->Create(width, height, samples, (RAS_IOffScreen::RAS_OFS_RENDER_TARGET)target)) { - delete ofs; - return NULL; - } - return ofs; -} - -RAS_ISync *RAS_OpenGLRasterizer::CreateSync(int type) -{ - RAS_ISync *sync; - - sync = new RAS_OpenGLSync(); - - if (!sync->Create((RAS_ISync::RAS_SYNC_TYPE)type)) { - delete sync; - return NULL; - } - return sync; -} - -void RAS_OpenGLRasterizer::SwapBuffers() -{ - m_2DCanvas->SwapBuffers(); -} - - - -const MT_Matrix4x4& RAS_OpenGLRasterizer::GetViewMatrix() const -{ - return m_viewmatrix; -} - -const MT_Matrix4x4& RAS_OpenGLRasterizer::GetViewInvMatrix() const -{ - return m_viewinvmatrix; -} - -void RAS_OpenGLRasterizer::IndexPrimitives_3DText(RAS_MeshSlot& ms, - class RAS_IPolyMaterial* polymat) -{ - bool obcolor = ms.m_bObjectColor; - MT_Vector4& rgba = ms.m_RGBAcolor; - RAS_MeshSlot::iterator it; - - const STR_String& mytext = ((CValue*)m_clientobject)->GetPropertyText("Text"); - - // handle object color - if (obcolor) { - glDisableClientState(GL_COLOR_ARRAY); - glColor4d(rgba[0], rgba[1], rgba[2], rgba[3]); - } - else - glEnableClientState(GL_COLOR_ARRAY); - - for (ms.begin(it); !ms.end(it); ms.next(it)) { - RAS_TexVert *vertex; - size_t i, j, numvert; - - numvert = it.array->m_type; - - if (it.array->m_type == RAS_DisplayArray::LINE) { - // line drawing, no text - glBegin(GL_LINES); - - for (i=0; igetXYZ()); - - vertex = &it.vertex[it.index[i+1]]; - glVertex3fv(vertex->getXYZ()); - } - - glEnd(); - } - else { - // triangle and quad text drawing - for (i=0; igetXYZ()[0]; - v[j][1] = vertex->getXYZ()[1]; - v[j][2] = vertex->getXYZ()[2]; - v_ptr[j] = v[j]; - - uv_ptr[j] = vertex->getUV(0); - } - - // find the right opengl attribute - glattrib = -1; - if (GLEW_ARB_vertex_program) - for (unit=0; unitGetDrawingMode(), mytext, mytext.Length(), polymat->GetMCol(), - v_ptr, uv_ptr, glattrib); - - ClearCachingInfo(); - } - } - } - - glDisableClientState(GL_COLOR_ARRAY); -} - -void RAS_OpenGLRasterizer::SetTexCoordNum(int num) -{ - m_texco_num = num; - if (m_texco_num > RAS_MAX_TEXCO) - m_texco_num = RAS_MAX_TEXCO; -} - -void RAS_OpenGLRasterizer::SetAttribNum(int num) -{ - m_attrib_num = num; - if (m_attrib_num > RAS_MAX_ATTRIB) - m_attrib_num = RAS_MAX_ATTRIB; -} - -void RAS_OpenGLRasterizer::SetTexCoord(TexCoGen coords, int unit) -{ - // this changes from material to material - if (unit < RAS_MAX_TEXCO) - m_texco[unit] = coords; -} - -void RAS_OpenGLRasterizer::SetAttrib(TexCoGen coords, int unit, int layer) -{ - // this changes from material to material - if (unit < RAS_MAX_ATTRIB) { - m_attrib[unit] = coords; - m_attrib_layer[unit] = layer; - } -} - -void RAS_OpenGLRasterizer::IndexPrimitives(RAS_MeshSlot& ms) -{ - if (ms.m_pDerivedMesh) - DrawDerivedMesh(ms); - else - m_storage->IndexPrimitives(ms); -} - -// Code for hooking into Blender's mesh drawing for derived meshes. -// If/when we use more of Blender's drawing code, we may be able to -// clean this up -static bool current_wireframe; -static RAS_MaterialBucket *current_bucket; -static RAS_IPolyMaterial *current_polymat; -static RAS_MeshSlot *current_ms; -static RAS_MeshObject *current_mesh; -static int current_blmat_nr; -static GPUVertexAttribs current_gpu_attribs; -static int CheckMaterialDM(int matnr, void *attribs) -{ - // only draw the current material - if (matnr != current_blmat_nr) - return 0; - GPUVertexAttribs *gattribs = (GPUVertexAttribs *)attribs; - if (gattribs) - memcpy(gattribs, ¤t_gpu_attribs, sizeof(GPUVertexAttribs)); - return 1; -} - -void RAS_OpenGLRasterizer::DrawDerivedMesh(class RAS_MeshSlot &ms) -{ - // mesh data is in derived mesh - current_bucket = ms.m_bucket; - current_polymat = current_bucket->GetPolyMaterial(); - current_ms = &ms; - current_mesh = ms.m_mesh; - current_wireframe = m_drawingmode <= RAS_IRasterizer::KX_WIREFRAME; - // MCol *mcol = (MCol*)ms.m_pDerivedMesh->getFaceDataArray(ms.m_pDerivedMesh, CD_MCOL); /* UNUSED */ - - // handle two-side - if (current_polymat->GetDrawingMode() & RAS_IRasterizer::KX_BACKCULL) - this->SetCullFace(true); - else - this->SetCullFace(false); - -#if 0 - if (current_polymat->GetFlag() & RAS_BLENDERGLSL) -#endif - { - // GetMaterialIndex return the original mface material index, - // increment by 1 to match what derived mesh is doing - current_blmat_nr = current_polymat->GetMaterialIndex()+1; - // For GLSL we need to retrieve the GPU material attribute - Material* blmat = current_polymat->GetBlenderMaterial(); - Scene* blscene = current_polymat->GetBlenderScene(); - if (!current_wireframe && blscene && blmat) - GPU_material_vertex_attributes(GPU_material_from_blender(blscene, blmat, false), ¤t_gpu_attribs); - else - memset(¤t_gpu_attribs, 0, sizeof(current_gpu_attribs)); - // DM draw can mess up blending mode, restore at the end - int current_blend_mode = GPU_get_material_alpha_blend(); - ms.m_pDerivedMesh->drawFacesGLSL(ms.m_pDerivedMesh, CheckMaterialDM); - GPU_set_material_alpha_blend(current_blend_mode); - } -} - -void RAS_OpenGLRasterizer::SetProjectionMatrix(MT_CmMatrix4x4 &mat) -{ - glMatrixMode(GL_PROJECTION); - float* matrix = &mat(0, 0); - glLoadMatrixf(matrix); - - m_camortho = (mat(3, 3) != 0.0f); -} - -void RAS_OpenGLRasterizer::SetProjectionMatrix(const MT_Matrix4x4 & mat) -{ - glMatrixMode(GL_PROJECTION); - float matrix[16]; - /* Get into argument. Looks a bit dodgy, but it's ok. */ - mat.getValue(matrix); - glLoadMatrixf(matrix); - - m_camortho = (mat[3][3] != 0.0f); -} - -MT_Matrix4x4 RAS_OpenGLRasterizer::GetFrustumMatrix( - float left, - float right, - float bottom, - float top, - float frustnear, - float frustfar, - float focallength, - bool -) { - MT_Matrix4x4 result; - float mat[16]; - - // correction for stereo - if (Stereo()) - { - float near_div_focallength; - float offset; - - // if Rasterizer.setFocalLength is not called we use the camera focallength - if (!m_setfocallength) - // if focallength is null we use a value known to be reasonable - m_focallength = (focallength == 0.f) ? m_eyeseparation * 30.0f - : focallength; - - near_div_focallength = frustnear / m_focallength; - offset = 0.5f * m_eyeseparation * near_div_focallength; - switch (m_curreye) { - case RAS_STEREO_LEFTEYE: - left += offset; - right += offset; - break; - case RAS_STEREO_RIGHTEYE: - left -= offset; - right -= offset; - break; - } - // leave bottom and top untouched - if (m_stereomode == RAS_STEREO_3DTVTOPBOTTOM) { - // restore the vertical frustum because the 3DTV will - // expand the top and bottom part to the full size of the screen - bottom *= 2.0f; - top *= 2.0f; - } - } - - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glFrustum(left, right, bottom, top, frustnear, frustfar); - - glGetFloatv(GL_PROJECTION_MATRIX, mat); - result.setValue(mat); - - return result; -} - -MT_Matrix4x4 RAS_OpenGLRasterizer::GetOrthoMatrix( - float left, - float right, - float bottom, - float top, - float frustnear, - float frustfar -) { - MT_Matrix4x4 result; - float mat[16]; - - // stereo is meaningless for orthographic, disable it - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glOrtho(left, right, bottom, top, frustnear, frustfar); - - glGetFloatv(GL_PROJECTION_MATRIX, mat); - result.setValue(mat); - - return result; -} - - -// next arguments probably contain redundant info, for later... -void RAS_OpenGLRasterizer::SetViewMatrix(const MT_Matrix4x4 &mat, - const MT_Matrix3x3 & camOrientMat3x3, - const MT_Point3 & pos, - const MT_Vector3 &scale, - bool perspective) -{ - m_viewmatrix = mat; - - // correction for stereo - if (Stereo() && perspective) - { - MT_Vector3 unitViewDir(0.0f, -1.0f, 0.0f); // minus y direction, Blender convention - MT_Vector3 unitViewupVec(0.0f, 0.0f, 1.0f); - MT_Vector3 viewDir, viewupVec; - MT_Vector3 eyeline; - - // actual viewDir - viewDir = camOrientMat3x3 * unitViewDir; // this is the moto convention, vector on right hand side - // actual viewup vec - viewupVec = camOrientMat3x3 * unitViewupVec; - - // vector between eyes - eyeline = viewDir.cross(viewupVec); - - switch (m_curreye) { - case RAS_STEREO_LEFTEYE: - { - // translate to left by half the eye distance - MT_Transform transform; - transform.setIdentity(); - transform.translate(-(eyeline * m_eyeseparation / 2.0f)); - m_viewmatrix *= transform; - } - break; - case RAS_STEREO_RIGHTEYE: - { - // translate to right by half the eye distance - MT_Transform transform; - transform.setIdentity(); - transform.translate(eyeline * m_eyeseparation / 2.0f); - m_viewmatrix *= transform; - } - break; - } - } - - bool negX = (scale[0] < 0.0f); - bool negY = (scale[1] < 0.0f); - bool negZ = (scale[2] < 0.0f); - if (negX || negY || negZ) { - m_viewmatrix.tscale((negX)?-1.0f:1.0f, (negY)?-1.0f:1.0f, (negZ)?-1.0f:1.0f, 1.0); - } - m_viewinvmatrix = m_viewmatrix; - m_viewinvmatrix.invert(); - - // note: getValue gives back column major as needed by OpenGL - MT_Scalar glviewmat[16]; - m_viewmatrix.getValue(glviewmat); - - glMatrixMode(GL_MODELVIEW); - glLoadMatrixf(glviewmat); - m_campos = pos; - m_camnegscale = negX ^ negY ^ negZ; -} - - -const MT_Point3& RAS_OpenGLRasterizer::GetCameraPosition() -{ - return m_campos; -} - -bool RAS_OpenGLRasterizer::GetCameraOrtho() -{ - return m_camortho; -} - -void RAS_OpenGLRasterizer::SetCullFace(bool enable) -{ - if (enable) - glEnable(GL_CULL_FACE); - else - glDisable(GL_CULL_FACE); -} - -void RAS_OpenGLRasterizer::SetLines(bool enable) -{ - if (enable) - glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); - else - glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); -} - -void RAS_OpenGLRasterizer::SetSpecularity(float specX, - float specY, - float specZ, - float specval) -{ - GLfloat mat_specular[] = {specX, specY, specZ, specval}; - glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular); -} - - - -void RAS_OpenGLRasterizer::SetShinyness(float shiny) -{ - GLfloat mat_shininess[] = { shiny }; - glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess); -} - - - -void RAS_OpenGLRasterizer::SetDiffuse(float difX,float difY,float difZ,float diffuse) -{ - GLfloat mat_diffuse [] = {difX, difY,difZ, diffuse}; - glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_diffuse); -} - -void RAS_OpenGLRasterizer::SetEmissive(float eX, float eY, float eZ, float e) -{ - GLfloat mat_emit [] = {eX,eY,eZ,e}; - glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, mat_emit); -} - - -double RAS_OpenGLRasterizer::GetTime() -{ - return m_time; -} - -void RAS_OpenGLRasterizer::SetPolygonOffset(float mult, float add) -{ - glPolygonOffset(mult, add); - GLint mode = GL_POLYGON_OFFSET_FILL; - if (m_drawingmode < KX_SHADED) - mode = GL_POLYGON_OFFSET_LINE; - if (mult != 0.0f || add != 0.0f) - glEnable(mode); - else - glDisable(mode); -} - -void RAS_OpenGLRasterizer::EnableMotionBlur(float motionblurvalue) -{ - /* don't just set m_motionblur to 1, but check if it is 0 so - * we don't reset a motion blur that is already enabled */ - if (m_motionblur == 0) - m_motionblur = 1; - m_motionblurvalue = motionblurvalue; -} - -void RAS_OpenGLRasterizer::DisableMotionBlur() -{ - m_motionblur = 0; - m_motionblurvalue = -1.0f; -} - -void RAS_OpenGLRasterizer::SetAlphaBlend(int alphablend) -{ - /* Variance shadow maps don't handle alpha well, best to not allow it for now */ - if (m_drawingmode == KX_SHADOW && m_usingoverrideshader) - GPU_set_material_alpha_blend(GPU_BLEND_SOLID); - else - GPU_set_material_alpha_blend(alphablend); -/* - if (alphablend == m_last_alphablend) - return; - - if (alphablend == GPU_BLEND_SOLID) { - glDisable(GL_BLEND); - glDisable(GL_ALPHA_TEST); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - } - else if (alphablend == GPU_BLEND_ADD) { - glBlendFunc(GL_ONE, GL_ONE); - glEnable(GL_BLEND); - glDisable(GL_ALPHA_TEST); - } - else if (alphablend == GPU_BLEND_ALPHA) { - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glEnable(GL_BLEND); - glEnable(GL_ALPHA_TEST); - glAlphaFunc(GL_GREATER, 0.0f); - } - else if (alphablend == GPU_BLEND_CLIP) { - glDisable(GL_BLEND); - glEnable(GL_ALPHA_TEST); - glAlphaFunc(GL_GREATER, 0.5f); - } - - m_last_alphablend = alphablend; -*/ -} - -void RAS_OpenGLRasterizer::SetFrontFace(bool ccw) -{ - if (m_camnegscale) - ccw = !ccw; - - if (m_last_frontface == ccw) - return; - - if (ccw) - glFrontFace(GL_CCW); - else - glFrontFace(GL_CW); - - m_last_frontface = ccw; -} - -void RAS_OpenGLRasterizer::SetAnisotropicFiltering(short level) -{ - GPU_set_anisotropic((float)level); -} - -short RAS_OpenGLRasterizer::GetAnisotropicFiltering() -{ - return (short)GPU_get_anisotropic(); -} - -void RAS_OpenGLRasterizer::SetMipmapping(MipmapOption val) -{ - if (val == RAS_IRasterizer::RAS_MIPMAP_LINEAR) - { - GPU_set_linear_mipmap(1); - GPU_set_mipmap(1); - } - else if (val == RAS_IRasterizer::RAS_MIPMAP_NEAREST) - { - GPU_set_linear_mipmap(0); - GPU_set_mipmap(1); - } - else - { - GPU_set_linear_mipmap(0); - GPU_set_mipmap(0); - } -} - -RAS_IRasterizer::MipmapOption RAS_OpenGLRasterizer::GetMipmapping() -{ - if (GPU_get_mipmap()) { - if (GPU_get_linear_mipmap()) { - return RAS_IRasterizer::RAS_MIPMAP_LINEAR; - } - else { - return RAS_IRasterizer::RAS_MIPMAP_NEAREST; - } - } - else { - return RAS_IRasterizer::RAS_MIPMAP_NONE; - } -} - -void RAS_OpenGLRasterizer::SetUsingOverrideShader(bool val) -{ - m_usingoverrideshader = val; -} - -bool RAS_OpenGLRasterizer::GetUsingOverrideShader() -{ - return m_usingoverrideshader; -} - -/** - * Render Tools - */ - -/* ProcessLighting performs lighting on objects. the layer is a bitfield that - * contains layer information. There are 20 'official' layers in blender. A - * light is applied on an object only when they are in the same layer. OpenGL - * has a maximum of 8 lights (simultaneous), so 20 * 8 lights are possible in - * a scene. */ - -void RAS_OpenGLRasterizer::ProcessLighting(bool uselights, const MT_Transform& viewmat) -{ - bool enable = false; - int layer= -1; - - /* find the layer */ - if (uselights) { - if (m_clientobject) - layer = static_cast(m_clientobject)->GetLayer(); - } - - /* avoid state switching */ - if (m_lastlightlayer == layer && m_lastauxinfo == m_auxilaryClientInfo) - return; - - m_lastlightlayer = layer; - m_lastauxinfo = m_auxilaryClientInfo; - - /* enable/disable lights as needed */ - if (layer >= 0) { - //enable = ApplyLights(layer, viewmat); - // taken from blender source, incompatibility between Blender Object / GameObject - KX_Scene* kxscene = (KX_Scene*)m_auxilaryClientInfo; - float glviewmat[16]; - unsigned int count; - std::vector::iterator lit = m_lights.begin(); - - for (count=0; countApplyFixedFunctionLighting(kxscene, layer, count)) - count++; - } - glPopMatrix(); - - enable = count > 0; - } - - if (enable) - EnableOpenGLLights(); - else - DisableOpenGLLights(); -} - -void RAS_OpenGLRasterizer::EnableOpenGLLights() -{ - if (m_lastlighting == true) - return; - - glEnable(GL_LIGHTING); - glEnable(GL_COLOR_MATERIAL); - - glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); - glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE); - glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, (GetCameraOrtho())? GL_FALSE: GL_TRUE); - if (GLEW_EXT_separate_specular_color || GLEW_VERSION_1_2) - glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR); - - m_lastlighting = true; -} - -void RAS_OpenGLRasterizer::DisableOpenGLLights() -{ - if (m_lastlighting == false) - return; - - glDisable(GL_LIGHTING); - glDisable(GL_COLOR_MATERIAL); - - m_lastlighting = false; -} - -RAS_ILightObject *RAS_OpenGLRasterizer::CreateLight() -{ - return new RAS_OpenGLLight(this); -} - -void RAS_OpenGLRasterizer::AddLight(RAS_ILightObject* lightobject) -{ - RAS_OpenGLLight* gllight = dynamic_cast(lightobject); - assert(gllight); - m_lights.push_back(gllight); -} - -void RAS_OpenGLRasterizer::RemoveLight(RAS_ILightObject* lightobject) -{ - RAS_OpenGLLight* gllight = dynamic_cast(lightobject); - assert(gllight); - - std::vector::iterator lit = - std::find(m_lights.begin(),m_lights.end(),gllight); - - if (!(lit==m_lights.end())) - m_lights.erase(lit); -} - -bool RAS_OpenGLRasterizer::RayHit(struct KX_ClientObjectInfo *client, KX_RayCast *result, float *oglmatrix) -{ - if (result->m_hitMesh) { - - RAS_Polygon* poly = result->m_hitMesh->GetPolygon(result->m_hitPolygon); - if (!poly->IsVisible()) - return false; - - MT_Vector3 resultnormal(result->m_hitNormal); - MT_Vector3 left(oglmatrix[0],oglmatrix[1],oglmatrix[2]); - MT_Vector3 dir = -(left.cross(resultnormal)).safe_normalized(); - left = (dir.cross(resultnormal)).safe_normalized(); - // for the up vector, we take the 'resultnormal' returned by the physics - - float maat[16] = {left[0], left[1], left[2], 0, - dir[0], dir[1], dir[2], 0, - resultnormal[0], resultnormal[1], resultnormal[2], 0, - 0, 0, 0, 1}; - - glTranslatef(oglmatrix[12],oglmatrix[13],oglmatrix[14]); - //glMultMatrixd(oglmatrix); - glMultMatrixf(maat); - return true; - } - else { - return false; - } -} - -void RAS_OpenGLRasterizer::applyTransform(float* oglmatrix,int objectdrawmode ) -{ - /* FIXME: - blender: intern/moto/include/MT_Vector3.inl:42: MT_Vector3 operator/(const - MT_Vector3&, double): Assertion `!MT_fuzzyZero(s)' failed. - - Program received signal SIGABRT, Aborted. - [Switching to Thread 16384 (LWP 1519)] - 0x40477571 in kill () from /lib/libc.so.6 - (gdb) bt - #7 0x08334368 in MT_Vector3::normalized() const () - #8 0x0833e6ec in RAS_OpenGLRasterizer::applyTransform(RAS_IRasterizer*, double*, int) () - */ - - if (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED || - objectdrawmode & RAS_IPolyMaterial::BILLBOARD_AXISALIGNED) - { - // rotate the billboard/halo - //page 360/361 3D Game Engine Design, David Eberly for a discussion - // on screen aligned and axis aligned billboards - // assumed is that the preprocessor transformed all billboard polygons - // so that their normal points into the positive x direction (1.0f, 0.0f, 0.0f) - // when new parenting for objects is done, this rotation - // will be moved into the object - - MT_Point3 objpos (oglmatrix[12],oglmatrix[13],oglmatrix[14]); - MT_Point3 campos = GetCameraPosition(); - MT_Vector3 dir = (campos - objpos).safe_normalized(); - MT_Vector3 up(0,0,1.0f); - - KX_GameObject* gameobj = (KX_GameObject*)m_clientobject; - // get scaling of halo object - MT_Vector3 size = gameobj->GetSGNode()->GetWorldScaling(); - - bool screenaligned = (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED)!=0;//false; //either screen or axisaligned - if (screenaligned) - { - up = (up - up.dot(dir) * dir).safe_normalized(); - } else - { - dir = (dir - up.dot(dir)*up).safe_normalized(); - } - - MT_Vector3 left = dir.normalized(); - dir = (up.cross(left)).normalized(); - - // we have calculated the row vectors, now we keep - // local scaling into account: - - left *= size[0]; - dir *= size[1]; - up *= size[2]; - - float maat[16] = {left[0], left[1], left[2], 0, - dir[0], dir[1], dir[2], 0, - up[0], up[1], up[2], 0, - 0, 0, 0, 1}; - - glTranslatef(objpos[0],objpos[1],objpos[2]); - glMultMatrixf(maat); - - } - else { - if (objectdrawmode & RAS_IPolyMaterial::SHADOW) - { - // shadow must be cast to the ground, physics system needed here! - MT_Point3 frompoint(oglmatrix[12],oglmatrix[13],oglmatrix[14]); - KX_GameObject *gameobj = (KX_GameObject*)m_clientobject; - MT_Vector3 direction = MT_Vector3(0,0,-1); - - direction.normalize(); - direction *= 100000; - - MT_Point3 topoint = frompoint + direction; - - KX_Scene* kxscene = (KX_Scene*) m_auxilaryClientInfo; - PHY_IPhysicsEnvironment* physics_environment = kxscene->GetPhysicsEnvironment(); - PHY_IPhysicsController* physics_controller = gameobj->GetPhysicsController(); - - KX_GameObject *parent = gameobj->GetParent(); - if (!physics_controller && parent) - physics_controller = parent->GetPhysicsController(); - - KX_RayCast::Callback callback(this, physics_controller, oglmatrix); - if (!KX_RayCast::RayTest(physics_environment, frompoint, topoint, callback)) - { - // couldn't find something to cast the shadow on... - glMultMatrixf(oglmatrix); - } - else - { // we found the "ground", but the cast matrix doesn't take - // scaling in consideration, so we must apply the object scale - MT_Vector3 size = gameobj->GetSGNode()->GetLocalScale(); - glScalef(size[0], size[1], size[2]); - } - } else - { - - // 'normal' object - glMultMatrixf(oglmatrix); - } - } -} - -static void DisableForText() -{ - glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); /* needed for texture fonts otherwise they render as wireframe */ - - glDisable(GL_BLEND); - glDisable(GL_ALPHA_TEST); - - glDisable(GL_LIGHTING); - glDisable(GL_COLOR_MATERIAL); - - if (GLEW_ARB_multitexture) { - for (int i=0; i= 0.0f && motionblurvalue <= 1.0f) { - glAccum(GL_MULT, motionblurvalue); - glAccum(GL_ACCUM, 1-motionblurvalue); - glAccum(GL_RETURN, 1.0f); - glFlush(); - } - } -} - -void RAS_OpenGLRasterizer::SetClientObject(void* obj) -{ - if (m_clientobject != obj) - { - bool ccw = (obj == NULL || !((KX_GameObject*)obj)->IsNegativeScaling()); - SetFrontFace(ccw); - - m_clientobject = obj; - } -} - -void RAS_OpenGLRasterizer::SetAuxilaryClientInfo(void* inf) -{ - m_auxilaryClientInfo = inf; -} - -void RAS_OpenGLRasterizer::PrintHardwareInfo() -{ - #define pprint(x) std::cout << x << std::endl; - - pprint("GL_VENDOR: " << glGetString(GL_VENDOR)); - pprint("GL_RENDERER: " << glGetString(GL_RENDERER)); - pprint("GL_VERSION: " << glGetString(GL_VERSION)); - bool support=0; - pprint("Supported Extensions..."); - pprint(" GL_ARB_shader_objects supported? "<< (GLEW_ARB_shader_objects?"yes.":"no.")); - - support= GLEW_ARB_vertex_shader; - pprint(" GL_ARB_vertex_shader supported? "<< (support?"yes.":"no.")); - if (support) { - pprint(" ----------Details----------"); - int max=0; - glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB, (GLint*)&max); - pprint(" Max uniform components." << max); - - glGetIntegerv(GL_MAX_VARYING_FLOATS_ARB, (GLint*)&max); - pprint(" Max varying floats." << max); - - glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB, (GLint*)&max); - pprint(" Max vertex texture units." << max); - - glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB, (GLint*)&max); - pprint(" Max combined texture units." << max); - pprint(""); - } - - support=GLEW_ARB_fragment_shader; - pprint(" GL_ARB_fragment_shader supported? "<< (support?"yes.":"no.")); - if (support) { - pprint(" ----------Details----------"); - int max=0; - glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB, (GLint*)&max); - pprint(" Max uniform components." << max); - pprint(""); - } - - support = GLEW_ARB_texture_cube_map; - pprint(" GL_ARB_texture_cube_map supported? "<< (support?"yes.":"no.")); - if (support) { - pprint(" ----------Details----------"); - int size=0; - glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB, (GLint*)&size); - pprint(" Max cubemap size." << size); - pprint(""); - } - - support = GLEW_ARB_multitexture; - pprint(" GL_ARB_multitexture supported? "<< (support?"yes.":"no.")); - if (support) { - pprint(" ----------Details----------"); - int units=0; - glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, (GLint*)&units); - pprint(" Max texture units available. " << units); - pprint(""); - } - - pprint(" GL_ARB_texture_env_combine supported? "<< (GLEW_ARB_texture_env_combine?"yes.":"no.")); - - pprint(" GL_ARB_texture_non_power_of_two supported " << (GPU_full_non_power_of_two_support()?"yes.":"no.")); -} - diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h deleted file mode 100644 index 9561e207dba..00000000000 --- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h +++ /dev/null @@ -1,343 +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 RAS_OpenGLRasterizer.h - * \ingroup bgerastogl - */ - -#ifndef __RAS_OPENGLRASTERIZER_H__ -#define __RAS_OPENGLRASTERIZER_H__ - -#ifdef _MSC_VER -# pragma warning (disable:4786) -#endif - -#include "MT_CmMatrix4x4.h" -#include -#include -using namespace std; - -#include "RAS_IRasterizer.h" -#include "RAS_MaterialBucket.h" -#include "RAS_IPolygonMaterial.h" - -#include "BLI_utildefines.h" - -class RAS_IStorage; -class RAS_ICanvas; -class RAS_OpenGLLight; - -#define RAS_MAX_TEXCO 8 /* match in BL_Material */ -#define RAS_MAX_ATTRIB 16 /* match in BL_BlenderShader */ - -enum RAS_STORAGE_TYPE { - RAS_AUTO_STORAGE, - RAS_VA, - RAS_VBO, -}; - -struct OglDebugShape -{ - enum SHAPE_TYPE{ - LINE, - CIRCLE, - }; - SHAPE_TYPE m_type; - MT_Vector3 m_pos; - MT_Vector3 m_param; - MT_Vector3 m_param2; - MT_Vector3 m_color; -}; - -/** - * 3D rendering device context. - */ -class RAS_OpenGLRasterizer : public RAS_IRasterizer -{ - RAS_ICanvas *m_2DCanvas; - - /* fogging vars */ - bool m_fogenabled; - - float m_redback; - float m_greenback; - float m_blueback; - float m_alphaback; - - float m_ambr; - float m_ambg; - float m_ambb; - double m_time; - MT_Matrix4x4 m_viewmatrix; - MT_Matrix4x4 m_viewinvmatrix; - MT_Point3 m_campos; - bool m_camortho; - bool m_camnegscale; - - StereoMode m_stereomode; - StereoEye m_curreye; - float m_eyeseparation; - float m_focallength; - bool m_setfocallength; - int m_noOfScanlines; - - short m_prevafvalue; - - /* motion blur */ - int m_motionblur; - float m_motionblurvalue; - - bool m_usingoverrideshader; - - /* Render tools */ - void *m_clientobject; - void *m_auxilaryClientInfo; - std::vector m_lights; - int m_lastlightlayer; - bool m_lastlighting; - void *m_lastauxinfo; - unsigned int m_numgllights; - -protected: - int m_drawingmode; - TexCoGen m_texco[RAS_MAX_TEXCO]; - TexCoGen m_attrib[RAS_MAX_ATTRIB]; - int m_attrib_layer[RAS_MAX_ATTRIB]; - int m_texco_num; - int m_attrib_num; - /* int m_last_alphablend; */ - bool m_last_frontface; - - /* Stores the caching information for the last material activated. */ - RAS_IPolyMaterial::TCachingInfo m_materialCachingInfo; - - /* Making use of a Strategy design pattern for storage behavior. - * Examples of concrete strategies: Vertex Arrays, VBOs, Immediate Mode*/ - int m_storage_type; - RAS_IStorage *m_storage; - -public: - double GetTime(); - RAS_OpenGLRasterizer(RAS_ICanvas *canv, RAS_STORAGE_TYPE storage); - virtual ~RAS_OpenGLRasterizer(); - - /*enum DrawType - { - KX_BOUNDINGBOX = 1, - KX_WIREFRAME, - KX_SOLID, - KX_SHADED, - KX_TEXTURED - }; - - enum DepthMask - { - KX_DEPTHMASK_ENABLED =1, - KX_DEPTHMASK_DISABLED, - };*/ - virtual void SetDepthMask(DepthMask depthmask); - - virtual bool SetMaterial(const RAS_IPolyMaterial &mat); - virtual bool Init(); - virtual void Exit(); - virtual bool BeginFrame(double time); - virtual void ClearColorBuffer(); - virtual void ClearDepthBuffer(); - virtual void ClearCachingInfo(void); - virtual void EndFrame(); - virtual void SetRenderArea(); - - virtual void SetStereoMode(const StereoMode stereomode); - virtual RAS_IRasterizer::StereoMode GetStereoMode(); - virtual bool Stereo(); - virtual bool InterlacedStereo(); - virtual void SetEye(const StereoEye eye); - virtual StereoEye GetEye(); - virtual void SetEyeSeparation(const float eyeseparation); - virtual float GetEyeSeparation(); - virtual void SetFocalLength(const float focallength); - virtual float GetFocalLength(); - virtual RAS_IOffScreen *CreateOffScreen(int width, int height, int samples, int target); - virtual RAS_ISync *CreateSync(int type); - virtual void SwapBuffers(); - - virtual void IndexPrimitives(class RAS_MeshSlot &ms); - virtual void IndexPrimitives_3DText(class RAS_MeshSlot &ms, class RAS_IPolyMaterial *polymat); - virtual void DrawDerivedMesh(class RAS_MeshSlot &ms); - - virtual void SetProjectionMatrix(MT_CmMatrix4x4 &mat); - virtual void SetProjectionMatrix(const MT_Matrix4x4 &mat); - virtual void SetViewMatrix( - const MT_Matrix4x4 &mat, - const MT_Matrix3x3 &ori, - const MT_Point3 &pos, - const MT_Vector3 &scale, - bool perspective); - - virtual const MT_Point3& GetCameraPosition(); - virtual bool GetCameraOrtho(); - - virtual void SetFog(short type, float start, float dist, float intensity, float color[3]); - virtual void EnableFog(bool enable); - virtual void DisplayFog(); - - virtual void SetBackColor(float color[3]); - - virtual void SetDrawingMode(int drawingmode); - virtual int GetDrawingMode(); - - virtual void SetCullFace(bool enable); - virtual void SetLines(bool enable); - - virtual MT_Matrix4x4 GetFrustumMatrix( - float left, float right, float bottom, float top, - float frustnear, float frustfar, - float focallength, bool perspective); - virtual MT_Matrix4x4 GetOrthoMatrix( - float left, float right, float bottom, float top, - float frustnear, float frustfar); - - virtual void SetSpecularity(float specX, float specY, float specZ, float specval); - virtual void SetShinyness(float shiny); - virtual void SetDiffuse(float difX, float difY, float difZ, float diffuse); - virtual void SetEmissive(float eX, float eY, float eZ, float e); - - virtual void SetAmbientColor(float color[3]); - virtual void SetAmbient(float factor); - - virtual void SetPolygonOffset(float mult, float add); - - virtual void FlushDebugShapes(SCA_IScene *scene); - - virtual void DrawDebugLine(SCA_IScene *scene, const MT_Vector3 &from,const MT_Vector3 &to, const MT_Vector3 &color) - { - OglDebugShape line; - line.m_type = OglDebugShape::LINE; - line.m_pos= from; - line.m_param = to; - line.m_color = color; - m_debugShapes[scene].push_back(line); - } - - virtual void DrawDebugCircle(SCA_IScene *scene, const MT_Vector3 ¢er, const MT_Scalar radius, - const MT_Vector3 &color, const MT_Vector3 &normal, int nsector) - { - OglDebugShape line; - line.m_type = OglDebugShape::CIRCLE; - line.m_pos= center; - line.m_param = normal; - line.m_color = color; - line.m_param2.x() = radius; - line.m_param2.y() = (float) nsector; - m_debugShapes[scene].push_back(line); - } - - // We store each debug shape by scene. - std::map > m_debugShapes; - - virtual void SetTexCoordNum(int num); - virtual void SetAttribNum(int num); - virtual void SetTexCoord(TexCoGen coords, int unit); - virtual void SetAttrib(TexCoGen coords, int unit, int layer = 0); - - void TexCoord(const RAS_TexVert &tv); - - const MT_Matrix4x4 &GetViewMatrix() const; - const MT_Matrix4x4 &GetViewInvMatrix() const; - - virtual void EnableMotionBlur(float motionblurvalue); - virtual void DisableMotionBlur(); - virtual float GetMotionBlurValue() { return m_motionblurvalue; } - virtual int GetMotionBlurState() { return m_motionblur; } - virtual void SetMotionBlurState(int newstate) - { - if (newstate < 0) - m_motionblur = 0; - else if (newstate > 2) - m_motionblur = 2; - else - m_motionblur = newstate; - } - - virtual void SetAlphaBlend(int alphablend); - virtual void SetFrontFace(bool ccw); - - virtual void SetAnisotropicFiltering(short level); - virtual short GetAnisotropicFiltering(); - - virtual void SetMipmapping(MipmapOption val); - virtual MipmapOption GetMipmapping(); - - virtual void SetUsingOverrideShader(bool val); - virtual bool GetUsingOverrideShader(); - - /** - * Render Tools - */ - void EnableOpenGLLights(); - void DisableOpenGLLights(); - void ProcessLighting(bool uselights, const MT_Transform &viewmat); - - void RenderBox2D(int xco, int yco, int width, int height, float percentage); - void RenderText3D(int fontid, const char *text, int size, int dpi, - const float color[4], const float mat[16], float aspect); - void RenderText2D(RAS_TEXT_RENDER_MODE mode, const char *text, - int xco, int yco, int width, int height); - - void applyTransform(float *oglmatrix, int objectdrawmode); - - void PushMatrix(); - void PopMatrix(); - - /// \see KX_RayCast - bool RayHit(struct KX_ClientObjectInfo *client, class KX_RayCast *result, float *oglmatrix); - /// \see KX_RayCast - bool NeedRayCast(struct KX_ClientObjectInfo *, void *UNUSED(data)) { return true; } - - RAS_ILightObject* CreateLight(); - void AddLight(RAS_ILightObject* lightobject); - - void RemoveLight(RAS_ILightObject* lightobject); - int ApplyLights(int objectlayer, const MT_Transform& viewmat); - - void MotionBlur(); - - void SetClientObject(void *obj); - - void SetAuxilaryClientInfo(void *inf); - - /** - * Prints information about what the hardware supports. - */ - virtual void PrintHardwareInfo(); - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_OpenGLRasterizer") -#endif -}; - -#endif /* __RAS_OPENGLRASTERIZER_H__ */ diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLSync.cpp b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLSync.cpp deleted file mode 100644 index 26b956cd74e..00000000000 --- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLSync.cpp +++ /dev/null @@ -1,82 +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) 2015, Blender Foundation - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): Blender Foundation. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -#include "GPU_glew.h" - -#include - -#include "RAS_OpenGLSync.h" - -RAS_OpenGLSync::RAS_OpenGLSync() - :m_sync(NULL) -{ -} - -RAS_OpenGLSync::~RAS_OpenGLSync() -{ - Destroy(); -} - -bool RAS_OpenGLSync::Create(RAS_SYNC_TYPE type) -{ - if (m_sync) { - printf("RAS_OpenGLSync::Create(): sync already exists, destroy first\n"); - return false; - } - if (type != RAS_SYNC_TYPE_FENCE) { - printf("RAS_OpenGLSync::Create(): only RAS_SYNC_TYPE_FENCE are currently supported\n"); - return false; - } - if (!GLEW_ARB_sync) { - printf("RAS_OpenGLSync::Create(): ARB_sync extension is needed to create sync object\n"); - return false; - } - m_sync = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); - if (!m_sync) { - printf("RAS_OpenGLSync::Create(): glFenceSync() failed"); - return false; - } - return true; -} - -void RAS_OpenGLSync::Destroy() -{ - if (m_sync) { - glDeleteSync(m_sync); - m_sync = NULL; - } -} - -void RAS_OpenGLSync::Wait() -{ - if (m_sync) { - // this is needed to ensure that the sync is in the GPU - glFlush(); - // block until the operation have completed - glWaitSync(m_sync, 0, GL_TIMEOUT_IGNORED); - } -} diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLSync.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLSync.h deleted file mode 100644 index 4ba96903856..00000000000 --- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLSync.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) 2015, Blender Foundation - * All rights reserved. - * - * The Original Code is: all of this file. - * - * Contributor(s): Blender Foundation. - * - * ***** END GPL LICENSE BLOCK ***** - */ - -#ifndef __RAS_OPENGLSYNC__ -#define __RAS_OPENGLSYNC__ - - -#include "RAS_ISync.h" - -struct __GLsync; - -class RAS_OpenGLSync : public RAS_ISync -{ -private: - struct __GLsync *m_sync; - -public: - RAS_OpenGLSync(); - ~RAS_OpenGLSync(); - - virtual bool Create(RAS_SYNC_TYPE type); - virtual void Destroy(); - virtual void Wait(); -}; - -#endif /* __RAS_OPENGLSYNC__ */ diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVA.cpp b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVA.cpp deleted file mode 100644 index f980116f5f8..00000000000 --- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVA.cpp +++ /dev/null @@ -1,260 +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 "RAS_StorageVA.h" - -#include "GPU_glew.h" - -RAS_StorageVA::RAS_StorageVA(int *texco_num, RAS_IRasterizer::TexCoGen *texco, int *attrib_num, RAS_IRasterizer::TexCoGen *attrib, int *attrib_layer) : - m_drawingmode(RAS_IRasterizer::KX_TEXTURED), - m_texco_num(texco_num), - m_attrib_num(attrib_num), - m_last_texco_num(0), - m_last_attrib_num(0), - m_texco(texco), - m_attrib(attrib), - m_attrib_layer(attrib_layer) -{ -} - -RAS_StorageVA::~RAS_StorageVA() -{ -} - -bool RAS_StorageVA::Init() -{ - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - - return true; -} - -void RAS_StorageVA::Exit() -{ -} - -void RAS_StorageVA::IndexPrimitives(class RAS_MeshSlot& ms) -{ - static const GLsizei stride = sizeof(RAS_TexVert); - bool wireframe = m_drawingmode <= RAS_IRasterizer::KX_WIREFRAME, use_color_array = true; - RAS_MeshSlot::iterator it; - GLenum drawmode; - - if (!wireframe) - EnableTextures(true); - glEnableClientState(GL_VERTEX_ARRAY); - glEnableClientState(GL_NORMAL_ARRAY); - - // use glDrawElements to draw each vertexarray - for (ms.begin(it); !ms.end(it); ms.next(it)) { - if (it.totindex == 0) - continue; - - // drawing mode - if (it.array->m_type == RAS_DisplayArray::TRIANGLE) - drawmode = GL_TRIANGLES; - else if (it.array->m_type == RAS_DisplayArray::QUAD) - drawmode = GL_QUADS; - else - drawmode = GL_LINES; - - // colors - if (drawmode != GL_LINES && !wireframe) { - if (ms.m_bObjectColor) { - const MT_Vector4& rgba = ms.m_RGBAcolor; - - glDisableClientState(GL_COLOR_ARRAY); - glColor4d(rgba[0], rgba[1], rgba[2], rgba[3]); - use_color_array = false; - } - else { - glColor4f(0.0f, 0.0f, 0.0f, 1.0f); - glEnableClientState(GL_COLOR_ARRAY); - use_color_array = true; - } - } - else - glColor4f(0.0f, 0.0f, 0.0f, 1.0f); - - glVertexPointer(3, GL_FLOAT, stride, it.vertex->getXYZ()); - glNormalPointer(GL_FLOAT, stride, it.vertex->getNormal()); - - if (!wireframe) { - TexCoordPtr(it.vertex); - if (use_color_array) - glColorPointer(4, GL_UNSIGNED_BYTE, stride, it.vertex->getRGBA()); - } - - // here the actual drawing takes places - glDrawElements(drawmode, it.totindex, GL_UNSIGNED_SHORT, it.index); - } - - glDisableClientState(GL_VERTEX_ARRAY); - glDisableClientState(GL_NORMAL_ARRAY); - if (!wireframe) { - glDisableClientState(GL_COLOR_ARRAY); - EnableTextures(false); - } -} - -void RAS_StorageVA::TexCoordPtr(const RAS_TexVert *tv) -{ - /* note: this function must closely match EnableTextures to enable/disable - * the right arrays, otherwise coordinate and attribute pointers from other - * materials can still be used and cause crashes */ - int unit; - - if (GLEW_ARB_multitexture) - { - for (unit = 0; unit < *m_texco_num; unit++) - { - glClientActiveTextureARB(GL_TEXTURE0_ARB+unit); - switch (m_texco[unit]) { - case RAS_IRasterizer::RAS_TEXCO_ORCO: - case RAS_IRasterizer::RAS_TEXCO_GLOB: - glTexCoordPointer(3, GL_FLOAT, sizeof(RAS_TexVert),tv->getXYZ()); - break; - case RAS_IRasterizer::RAS_TEXCO_UV: - glTexCoordPointer(2, GL_FLOAT, sizeof(RAS_TexVert),tv->getUV(unit)); - break; - case RAS_IRasterizer::RAS_TEXCO_NORM: - glTexCoordPointer(3, GL_FLOAT, sizeof(RAS_TexVert),tv->getNormal()); - break; - case RAS_IRasterizer::RAS_TEXTANGENT: - glTexCoordPointer(4, GL_FLOAT, sizeof(RAS_TexVert),tv->getTangent()); - break; - default: - break; - } - } - - glClientActiveTextureARB(GL_TEXTURE0_ARB); - } - - if (GLEW_ARB_vertex_program) { - for (unit = 0; unit < *m_attrib_num; unit++) { - switch (m_attrib[unit]) { - case RAS_IRasterizer::RAS_TEXCO_ORCO: - case RAS_IRasterizer::RAS_TEXCO_GLOB: - glVertexAttribPointerARB(unit, 3, GL_FLOAT, GL_FALSE, sizeof(RAS_TexVert), tv->getXYZ()); - break; - case RAS_IRasterizer::RAS_TEXCO_UV: - glVertexAttribPointerARB(unit, 2, GL_FLOAT, GL_FALSE, sizeof(RAS_TexVert), tv->getUV(m_attrib_layer[unit])); - break; - case RAS_IRasterizer::RAS_TEXCO_NORM: - glVertexAttribPointerARB(unit, 3, GL_FLOAT, GL_FALSE, sizeof(RAS_TexVert), tv->getNormal()); - break; - case RAS_IRasterizer::RAS_TEXTANGENT: - glVertexAttribPointerARB(unit, 4, GL_FLOAT, GL_FALSE, sizeof(RAS_TexVert), tv->getTangent()); - break; - case RAS_IRasterizer::RAS_TEXCO_VCOL: - glVertexAttribPointerARB(unit, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(RAS_TexVert), tv->getRGBA()); - break; - default: - break; - } - } - } -} - -void RAS_StorageVA::EnableTextures(bool enable) -{ - RAS_IRasterizer::TexCoGen *texco, *attrib; - int unit, texco_num, attrib_num; - - /* we cache last texcoords and attribs to ensure we disable the ones that - * were actually last set */ - if (enable) { - texco = m_texco; - texco_num = *m_texco_num; - attrib = m_attrib; - attrib_num = *m_attrib_num; - - memcpy(m_last_texco, m_texco, sizeof(RAS_IRasterizer::TexCoGen)*(*m_texco_num)); - m_last_texco_num = *m_texco_num; - memcpy(m_last_attrib, m_attrib, sizeof(RAS_IRasterizer::TexCoGen)*(*m_attrib_num)); - m_last_attrib_num = *m_attrib_num; - } - else { - texco = m_last_texco; - texco_num = m_last_texco_num; - attrib = m_last_attrib; - attrib_num = m_last_attrib_num; - } - - if (GLEW_ARB_multitexture) { - for (unit = 0; unit < texco_num; unit++) { - glClientActiveTextureARB(GL_TEXTURE0_ARB + unit); - - switch (texco[unit]) { - case RAS_IRasterizer::RAS_TEXCO_ORCO: - case RAS_IRasterizer::RAS_TEXCO_GLOB: - case RAS_IRasterizer::RAS_TEXCO_UV: - case RAS_IRasterizer::RAS_TEXCO_NORM: - case RAS_IRasterizer::RAS_TEXTANGENT: - if (enable) glEnableClientState(GL_TEXTURE_COORD_ARRAY); - else glDisableClientState(GL_TEXTURE_COORD_ARRAY); - break; - default: - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - break; - } - } - - glClientActiveTextureARB(GL_TEXTURE0_ARB); - } - else { - if (texco_num) { - if (enable) glEnableClientState(GL_TEXTURE_COORD_ARRAY); - else glDisableClientState(GL_TEXTURE_COORD_ARRAY); - } - } - - if (GLEW_ARB_vertex_program) { - for (unit = 0; unit < attrib_num; unit++) { - switch (attrib[unit]) { - case RAS_IRasterizer::RAS_TEXCO_ORCO: - case RAS_IRasterizer::RAS_TEXCO_GLOB: - case RAS_IRasterizer::RAS_TEXCO_UV: - case RAS_IRasterizer::RAS_TEXCO_NORM: - case RAS_IRasterizer::RAS_TEXTANGENT: - case RAS_IRasterizer::RAS_TEXCO_VCOL: - if (enable) glEnableVertexAttribArrayARB(unit); - else glDisableVertexAttribArrayARB(unit); - break; - default: - glDisableVertexAttribArrayARB(unit); - break; - } - } - } - - if (!enable) { - m_last_texco_num = 0; - m_last_attrib_num = 0; - } -} - diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVA.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVA.h deleted file mode 100644 index a5a3170ed77..00000000000 --- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVA.h +++ /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 ***** - */ - -#ifndef __KX_VERTEXARRAYSTORAGE -#define __KX_VERTEXARRAYSTORAGE - -#include "RAS_IStorage.h" -#include "RAS_IRasterizer.h" - -#include "RAS_OpenGLRasterizer.h" - -class RAS_StorageVA : public RAS_IStorage -{ - -public: - RAS_StorageVA(int *texco_num, RAS_IRasterizer::TexCoGen *texco, int *attrib_num, RAS_IRasterizer::TexCoGen *attrib, int *attrib_layer); - virtual ~RAS_StorageVA(); - - virtual bool Init(); - virtual void Exit(); - - virtual void IndexPrimitives(RAS_MeshSlot& ms); - - virtual void SetDrawingMode(int drawingmode) {m_drawingmode = drawingmode;}; - -protected: - int m_drawingmode; - - int* m_texco_num; - int* m_attrib_num; - - int m_last_texco_num; - int m_last_attrib_num; - - RAS_IRasterizer::TexCoGen* m_texco; - RAS_IRasterizer::TexCoGen* m_attrib; - int* m_attrib_layer; - - RAS_IRasterizer::TexCoGen m_last_texco[RAS_MAX_TEXCO]; - RAS_IRasterizer::TexCoGen m_last_attrib[RAS_MAX_ATTRIB]; - - virtual void EnableTextures(bool enable); - virtual void TexCoordPtr(const RAS_TexVert *tv); - - -#ifdef WITH_CXX_GUARDEDALLOC -public: - void *operator new(size_t num_bytes) { return MEM_mallocN(num_bytes, "GE:RAS_StorageVA"); } - void operator delete( void *mem ) { MEM_freeN(mem); } -#endif -}; - -#endif //__KX_VERTEXARRAYSTORAGE diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVBO.cpp b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVBO.cpp deleted file mode 100644 index 4ba5882a46e..00000000000 --- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVBO.cpp +++ /dev/null @@ -1,227 +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 "RAS_StorageVBO.h" -#include "RAS_MeshObject.h" - -#include "GPU_glew.h" - -VBO::VBO(RAS_DisplayArray *data, unsigned int indices) -{ - this->data = data; - this->size = data->m_vertex.size(); - this->indices = indices; - this->stride = sizeof(RAS_TexVert); - - // Determine drawmode - if (data->m_type == data->QUAD) - this->mode = GL_QUADS; - else if (data->m_type == data->TRIANGLE) - this->mode = GL_TRIANGLES; - else - this->mode = GL_LINE; - - // Generate Buffers - glGenBuffersARB(1, &this->ibo); - glGenBuffersARB(1, &this->vbo_id); - - // Fill the buffers with initial data - UpdateIndices(); - UpdateData(); - - // Establish offsets - this->vertex_offset = (void*)(((RAS_TexVert*)0)->getXYZ()); - this->normal_offset = (void*)(((RAS_TexVert*)0)->getNormal()); - this->tangent_offset = (void*)(((RAS_TexVert*)0)->getTangent()); - this->color_offset = (void*)(((RAS_TexVert*)0)->getRGBA()); - this->uv_offset = (void*)(((RAS_TexVert*)0)->getUV(0)); -} - -VBO::~VBO() -{ - glDeleteBuffersARB(1, &this->ibo); - glDeleteBuffersARB(1, &this->vbo_id); -} - -void VBO::UpdateData() -{ - glBindBufferARB(GL_ARRAY_BUFFER_ARB, this->vbo_id); - glBufferData(GL_ARRAY_BUFFER, this->stride*this->size, &this->data->m_vertex[0], GL_STATIC_DRAW); -} - -void VBO::UpdateIndices() -{ - glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, this->ibo); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, data->m_index.size() * sizeof(GLushort), - &data->m_index[0], GL_STATIC_DRAW); -} - -void VBO::Draw(int texco_num, RAS_IRasterizer::TexCoGen* texco, int attrib_num, RAS_IRasterizer::TexCoGen* attrib, int *attrib_layer) -{ - int unit; - - // Bind buffers - glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, this->ibo); - glBindBufferARB(GL_ARRAY_BUFFER_ARB, this->vbo_id); - - // Vertexes - glEnableClientState(GL_VERTEX_ARRAY); - glVertexPointer(3, GL_FLOAT, this->stride, this->vertex_offset); - - // Normals - glEnableClientState(GL_NORMAL_ARRAY); - glNormalPointer(GL_FLOAT, this->stride, this->normal_offset); - - // Colors - glEnableClientState(GL_COLOR_ARRAY); - glColorPointer(4, GL_UNSIGNED_BYTE, this->stride, this->color_offset); - - for (unit = 0; unit < texco_num; ++unit) - { - glClientActiveTexture(GL_TEXTURE0_ARB + unit); - switch (texco[unit]) { - case RAS_IRasterizer::RAS_TEXCO_ORCO: - case RAS_IRasterizer::RAS_TEXCO_GLOB: - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - glTexCoordPointer(3, GL_FLOAT, this->stride, this->vertex_offset); - break; - case RAS_IRasterizer::RAS_TEXCO_UV: - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - glTexCoordPointer(2, GL_FLOAT, this->stride, (void*)((intptr_t)this->uv_offset+(sizeof(GLfloat)*2*unit))); - break; - case RAS_IRasterizer::RAS_TEXCO_NORM: - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - glTexCoordPointer(3, GL_FLOAT, this->stride, this->normal_offset); - break; - case RAS_IRasterizer::RAS_TEXTANGENT: - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - glTexCoordPointer(4, GL_FLOAT, this->stride, this->tangent_offset); - break; - default: - break; - } - } - glClientActiveTextureARB(GL_TEXTURE0_ARB); - - if (GLEW_ARB_vertex_program) - { - for (unit = 0; unit < attrib_num; ++unit) - { - switch (attrib[unit]) { - case RAS_IRasterizer::RAS_TEXCO_ORCO: - case RAS_IRasterizer::RAS_TEXCO_GLOB: - glVertexAttribPointerARB(unit, 3, GL_FLOAT, GL_FALSE, this->stride, this->vertex_offset); - glEnableVertexAttribArrayARB(unit); - break; - case RAS_IRasterizer::RAS_TEXCO_UV: - glVertexAttribPointerARB(unit, 2, GL_FLOAT, GL_FALSE, this->stride, (void*)((intptr_t)this->uv_offset+attrib_layer[unit]*sizeof(GLfloat)*2)); - glEnableVertexAttribArrayARB(unit); - break; - case RAS_IRasterizer::RAS_TEXCO_NORM: - glVertexAttribPointerARB(unit, 2, GL_FLOAT, GL_FALSE, stride, this->normal_offset); - glEnableVertexAttribArrayARB(unit); - break; - case RAS_IRasterizer::RAS_TEXTANGENT: - glVertexAttribPointerARB(unit, 4, GL_FLOAT, GL_FALSE, this->stride, this->tangent_offset); - glEnableVertexAttribArrayARB(unit); - break; - case RAS_IRasterizer::RAS_TEXCO_VCOL: - glVertexAttribPointerARB(unit, 4, GL_UNSIGNED_BYTE, GL_TRUE, this->stride, this->color_offset); - glEnableVertexAttribArrayARB(unit); - default: - break; - } - } - } - - glDrawElements(this->mode, this->indices, GL_UNSIGNED_SHORT, 0); - - glDisableClientState(GL_VERTEX_ARRAY); - glDisableClientState(GL_NORMAL_ARRAY); - glDisableClientState(GL_COLOR_ARRAY); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - - if (GLEW_ARB_vertex_program) - { - for (int i = 0; i < attrib_num; ++i) - glDisableVertexAttribArrayARB(i); - } - - glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0); - glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); -} - -RAS_StorageVBO::RAS_StorageVBO(int *texco_num, RAS_IRasterizer::TexCoGen *texco, int *attrib_num, RAS_IRasterizer::TexCoGen *attrib, int *attrib_layer): - m_drawingmode(RAS_IRasterizer::KX_TEXTURED), - m_texco_num(texco_num), - m_attrib_num(attrib_num), - m_texco(texco), - m_attrib(attrib), - m_attrib_layer(attrib_layer) -{ -} - -RAS_StorageVBO::~RAS_StorageVBO() -{ -} - -bool RAS_StorageVBO::Init() -{ - return true; -} - -void RAS_StorageVBO::Exit() -{ - VBOMap::iterator it = m_vbo_lookup.begin(); - while (it != m_vbo_lookup.end()) { - delete it->second; - ++it; - } - m_vbo_lookup.clear(); -} - -void RAS_StorageVBO::IndexPrimitives(RAS_MeshSlot& ms) -{ - RAS_MeshSlot::iterator it; - VBO *vbo; - - for (ms.begin(it); !ms.end(it); ms.next(it)) - { - vbo = m_vbo_lookup[it.array]; - - if (vbo == 0) - m_vbo_lookup[it.array] = vbo = new VBO(it.array, it.totindex); - - // Update the vbo - if (ms.m_mesh->MeshModified()) - { - vbo->UpdateData(); - } - - vbo->Draw(*m_texco_num, m_texco, *m_attrib_num, m_attrib, m_attrib_layer); - } -} diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVBO.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVBO.h deleted file mode 100644 index c82b6a3206d..00000000000 --- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_StorageVBO.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 ***** - */ - -#ifndef __KX_VERTEXBUFFEROBJECTSTORAGE -#define __KX_VERTEXBUFFEROBJECTSTORAGE - -#include -#include "GPU_glew.h" - -#include "RAS_IStorage.h" -#include "RAS_IRasterizer.h" - -#include "RAS_OpenGLRasterizer.h" - -class VBO -{ -public: - VBO(RAS_DisplayArray *data, unsigned int indices); - ~VBO(); - - void Draw(int texco_num, RAS_IRasterizer::TexCoGen* texco, int attrib_num, RAS_IRasterizer::TexCoGen* attrib, int *attrib_layer); - - void UpdateData(); - void UpdateIndices(); -private: - RAS_DisplayArray* data; - GLuint size; - GLuint stride; - GLuint indices; - GLenum mode; - GLuint ibo; - GLuint vbo_id; - - void* vertex_offset; - void* normal_offset; - void* color_offset; - void* tangent_offset; - void* uv_offset; -}; - -typedef std::map VBOMap; - -class RAS_StorageVBO : public RAS_IStorage -{ - -public: - RAS_StorageVBO(int *texco_num, RAS_IRasterizer::TexCoGen *texco, int *attrib_num, RAS_IRasterizer::TexCoGen *attrib, int *attrib_layer); - virtual ~RAS_StorageVBO(); - - virtual bool Init(); - virtual void Exit(); - - virtual void IndexPrimitives(RAS_MeshSlot& ms); - - virtual void SetDrawingMode(int drawingmode) {m_drawingmode = drawingmode;}; - -protected: - int m_drawingmode; - - int* m_texco_num; - int* m_attrib_num; - - RAS_IRasterizer::TexCoGen* m_texco; - RAS_IRasterizer::TexCoGen* m_attrib; - int* m_attrib_layer; - - VBOMap m_vbo_lookup; - -#ifdef WITH_CXX_GUARDEDALLOC -public: - void *operator new(size_t num_bytes) { return MEM_mallocN(num_bytes, "GE:RAS_StorageVA"); } - void operator delete( void *mem ) { MEM_freeN(mem); } -#endif -}; - -#endif //__KX_VERTEXBUFFEROBJECTSTORAGE diff --git a/source/gameengine/Rasterizer/RAS_Polygon.cpp b/source/gameengine/Rasterizer/RAS_Polygon.cpp deleted file mode 100644 index 3274ded4406..00000000000 --- a/source/gameengine/Rasterizer/RAS_Polygon.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. - * - * 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/Rasterizer/RAS_Polygon.cpp - * \ingroup bgerast - */ - -#ifdef _MSC_VER -# pragma warning (disable:4786) -#endif - -#include "RAS_Polygon.h" -#include "RAS_MaterialBucket.h" - -RAS_Polygon::RAS_Polygon(RAS_MaterialBucket* bucket, RAS_DisplayArray *darray, int numvert) -{ - m_bucket = bucket; - m_darray = darray; - m_offset[0] = m_offset[1] = m_offset[2] = m_offset[3] = 0; - m_numvert = numvert; - -// m_edgecode = 255; - m_polyflags = 0; -} - -int RAS_Polygon::VertexCount() -{ - return m_numvert; -} - -void RAS_Polygon::SetVertexOffset(int i, unsigned short offset) -{ - m_offset[i] = offset; -} - -RAS_TexVert *RAS_Polygon::GetVertex(int i) -{ - return &m_darray->m_vertex[m_offset[i]]; -} - -unsigned int RAS_Polygon::GetVertexOffsetAbsolute(unsigned short i) -{ - return m_offset[i] + m_darray->m_offset; -} - -/* -int RAS_Polygon::GetEdgeCode() -{ - return m_edgecode; -} - -void RAS_Polygon::SetEdgeCode(int edgecode) -{ - m_edgecode = edgecode; -}*/ - - -bool RAS_Polygon::IsVisible() -{ - return (m_polyflags & VISIBLE) != 0; -} - -void RAS_Polygon::SetVisible(bool visible) -{ - if (visible) m_polyflags |= VISIBLE; - else m_polyflags &= ~VISIBLE; -} - -bool RAS_Polygon::IsCollider() -{ - return (m_polyflags & COLLIDER) != 0; -} - -void RAS_Polygon::SetCollider(bool visible) -{ - if (visible) m_polyflags |= COLLIDER; - else m_polyflags &= ~COLLIDER; -} - -bool RAS_Polygon::IsTwoside() -{ - return (m_polyflags & TWOSIDE) != 0; -} - -void RAS_Polygon::SetTwoside(bool twoside) -{ - if (twoside) m_polyflags |= TWOSIDE; - else m_polyflags &= ~TWOSIDE; -} - -RAS_MaterialBucket* RAS_Polygon::GetMaterial() -{ - return m_bucket; -} - -RAS_DisplayArray* RAS_Polygon::GetDisplayArray() -{ - return m_darray; -} diff --git a/source/gameengine/Rasterizer/RAS_Polygon.h b/source/gameengine/Rasterizer/RAS_Polygon.h deleted file mode 100644 index 597e80ffdfb..00000000000 --- a/source/gameengine/Rasterizer/RAS_Polygon.h +++ /dev/null @@ -1,101 +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 RAS_Polygon.h - * \ingroup bgerast - */ - -#ifndef __RAS_POLYGON_H__ -#define __RAS_POLYGON_H__ - -class RAS_DisplayArray; -class RAS_MaterialBucket; -class RAS_TexVert; - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -/* polygon flags */ - -class RAS_Polygon -{ - /* location */ - RAS_MaterialBucket* m_bucket; - RAS_DisplayArray* m_darray; - unsigned short m_offset[4]; - unsigned short m_numvert; - - /* flags */ -#if 1 - unsigned short m_polyflags; -#else - unsigned char m_edgecode; - unsigned char m_polyflags; -#endif - -public: - enum { - VISIBLE = 1, - COLLIDER = 2, - TWOSIDE = 4 - }; - - RAS_Polygon(RAS_MaterialBucket* bucket, RAS_DisplayArray* darray, int numvert); - virtual ~RAS_Polygon() {}; - - int VertexCount(); - RAS_TexVert* GetVertex(int i); - - void SetVertexOffset(int i, unsigned short offset); - unsigned int GetVertexOffsetAbsolute(unsigned short i); - - // each bit is for a visible edge, starting with bit 1 for the first edge, bit 2 for second etc. - // - Not used yet! -/* int GetEdgeCode(); - void SetEdgeCode(int edgecode); */ - - bool IsVisible(); - void SetVisible(bool visible); - - bool IsCollider(); - void SetCollider(bool collider); - - bool IsTwoside(); - void SetTwoside(bool twoside); - - RAS_MaterialBucket* GetMaterial(); - RAS_DisplayArray* GetDisplayArray(); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_Polygon") -#endif -}; - -#endif - diff --git a/source/gameengine/Rasterizer/RAS_Rect.h b/source/gameengine/Rasterizer/RAS_Rect.h deleted file mode 100644 index fc99c9159db..00000000000 --- a/source/gameengine/Rasterizer/RAS_Rect.h +++ /dev/null @@ -1,104 +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 RAS_Rect.h - * \ingroup bgerast - */ - -#ifndef __RAS_RECT_H__ -#define __RAS_RECT_H__ - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -/** - * \section interface class. - * RAS_Rect just encodes a simple rectangle. - * \note Should be part of a generic library - */ -class RAS_Rect -{ -public: // todo: make a decent class, and make private - int m_x1, m_y1; - int m_x2, m_y2; - -public: - RAS_Rect() : m_x1(0), m_y1(0), m_x2(0), m_y2(0) {} - int GetWidth( - ) const { - return m_x2 - m_x1; - } - int GetHeight( - ) const { - return m_y2 - m_y1; - } - int GetLeft( - ) const { - return m_x1; - } - int GetRight( - ) const { - return m_x2; - } - int GetBottom( - ) const { - return m_y1; - } - int GetTop( - ) const { - return m_y2; - } - - void SetLeft( - int x1) - { - m_x1 = x1; - } - void SetBottom( - int y1) - { - m_y1 = y1; - } - void SetRight( - int x2) - { - m_x2 = x2; - } - void SetTop( - int y2) - { - m_y2 = y2; - } - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_Rect") -#endif -}; - -#endif /* __RAS_RECT_H__ */ diff --git a/source/gameengine/Rasterizer/RAS_TexMatrix.h b/source/gameengine/Rasterizer/RAS_TexMatrix.h deleted file mode 100644 index a2dd291d016..00000000000 --- a/source/gameengine/Rasterizer/RAS_TexMatrix.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 RAS_TexMatrix.h - * \ingroup bgerast - */ - -#ifndef __RAS_TEXMATRIX_H__ -#define __RAS_TEXMATRIX_H__ - -#include "MT_Matrix3x3.h" -#include "MT_Point3.h" -#include "MT_Point2.h" -#include "RAS_TexVert.h" - -void RAS_CalcTexMatrix(RAS_TexVert p[3],MT_Point3& origin,MT_Vector3& udir,MT_Vector3& vdir); - -#endif /* __RAS_TEXMATRIX_H__ */ diff --git a/source/gameengine/Rasterizer/RAS_TexVert.cpp b/source/gameengine/Rasterizer/RAS_TexVert.cpp deleted file mode 100644 index 2e176360d61..00000000000 --- a/source/gameengine/Rasterizer/RAS_TexVert.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. - * - * 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/Rasterizer/RAS_TexVert.cpp - * \ingroup bgerast - */ - - -#include "RAS_TexVert.h" -#include "MT_Matrix4x4.h" -#include "BLI_math.h" - -RAS_TexVert::RAS_TexVert(const MT_Point3& xyz, - const MT_Point2 uvs[MAX_UNIT], - const MT_Vector4& tangent, - const unsigned int rgba, - const MT_Vector3& normal, - const bool flat, - const unsigned int origindex) -{ - xyz.getValue(m_localxyz); - SetRGBA(rgba); - SetNormal(normal); - tangent.getValue(m_tangent); - m_flag = (flat) ? FLAT: 0; - m_origindex = origindex; - m_unit = 2; - m_softBodyIndex = -1; - - for (int i = 0; i < MAX_UNIT; ++i) - { - uvs[i].getValue(m_uvs[i]); - } -} - -const MT_Point3& RAS_TexVert::xyz() -{ - g_pt3.setValue(m_localxyz); - return g_pt3; -} - -void RAS_TexVert::SetRGBA(const MT_Vector4& rgba) -{ - unsigned char *colp = (unsigned char*) &m_rgba; - colp[0] = (unsigned char) (rgba[0] * 255.0f); - colp[1] = (unsigned char) (rgba[1] * 255.0f); - colp[2] = (unsigned char) (rgba[2] * 255.0f); - colp[3] = (unsigned char) (rgba[3] * 255.0f); -} - - -void RAS_TexVert::SetXYZ(const MT_Point3& xyz) -{ - xyz.getValue(m_localxyz); -} - -void RAS_TexVert::SetXYZ(const float xyz[3]) -{ - copy_v3_v3(m_localxyz, xyz); -} - -void RAS_TexVert::SetUV(int index, const MT_Point2& uv) -{ - uv.getValue(m_uvs[index]); -} - -void RAS_TexVert::SetUV(int index, const float uv[2]) -{ - copy_v2_v2(m_uvs[index], uv); -} - -void RAS_TexVert::SetRGBA(const unsigned int rgba) -{ - m_rgba = rgba; -} - - -void RAS_TexVert::SetFlag(const short flag) -{ - m_flag = flag; -} - -void RAS_TexVert::SetUnit(const unsigned int u) -{ - m_unit = (u <= (unsigned int) MAX_UNIT) ? u: (unsigned int)MAX_UNIT; -} - -void RAS_TexVert::SetNormal(const MT_Vector3& normal) -{ - normal.getValue(m_normal); -} - -void RAS_TexVert::SetTangent(const MT_Vector3& tangent) -{ - tangent.getValue(m_tangent); -} - - -// compare two vertices, and return true if both are almost identical (they can be shared) -bool RAS_TexVert::closeTo(const RAS_TexVert* other) -{ - const float eps = FLT_EPSILON; - for (int i = 0; i < MAX_UNIT; i++) { - if (!compare_v2v2(m_uvs[i], other->m_uvs[i], eps)) { - return false; - } - } - - return (/* m_flag == other->m_flag && */ - /* at the moment the face only stores the smooth/flat setting so don't bother comparing it */ - (m_rgba == other->m_rgba) && - compare_v3v3(m_normal, other->m_normal, eps) && - compare_v3v3(m_tangent, other->m_tangent, eps) - /* don't bother comparing m_localxyz since we know there from the same vert */ - /* && compare_v3v3(m_localxyz, other->m_localxyz, eps))*/ - ); -} - -short RAS_TexVert::getFlag() const -{ - return m_flag; -} - - -unsigned int RAS_TexVert::getUnit() const -{ - return m_unit; -} - -void RAS_TexVert::Transform(const MT_Matrix4x4& mat, const MT_Matrix4x4& nmat) -{ - SetXYZ((mat * MT_Vector4(m_localxyz[0], m_localxyz[1], m_localxyz[2], 1.0f)).getValue()); - SetNormal((nmat * MT_Vector4(m_normal[0], m_normal[1], m_normal[2], 1.0f)).getValue()); - SetTangent((nmat * MT_Vector4(m_tangent[0], m_tangent[1], m_tangent[2], 1.0f)).getValue()); -} - -void RAS_TexVert::TransformUV(int index, const MT_Matrix4x4& mat) -{ - SetUV(index, (mat * MT_Vector4(m_uvs[index][0], m_uvs[index][1], 0.0f, 1.0f)).getValue()); -} diff --git a/source/gameengine/Rasterizer/RAS_TexVert.h b/source/gameengine/Rasterizer/RAS_TexVert.h deleted file mode 100644 index 8d08549d97e..00000000000 --- a/source/gameengine/Rasterizer/RAS_TexVert.h +++ /dev/null @@ -1,146 +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 RAS_TexVert.h - * \ingroup bgerast - */ - -#ifndef __RAS_TEXVERT_H__ -#define __RAS_TEXVERT_H__ - - -#include "MT_Point3.h" -#include "MT_Point2.h" -#include "MT_Transform.h" - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -static MT_Point3 g_pt3; -static MT_Point2 g_pt2; - -class RAS_TexVert -{ - - float m_localxyz[3]; // 3*4 = 12 - float m_uvs[8][2]; // 8*2*4=64 //8 = MAX_UNIT - unsigned int m_rgba; // 4 - float m_tangent[4]; // 4*4 = 16 - float m_normal[3]; // 3*4 = 12 - short m_flag; // 2 - short m_softBodyIndex; //2 - unsigned int m_unit; // 4 - unsigned int m_origindex; // 4 - char m_padding[8]; // 8 - //--------- - // 128 - // 32 bytes alignment improves performance on ATI cards. - -public: - enum { - FLAT = 1, - MAX_UNIT = 8 - }; - - short getFlag() const; - unsigned int getUnit() const; - - RAS_TexVert()// :m_xyz(0,0,0),m_uv(0,0),m_rgba(0) - {} - RAS_TexVert(const MT_Point3& xyz, - const MT_Point2 uvs[MAX_UNIT], - const MT_Vector4& tangent, - const unsigned int rgba, - const MT_Vector3& normal, - const bool flat, - const unsigned int origindex); - ~RAS_TexVert() {}; - - const float* getUV (int unit) const { - return m_uvs[unit]; - }; - - const float* getXYZ() const { - return m_localxyz; - }; - - const float* getNormal() const { - return m_normal; - } - - short int getSoftBodyIndex() const - { - return m_softBodyIndex; - } - - void setSoftBodyIndex(short int sbIndex) - { - m_softBodyIndex = sbIndex; - } - - const float* getTangent() const { - return m_tangent; - } - - const unsigned char* getRGBA() const { - return (unsigned char *) &m_rgba; - } - - unsigned int getOrigIndex() const { - return m_origindex; - } - - void SetXYZ(const MT_Point3& xyz); - void SetXYZ(const float xyz[3]); - void SetUV(int index, const MT_Point2& uv); - void SetUV(int index, const float uv[2]); - - void SetRGBA(const unsigned int rgba); - void SetNormal(const MT_Vector3& normal); - void SetTangent(const MT_Vector3& tangent); - void SetFlag(const short flag); - void SetUnit(const unsigned u); - - void SetRGBA(const MT_Vector4& rgba); - const MT_Point3& xyz(); - - void Transform(const class MT_Matrix4x4& mat, - const class MT_Matrix4x4& nmat); - void TransformUV(int index, const MT_Matrix4x4& mat); - - // compare two vertices, to test if they can be shared, used for - // splitting up based on uv's, colors, etc - bool closeTo(const RAS_TexVert* other); - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:RAS_TexVert") -#endif -}; - -#endif /* __RAS_TEXVERT_H__ */ diff --git a/source/gameengine/Rasterizer/RAS_texmatrix.cpp b/source/gameengine/Rasterizer/RAS_texmatrix.cpp deleted file mode 100644 index d30a3d3a75d..00000000000 --- a/source/gameengine/Rasterizer/RAS_texmatrix.cpp +++ /dev/null @@ -1,131 +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/Rasterizer/RAS_texmatrix.cpp - * \ingroup bgerast - */ - - -#include "RAS_TexMatrix.h" - -void RAS_CalcTexMatrix(RAS_TexVert p[3],MT_Point3& origin,MT_Vector3& udir,MT_Vector3& vdir) -{ -// precondition: 3 vertices are non-collinear - - MT_Vector3 vec1 = p[1].xyz()-p[0].xyz(); - MT_Vector3 vec2 = p[2].xyz()-p[0].xyz(); - MT_Vector3 normal = vec1.cross(vec2); - normal.normalize(); - - // determine which coordinate we drop, ie. max coordinate in the normal - - - int ZCOORD = normal.closestAxis(); - int XCOORD = (ZCOORD+1)%3; - int YCOORD = (ZCOORD+2)%3; - - // ax+by+cz+d=0 - MT_Scalar d = -p[0].xyz().dot(normal); - - - MT_Matrix3x3 mat3( p[0].getUV(0)[0],p[0].getUV(0)[1], 1, - p[1].getUV(0)[0],p[1].getUV(0)[1], 1, - p[2].getUV(0)[0],p[2].getUV(0)[1], 1); - - - MT_Matrix3x3 mat3inv = mat3.inverse(); - - MT_Vector3 p123x(p[0].xyz()[XCOORD],p[1].xyz()[XCOORD],p[2].xyz()[XCOORD]); - MT_Vector3 resultx = mat3inv*p123x; - MT_Vector3 p123y(p[0].xyz()[YCOORD],p[1].xyz()[YCOORD],p[2].xyz()[YCOORD]); - MT_Vector3 resulty = mat3inv*p123y; - - // normal[ZCOORD] is not zero, because it's chosen to be maximal (absolute), and normal has length 1, - // so at least on of the coords is <> 0 - - //droppedvalue udir.dot(normal) =0 - MT_Scalar droppedu = -(resultx.x()*normal[XCOORD]+resulty.x()*normal[YCOORD])/normal[ZCOORD]; - udir[XCOORD] = resultx.x(); - udir[YCOORD] = resulty.x(); - udir[ZCOORD] = droppedu; - MT_Scalar droppedv = -(resultx.y()*normal[XCOORD]+resulty.y()*normal[YCOORD])/normal[ZCOORD]; - vdir[XCOORD] = resultx.y(); - vdir[YCOORD] = resulty.y(); - vdir[ZCOORD] = droppedv; - // droppedvalue b = -(ax+cz+d)/y; - MT_Scalar droppedvalue = -((resultx.z()*normal[XCOORD] + resulty.z()*normal[YCOORD]+d))/normal[ZCOORD]; - origin[XCOORD] = resultx.z(); - origin[YCOORD] = resulty.z(); - origin[ZCOORD] = droppedvalue; - - -} - -#ifdef _TEXOWNMAIN - -int main() -{ - - MT_Point2 puv0={0,0}; - MT_Point3 pxyz0 (0,0,128); - - MT_Scalar puv1[2] = {1,0}; - MT_Point3 pxyz1(128,0,128); - - MT_Scalar puv2[2] = {1,1}; - MT_Point3 pxyz2(128,0,0); - - RAS_TexVert p0(pxyz0,puv0); - RAS_TexVert p1(pxyz1,puv1); - RAS_TexVert p2(pxyz2,puv2); - - RAS_TexVert vertices[3] = - { - p0, - p1, - p2 - }; - - MT_Vector3 udir,vdir; - MT_Point3 origin; - CalcTexMatrix(vertices,origin,udir,vdir); - - MT_Point3 testpoint(128,32,64); - - MT_Scalar lenu = udir.length2(); - MT_Scalar lenv = vdir.length2(); - - MT_Scalar testu=((pxyz2-origin).dot(udir))/lenu; - MT_Scalar testv=((pxyz2-origin).dot(vdir))/lenv; - - - - - return 0; -} - -#endif // _TEXOWNMAIN diff --git a/source/gameengine/SceneGraph/CMakeLists.txt b/source/gameengine/SceneGraph/CMakeLists.txt deleted file mode 100644 index bbad429bbcd..00000000000 --- a/source/gameengine/SceneGraph/CMakeLists.txt +++ /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) 2006, Blender Foundation -# All rights reserved. -# -# The Original Code is: all of this file. -# -# Contributor(s): Jacques Beaurain. -# -# ***** END GPL LICENSE BLOCK ***** - -set(INC - . -) - -set(INC_SYS - ../../../intern/moto/include -) - -set(SRC - SG_BBox.cpp - SG_Controller.cpp - SG_IObject.cpp - SG_Node.cpp - SG_Spatial.cpp - SG_Tree.cpp - - SG_BBox.h - SG_Controller.h - SG_DList.h - SG_IObject.h - SG_Node.h - SG_ParentRelation.h - SG_QList.h - SG_Spatial.h - SG_Tree.h -) - -blender_add_lib(ge_scenegraph "${SRC}" "${INC}" "${INC_SYS}") diff --git a/source/gameengine/SceneGraph/SG_BBox.cpp b/source/gameengine/SceneGraph/SG_BBox.cpp deleted file mode 100644 index f9d83d37384..00000000000 --- a/source/gameengine/SceneGraph/SG_BBox.cpp +++ /dev/null @@ -1,262 +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 ***** - * Bounding Box - */ - -/** \file gameengine/SceneGraph/SG_BBox.cpp - * \ingroup bgesg - */ - - -#include - -#include "SG_BBox.h" -#include "SG_Node.h" - -SG_BBox::SG_BBox() : - m_min(0.0f, 0.0f, 0.0f), - m_max(0.0f, 0.0f, 0.0f) -{ -} - -SG_BBox::SG_BBox(const MT_Point3 &min, const MT_Point3 &max) : - m_min(min), - m_max(max) -{ -} - -SG_BBox::SG_BBox(const SG_BBox &other, const MT_Transform &world) : - m_min(world(other.m_min)), - m_max(world(other.m_max)) -{ - *this += world(MT_Point3(m_min[0], m_min[1], m_max[2])); - *this += world(MT_Point3(m_min[0], m_max[1], m_min[2])); - *this += world(MT_Point3(m_min[0], m_max[1], m_max[2])); - *this += world(MT_Point3(m_max[0], m_min[1], m_min[2])); - *this += world(MT_Point3(m_max[0], m_min[1], m_max[2])); - *this += world(MT_Point3(m_max[0], m_max[1], m_min[2])); -} - -SG_BBox::SG_BBox(const SG_BBox &other) : - m_min(other.m_min), - m_max(other.m_max) -{ -} - -SG_BBox::~ SG_BBox() -{ -} - -SG_BBox& SG_BBox::operator +=(const MT_Point3 &point) -{ - if (point[0] < m_min[0]) - m_min[0] = point[0]; - else if (point[0] > m_max[0]) - m_max[0] = point[0]; - - if (point[1] < m_min[1]) - m_min[1] = point[1]; - else if (point[1] > m_max[1]) - m_max[1] = point[1]; - - if (point[2] < m_min[2]) - m_min[2] = point[2]; - else if (point[2] > m_max[2]) - m_max[2] = point[2]; - - return *this; -} - -SG_BBox& SG_BBox::operator += (const SG_BBox &bbox) -{ - *this += bbox.m_min; - *this += bbox.m_max; - - return *this; -} - -SG_BBox SG_BBox::operator +(const SG_BBox &bbox2) const -{ - SG_BBox ret = *this; - ret += bbox2; - return ret; -} - -MT_Scalar SG_BBox::volume() const -{ - MT_Vector3 size = m_max - m_min; - return size[0]*size[1]*size[2]; -} -#if 0 -void SG_BBox::translate(const MT_Vector3& dx) -{ - m_min += dx; - m_max += dx; -} - -void SG_BBox::scale(const MT_Vector3& size, const MT_Point3& point) -{ - MT_Vector3 center = (m_max - m_min)/2. + point; - m_max = (m_max - center)*size; - m_min = (m_min - center)*size; -} -#endif - -SG_BBox SG_BBox::transform(const MT_Transform &world) const -{ - SG_BBox bbox(world(m_min), world(m_max)); - bbox += world(MT_Point3(m_min[0], m_min[1], m_max[2])); - bbox += world(MT_Point3(m_min[0], m_max[1], m_min[2])); - bbox += world(MT_Point3(m_min[0], m_max[1], m_max[2])); - bbox += world(MT_Point3(m_max[0], m_min[1], m_min[2])); - bbox += world(MT_Point3(m_max[0], m_min[1], m_max[2])); - bbox += world(MT_Point3(m_max[0], m_max[1], m_min[2])); - return bbox; -} - -bool SG_BBox::inside(const MT_Point3 &point) const -{ - return point[0] >= m_min[0] && point[0] <= m_max[0] && - point[1] >= m_min[1] && point[1] <= m_max[1] && - point[2] >= m_min[2] && point[2] <= m_max[2]; -} - -bool SG_BBox::inside(const SG_BBox& other) const -{ - return inside(other.m_min) && inside(other.m_max); -} - -bool SG_BBox::intersects(const SG_BBox& other) const -{ - return inside(other.m_min) != inside(other.m_max); -} - -bool SG_BBox::outside(const SG_BBox& other) const -{ - return !inside(other.m_min) && !inside(other.m_max); -} - -SG_BBox::intersect SG_BBox::test(const SG_BBox& other) const -{ - bool point1(inside(other.m_min)), point2(inside(other.m_max)); - - return point1?(point2?INSIDE:INTERSECT):(point2?INTERSECT:OUTSIDE); -} - -void SG_BBox::get(MT_Point3 *box, const MT_Transform &world) const -{ - *box++ = world(m_min); - *box++ = world(MT_Point3(m_min[0], m_min[1], m_max[2])); - *box++ = world(MT_Point3(m_min[0], m_max[1], m_min[2])); - *box++ = world(MT_Point3(m_min[0], m_max[1], m_max[2])); - *box++ = world(MT_Point3(m_max[0], m_min[1], m_min[2])); - *box++ = world(MT_Point3(m_max[0], m_min[1], m_max[2])); - *box++ = world(MT_Point3(m_max[0], m_max[1], m_min[2])); - *box++ = world(m_max); -} - -void SG_BBox::getaa(MT_Point3 *box, const MT_Transform &world) const -{ - const MT_Point3 min(world(m_min)), max(world(m_max)); - *box++ = min; - *box++ = MT_Point3(min[0], min[1], max[2]); - *box++ = MT_Point3(min[0], max[1], min[2]); - *box++ = MT_Point3(min[0], max[1], max[2]); - *box++ = MT_Point3(max[0], min[1], min[2]); - *box++ = MT_Point3(max[0], min[1], max[2]); - *box++ = MT_Point3(max[0], max[1], min[2]); - *box++ = max; -} - -void SG_BBox::getmm(MT_Point3 *box, const MT_Transform &world) const -{ - const MT_Point3 min(world(m_min)), max(world(m_max)); - *box++ = min; - *box++ = max; -} - -void SG_BBox::split(SG_BBox &left, SG_BBox &right) const -{ - MT_Scalar sizex = m_max[0] - m_min[0]; - MT_Scalar sizey = m_max[1] - m_min[1]; - MT_Scalar sizez = m_max[2] - m_min[2]; - if (sizex < sizey) - { - if (sizey > sizez) - { - left.m_min = m_min; - left.m_max[0] = m_max[0]; - left.m_max[1] = m_min[1] + sizey/2.0f; - left.m_max[2] = m_max[2]; - - right.m_min[0] = m_min[0]; - right.m_min[1] = m_min[1] + sizey/2.0f; - right.m_min[2] = m_min[2]; - right.m_max = m_max; - std::cout << "splity" << std::endl; - } - else { - left.m_min = m_min; - left.m_max[0] = m_max[0]; - left.m_max[1] = m_max[1]; - left.m_max[2] = m_min[2] + sizez/2.0f; - - right.m_min[0] = m_min[0]; - right.m_min[1] = m_min[1]; - right.m_min[2] = m_min[2] + sizez/2.0f; - right.m_max = m_max; - std::cout << "splitz" << std::endl; - } - } - else { - if (sizex > sizez) { - left.m_min = m_min; - left.m_max[0] = m_min[0] + sizex/2.0f; - left.m_max[1] = m_max[1]; - left.m_max[2] = m_max[2]; - - right.m_min[0] = m_min[0] + sizex/2.0f; - right.m_min[1] = m_min[1]; - right.m_min[2] = m_min[2]; - right.m_max = m_max; - std::cout << "splitx" << std::endl; - } - else { - left.m_min = m_min; - left.m_max[0] = m_max[0]; - left.m_max[1] = m_max[1]; - left.m_max[2] = m_min[2] + sizez/2.0f; - - right.m_min[0] = m_min[0]; - right.m_min[1] = m_min[1]; - right.m_min[2] = m_min[2] + sizez/2.0f; - right.m_max = m_max; - std::cout << "splitz" << std::endl; - } - } - - //std::cout << "Left: " << left.m_min << " -> " << left.m_max << " Right: " << right.m_min << " -> " << right.m_max << std::endl; -} diff --git a/source/gameengine/SceneGraph/SG_BBox.h b/source/gameengine/SceneGraph/SG_BBox.h deleted file mode 100644 index 3c524dc7f18..00000000000 --- a/source/gameengine/SceneGraph/SG_BBox.h +++ /dev/null @@ -1,143 +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 SG_BBox.h - * \ingroup bgesg - * \brief Bounding Box - */ - -#ifndef __SG_BBOX_H__ -#define __SG_BBOX_H__ - -#include "MT_Scalar.h" -#include "MT_Point3.h" -#include "MT_Vector3.h" -#include "MT_Transform.h" - -#include - -#ifdef WITH_CXX_GUARDEDALLOC -#include "MEM_guardedalloc.h" -#endif - -class SG_Node; - -/** - * Bounding box class. - * Holds the minimum and maximum axis aligned points of a node's bounding box, - * in world coordinates. - */ -class SG_BBox -{ - MT_Point3 m_min; - MT_Point3 m_max; -public: - typedef enum { INSIDE, INTERSECT, OUTSIDE } intersect; - SG_BBox(); - SG_BBox(const MT_Point3 &min, const MT_Point3 &max); - SG_BBox(const SG_BBox &other, const MT_Transform &world); - SG_BBox(const SG_BBox &other); - ~SG_BBox(); - - /** - * Enlarges the bounding box to contain the specified point. - */ - SG_BBox& operator +=(const MT_Point3 &point); - /** - * Enlarges the bounding box to contain the specified bound box. - */ - SG_BBox& operator +=(const SG_BBox &bbox); - - SG_BBox operator + (const SG_BBox &bbox2) const; -#if 0 - /** - * Translates the bounding box. - */ - void translate(const MT_Vector3 &dx); - /** - * Scales the bounding box about the optional point. - */ - void scale(const MT_Vector3 &size, const MT_Point3 &point = MT_Point3(0.0f, 0.0f, 0.0f)); -#endif - SG_BBox transform(const MT_Transform &world) const; - /** - * Computes the volume of the bounding box. - */ - MT_Scalar volume() const; - - /** - * Test if the given point is inside this bounding box. - */ - bool inside(const MT_Point3 &point) const; - - /** - * Test if the given bounding box is inside this bounding box. - */ - bool inside(const SG_BBox &other) const; - - /** - * Test if the given bounding box is outside this bounding box. - */ - bool outside(const SG_BBox &other) const; - - /** - * Test if the given bounding box intersects this bounding box. - */ - bool intersects(const SG_BBox &other) const; - - /** - * Test the given bounding box with this bounding box. - */ - intersect test(const SG_BBox &other) const; - - /** - * Get the eight points that define this bounding box. - * - * \param world a world transform to apply to the produced points bounding box. - */ - void get(MT_Point3 *box, const MT_Transform &world) const; - /** - * Get the eight points that define this axis aligned bounding box. - * This differs from SG_BBox::get() in that the produced box will be world axis aligned. - * The maximum & minimum local points will be transformed *before* splitting to 8 points. - * \param world a world transform to be applied. - */ - void getaa(MT_Point3 *box, const MT_Transform &world) const; - - void getmm(MT_Point3 *box, const MT_Transform &world) const; - - void split(SG_BBox &left, SG_BBox &right) const; - - friend class SG_Tree; - - -#ifdef WITH_CXX_GUARDEDALLOC - MEM_CXX_CLASS_ALLOC_FUNCS("GE:SG_BBox") -#endif -}; - -#endif /* __SG_BBOX_H__ */ diff --git a/source/gameengine/SceneGraph/SG_Controller.cpp b/source/gameengine/SceneGraph/SG_Controller.cpp deleted file mode 100644 index 264942415c9..00000000000 --- a/source/gameengine/SceneGraph/SG_Controller.cpp +++ /dev/null @@ -1,46 +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/SceneGraph/SG_Controller.cpp - * \ingroup bgesg - */ - -#include "SG_Controller.h" - - void -SG_Controller:: -SetObject(SG_IObject* obj) -{ - m_pObject = obj; // no checks yet ? -} - - void -SG_Controller:: -ClearObject( -) { - m_pObject = NULL; -} diff --git a/source/gameengine/SceneGraph/SG_Controller.h b/source/gameengine/SceneGraph/SG_Controller.h deleted file mode 100644 index a173633e13c..00000000000 --- a/source/gameengine/SceneGraph/SG_Controller.h +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Implementationclass to derive controllers from - * - * - * ***** 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 SG_Controller.h - * \ingroup bgesg - */ - -#ifndef __SG_CONTROLLER_H__ -#define __SG_CONTROLLER_H__ - -#include "SG_IObject.h" - -/** - * A scenegraph controller - */ -class SG_Controller -{ -public: - SG_Controller( - ) : - m_pObject(NULL) { - } - - virtual - ~SG_Controller( - ) {}; - - virtual - bool - Update( - double time - )=0; - - virtual - void - SetObject ( - SG_IObject* object - ); - - void - ClearObject( - ); - - virtual - void - SetSimulatedTime( - double time - )=0; - - virtual - SG_Controller* - GetReplica( - class SG_Node* destnode - )=0; - - /** - * Hacky way of passing options to specific controllers - * \param option An integer identifying the option. - * \param value The value of this option. - * \attention This has been placed here to give sca-elements - * \attention some control over the controllers. This is - * \attention necessary because the identity of the controller - * \attention is lost on the way here. - */ - virtual - void - SetOption( - int option, - int value - )=0; - - /** - * Option-identifiers: SG_CONTR__