2 * ***** BEGIN GPL LICENSE BLOCK *****
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software Foundation,
16 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19 * All rights reserved.
21 * The Original Code is: all of this file.
23 * Contributor(s): none yet.
25 * ***** END GPL LICENSE BLOCK *****
29 /** \file gameengine/Ketsji/KX_GameObject.cpp
34 /* This warning tells us about truncation of __long__ stl-generated names.
35 * It can occasionally cause DevStudio to have internal compiler warnings. */
36 # pragma warning( disable:4786 )
39 #include "RAS_IPolygonMaterial.h"
40 #include "KX_BlenderMaterial.h"
41 #include "KX_GameObject.h"
42 #include "KX_Camera.h" // only for their ::Type
43 #include "KX_Light.h" // only for their ::Type
44 #include "KX_FontObject.h" // only for their ::Type
45 #include "RAS_MeshObject.h"
46 #include "KX_NavMeshObject.h"
47 #include "KX_MeshProxy.h"
48 #include "KX_PolyProxy.h"
49 #include <stdio.h> // printf
50 #include "SG_Controller.h"
51 #include "PHY_IGraphicController.h"
53 #include "KX_ClientObjectInfo.h"
54 #include "RAS_BucketManager.h"
55 #include "KX_RayCast.h"
56 #include "KX_PythonInit.h"
57 #include "KX_PyMath.h"
58 #include "KX_PythonSeq.h"
59 #include "SCA_IActuator.h"
60 #include "SCA_ISensor.h"
61 #include "SCA_IController.h"
62 #include "NG_NetworkScene.h" //Needed for sendMessage()
63 #include "KX_ObstacleSimulation.h"
66 #include "BKE_object.h"
68 #include "BL_ActionManager.h"
69 #include "BL_Action.h"
71 #include "PyObjectPlus.h" /* python stuff */
72 #include "BLI_utildefines.h"
73 #include "python_utildefines.h"
75 // This file defines relationships between parents and children
76 // in the game engine.
78 #include "KX_SG_NodeRelationships.h"
82 static MT_Point3 dummy_point= MT_Point3(0.0, 0.0, 0.0);
83 static MT_Vector3 dummy_scaling = MT_Vector3(1.0, 1.0, 1.0);
84 static MT_Matrix3x3 dummy_orientation = MT_Matrix3x3(1.0, 0.0, 0.0,
88 KX_GameObject::KX_GameObject(
89 void* sgReplicationInfo,
90 SG_Callbacks callbacks)
95 m_previousLodLevel(0),
96 m_pBlenderObject(NULL),
97 m_pBlenderGroupObject(NULL),
98 m_bSuspendDynamics(false),
99 m_bUseObjectColor(false),
100 m_bIsNegativeScaling(false),
101 m_objectColor(1.0, 1.0, 1.0, 1.0),
105 m_pPhysicsController(NULL),
106 m_pGraphicController(NULL),
109 m_pObstacleSimulation(NULL),
110 m_pInstanceObjects(NULL),
111 m_pDupliGroupObject(NULL),
112 m_actionManager(NULL),
113 m_bRecordAnimation(false),
114 m_isDeformable(false)
118 m_collisionCallbacks(NULL)
121 m_ignore_activity_culling = false;
122 m_pClient_info = new KX_ClientObjectInfo(this, KX_ClientObjectInfo::ACTOR);
123 m_pSGNode = new SG_Node(this,sgReplicationInfo,callbacks);
125 // define the relationship between this node and it's parent.
127 KX_NormalParentRelation * parent_relation =
128 KX_NormalParentRelation::New();
129 m_pSGNode->SetParentRelation(parent_relation);
134 KX_GameObject::~KX_GameObject()
138 PyDict_Clear(m_attr_dict); /* in case of circular refs or other weird cases */
139 /* Py_CLEAR: Py_DECREF's and NULL's */
140 Py_CLEAR(m_attr_dict);
142 // Unregister collision callbacks
143 // Do this before we start freeing physics information like m_pClient_info
144 if (m_collisionCallbacks){
145 UnregisterCollisionCallbacks();
146 Py_CLEAR(m_collisionCallbacks);
148 #endif // WITH_PYTHON
152 // is this delete somewhere ?
155 delete m_pClient_info;
160 // must go through controllers and make sure they will not use us anymore
161 // This is important for KX_BulletPhysicsControllers that unregister themselves
162 // from the object when they are deleted.
163 SGControllerList::iterator contit;
164 SGControllerList& controllers = m_pSGNode->GetSGControllerList();
165 for (contit = controllers.begin();contit!=controllers.end();++contit)
167 (*contit)->ClearObject();
169 m_pSGNode->SetSGClientObject(NULL);
171 /* m_pSGNode is freed in KX_Scene::RemoveNodeDestructObject */
173 if (m_pGraphicController)
175 delete m_pGraphicController;
178 if (m_pPhysicsController)
180 delete m_pPhysicsController;
183 if (m_pObstacleSimulation)
185 m_pObstacleSimulation->DestroyObstacleForObj(this);
190 delete m_actionManager;
193 if (m_pDupliGroupObject)
195 m_pDupliGroupObject->Release();
198 if (m_pInstanceObjects)
200 m_pInstanceObjects->Release();
204 KX_GameObject* KX_GameObject::GetClientObject(KX_ClientObjectInfo *info)
208 return info->m_gameobject;
211 CValue* KX_GameObject:: Calc(VALUE_OPERATOR op, CValue *val)
218 CValue* KX_GameObject::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val)
225 const STR_String & KX_GameObject::GetText()
232 double KX_GameObject::GetNumber()
239 STR_String& KX_GameObject::GetName()
245 /* Set the name of the value */
246 void KX_GameObject::SetName(const char *name)
251 PHY_IPhysicsController* KX_GameObject::GetPhysicsController()
253 return m_pPhysicsController;
256 KX_GameObject* KX_GameObject::GetDupliGroupObject()
258 return m_pDupliGroupObject;
261 CListValue* KX_GameObject::GetInstanceObjects()
263 return m_pInstanceObjects;
266 void KX_GameObject::AddInstanceObjects(KX_GameObject* obj)
268 if (!m_pInstanceObjects)
269 m_pInstanceObjects = new CListValue();
272 m_pInstanceObjects->Add(obj);
275 void KX_GameObject::RemoveInstanceObject(KX_GameObject* obj)
277 assert(m_pInstanceObjects);
278 m_pInstanceObjects->RemoveValue(obj);
282 void KX_GameObject::RemoveDupliGroupObject()
284 if (m_pDupliGroupObject) {
285 m_pDupliGroupObject->Release();
286 m_pDupliGroupObject = NULL;
290 void KX_GameObject::SetDupliGroupObject(KX_GameObject* obj)
293 m_pDupliGroupObject = obj;
296 void KX_GameObject::AddConstraint(bRigidBodyJointConstraint *cons)
298 m_constraints.push_back(cons);
301 std::vector<bRigidBodyJointConstraint*> KX_GameObject::GetConstraints()
303 return m_constraints;
306 void KX_GameObject::ClearConstraints()
308 m_constraints.clear();
311 KX_GameObject* KX_GameObject::GetParent()
313 KX_GameObject* result = NULL;
314 SG_Node* node = m_pSGNode;
316 while (node && !result)
318 node = node->GetSGParent();
320 result = (KX_GameObject*)node->GetSGClientObject();
327 void KX_GameObject::SetParent(KX_Scene *scene, KX_GameObject* obj, bool addToCompound, bool ghost)
329 // check on valid node in case a python controller holds a reference to a deleted object
331 GetSGNode() && // object is not zombi
332 obj->GetSGNode() && // object is not zombi
333 GetSGNode()->GetSGParent() != obj->GetSGNode() && // not already parented to same object
334 !GetSGNode()->IsAncessor(obj->GetSGNode()) && // no parenting loop
335 this != obj) // not the object itself
337 // Make sure the objects have some scale
338 MT_Vector3 scale1 = NodeGetWorldScaling();
339 MT_Vector3 scale2 = obj->NodeGetWorldScaling();
340 if (fabs(scale2[0]) < (MT_Scalar)FLT_EPSILON ||
341 fabs(scale2[1]) < (MT_Scalar)FLT_EPSILON ||
342 fabs(scale2[2]) < (MT_Scalar)FLT_EPSILON ||
343 fabs(scale1[0]) < (MT_Scalar)FLT_EPSILON ||
344 fabs(scale1[1]) < (MT_Scalar)FLT_EPSILON ||
345 fabs(scale1[2]) < (MT_Scalar)FLT_EPSILON) { return; }
347 // Remove us from our old parent and set our new parent
349 obj->GetSGNode()->AddChild(GetSGNode());
351 if (m_pPhysicsController)
353 m_pPhysicsController->SuspendDynamics(ghost);
355 // Set us to our new scale, position, and orientation
356 scale2[0] = 1.0/scale2[0];
357 scale2[1] = 1.0/scale2[1];
358 scale2[2] = 1.0/scale2[2];
359 scale1 = scale1 * scale2;
360 MT_Matrix3x3 invori = obj->NodeGetWorldOrientation().inverse();
361 MT_Vector3 newpos = invori*(NodeGetWorldPosition()-obj->NodeGetWorldPosition())*scale2;
363 NodeSetLocalScale(scale1);
364 NodeSetLocalPosition(MT_Point3(newpos[0],newpos[1],newpos[2]));
365 NodeSetLocalOrientation(invori*NodeGetWorldOrientation());
367 // object will now be a child, it must be removed from the parent list
368 CListValue* rootlist = scene->GetRootParentList();
369 if (rootlist->RemoveValue(this))
370 // the object was in parent list, decrement ref count as it's now removed
372 // if the new parent is a compound object, add this object shape to the compound shape.
373 // step 0: verify this object has physical controller
374 if (m_pPhysicsController && addToCompound)
376 // step 1: find the top parent (not necessarily obj)
377 KX_GameObject* rootobj = (KX_GameObject*)obj->GetSGNode()->GetRootSGParent()->GetSGClientObject();
378 // step 2: verify it has a physical controller and compound shape
379 if (rootobj != NULL &&
380 rootobj->m_pPhysicsController != NULL &&
381 rootobj->m_pPhysicsController->IsCompound())
383 rootobj->m_pPhysicsController->AddCompoundChild(m_pPhysicsController);
386 // graphically, the object hasn't change place, no need to update m_pGraphicController
390 void KX_GameObject::RemoveParent(KX_Scene *scene)
392 // check on valid node in case a python controller holds a reference to a deleted object
393 if (GetSGNode() && GetSGNode()->GetSGParent())
395 // get the root object to remove us from compound object if needed
396 KX_GameObject* rootobj = (KX_GameObject*)GetSGNode()->GetRootSGParent()->GetSGClientObject();
397 // Set us to the right spot
398 GetSGNode()->SetLocalScale(GetSGNode()->GetWorldScaling());
399 GetSGNode()->SetLocalOrientation(GetSGNode()->GetWorldOrientation());
400 GetSGNode()->SetLocalPosition(GetSGNode()->GetWorldPosition());
402 // Remove us from our parent
403 GetSGNode()->DisconnectFromParent();
405 // the object is now a root object, add it to the parentlist
406 CListValue* rootlist = scene->GetRootParentList();
407 if (!rootlist->SearchValue(this))
408 // object was not in root list, add it now and increment ref count
409 rootlist->Add(AddRef());
410 if (m_pPhysicsController)
412 // in case this controller was added as a child shape to the parent
413 if (rootobj != NULL &&
414 rootobj->m_pPhysicsController != NULL &&
415 rootobj->m_pPhysicsController->IsCompound())
417 rootobj->m_pPhysicsController->RemoveCompoundChild(m_pPhysicsController);
419 m_pPhysicsController->RestoreDynamics();
420 if (m_pPhysicsController->IsDynamic() && (rootobj != NULL && rootobj->m_pPhysicsController))
422 // dynamic object should remember the velocity they had while being parented
423 MT_Point3 childPoint = GetSGNode()->GetWorldPosition();
424 MT_Point3 rootPoint = rootobj->GetSGNode()->GetWorldPosition();
426 relPoint = (childPoint-rootPoint);
427 MT_Vector3 linVel = rootobj->m_pPhysicsController->GetVelocity(relPoint);
428 MT_Vector3 angVel = rootobj->m_pPhysicsController->GetAngularVelocity();
429 m_pPhysicsController->SetLinearVelocity(linVel, false);
430 m_pPhysicsController->SetAngularVelocity(angVel, false);
433 // graphically, the object hasn't change place, no need to update m_pGraphicController
437 BL_ActionManager* KX_GameObject::GetActionManager()
439 // We only want to create an action manager if we need it
440 if (!m_actionManager)
442 GetScene()->AddAnimatedObject(this);
443 m_actionManager = new BL_ActionManager(this);
445 return m_actionManager;
448 bool KX_GameObject::PlayAction(const char* name,
457 float playback_speed,
460 return GetActionManager()->PlayAction(name, start, end, layer, priority, blendin, play_mode, layer_weight, ipo_flags, playback_speed, blend_mode);
463 void KX_GameObject::StopAction(short layer)
465 GetActionManager()->StopAction(layer);
468 bool KX_GameObject::IsActionDone(short layer)
470 return GetActionManager()->IsActionDone(layer);
473 void KX_GameObject::UpdateActionManager(float curtime)
475 GetActionManager()->Update(curtime);
478 void KX_GameObject::UpdateActionIPOs()
480 GetActionManager()->UpdateIPOs();
483 float KX_GameObject::GetActionFrame(short layer)
485 return GetActionManager()->GetActionFrame(layer);
488 void KX_GameObject::SetActionFrame(short layer, float frame)
490 GetActionManager()->SetActionFrame(layer, frame);
493 bAction *KX_GameObject::GetCurrentAction(short layer)
495 return GetActionManager()->GetCurrentAction(layer);
498 void KX_GameObject::SetPlayMode(short layer, short mode)
500 GetActionManager()->SetPlayMode(layer, mode);
503 void KX_GameObject::SetTimes(short layer, float start, float end)
505 GetActionManager()->SetTimes(layer, start, end);
508 void KX_GameObject::ProcessReplica()
510 SCA_IObject::ProcessReplica();
512 m_pGraphicController = NULL;
513 m_pPhysicsController = NULL;
515 m_pClient_info = new KX_ClientObjectInfo(*m_pClient_info);
516 m_pClient_info->m_gameobject = this;
517 m_actionManager = NULL;
520 KX_Scene* scene = KX_GetActiveScene();
521 KX_ObstacleSimulation* obssimulation = scene->GetObstacleSimulation();
522 struct Object* blenderobject = GetBlenderObject();
523 if (obssimulation && (blenderobject->gameflag & OB_HASOBSTACLE))
525 obssimulation->AddObstacleForObj(this);
530 m_attr_dict= PyDict_Copy(m_attr_dict);
535 static void setGraphicController_recursive(SG_Node* node)
537 NodeList& children = node->GetSGChildren();
539 for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
541 SG_Node* childnode = (*childit);
542 KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
543 if (clientgameobj != NULL) // This is a GameObject
544 clientgameobj->ActivateGraphicController(false);
546 // if the childobj is NULL then this may be an inverse parent link
547 // so a non recursive search should still look down this node.
548 setGraphicController_recursive(childnode);
553 void KX_GameObject::ActivateGraphicController(bool recurse)
555 if (m_pGraphicController)
557 m_pGraphicController->Activate(m_bVisible);
561 setGraphicController_recursive(GetSGNode());
565 void KX_GameObject::SetUserCollisionGroup(short group)
567 m_userCollisionGroup = group;
569 void KX_GameObject::SetUserCollisionMask(short mask)
571 m_userCollisionMask = mask;
574 bool KX_GameObject::CheckCollision(KX_GameObject* other)
576 return this->m_userCollisionGroup & other->m_userCollisionMask;
579 CValue* KX_GameObject::GetReplica()
581 KX_GameObject* replica = new KX_GameObject(*this);
583 // this will copy properties and so on...
584 replica->ProcessReplica();
589 float KX_GameObject::getLinearDamping() const
591 if (m_pPhysicsController)
592 return m_pPhysicsController->GetLinearDamping();
596 float KX_GameObject::getAngularDamping() const
598 if (m_pPhysicsController)
599 return m_pPhysicsController->GetAngularDamping();
603 void KX_GameObject::setLinearDamping(float damping)
605 if (m_pPhysicsController)
606 m_pPhysicsController->SetLinearDamping(damping);
610 void KX_GameObject::setAngularDamping(float damping)
612 if (m_pPhysicsController)
613 m_pPhysicsController->SetAngularDamping(damping);
617 void KX_GameObject::setDamping(float linear, float angular)
619 if (m_pPhysicsController)
620 m_pPhysicsController->SetDamping(linear, angular);
624 void KX_GameObject::ApplyForce(const MT_Vector3& force,bool local)
626 if (m_pPhysicsController)
627 m_pPhysicsController->ApplyForce(force,local);
632 void KX_GameObject::ApplyTorque(const MT_Vector3& torque,bool local)
634 if (m_pPhysicsController)
635 m_pPhysicsController->ApplyTorque(torque,local);
640 void KX_GameObject::ApplyMovement(const MT_Vector3& dloc,bool local)
644 if (m_pPhysicsController) // (IsDynamic())
646 m_pPhysicsController->RelativeTranslate(dloc,local);
648 GetSGNode()->RelativeTranslate(dloc,GetSGNode()->GetSGParent(),local);
654 void KX_GameObject::ApplyRotation(const MT_Vector3& drot,bool local)
656 MT_Matrix3x3 rotmat(drot);
659 GetSGNode()->RelativeRotate(rotmat,local);
661 if (m_pPhysicsController) { // (IsDynamic())
662 m_pPhysicsController->RelativeRotate(rotmat,local);
670 * GetOpenGL Matrix, returns an OpenGL 'compatible' matrix
672 double* KX_GameObject::GetOpenGLMatrix()
674 // todo: optimize and only update if necessary
675 double* fl = m_OpenGL_4x4Matrix.getPointer();
679 trans.setOrigin(GetSGNode()->GetWorldPosition());
680 trans.setBasis(GetSGNode()->GetWorldOrientation());
682 MT_Vector3 scaling = GetSGNode()->GetWorldScaling();
683 m_bIsNegativeScaling = ((scaling[0] < 0.0) ^ (scaling[1] < 0.0) ^ (scaling[2] < 0.0)) ? true : false;
684 trans.scale(scaling[0], scaling[1], scaling[2]);
686 GetSGNode()->ClearDirty();
691 void KX_GameObject::UpdateBlenderObjectMatrix(Object* blendobj)
694 blendobj = m_pBlenderObject;
696 const MT_Matrix3x3& rot = NodeGetWorldOrientation();
697 const MT_Vector3& scale = NodeGetWorldScaling();
698 const MT_Vector3& pos = NodeGetWorldPosition();
699 rot.getValue(blendobj->obmat[0]);
700 pos.getValue(blendobj->obmat[3]);
701 mul_v3_fl(blendobj->obmat[0], scale[0]);
702 mul_v3_fl(blendobj->obmat[1], scale[1]);
703 mul_v3_fl(blendobj->obmat[2], scale[2]);
707 void KX_GameObject::AddMeshUser()
709 for (size_t i=0;i<m_meshes.size();i++)
711 m_meshes[i]->AddMeshUser(this, &m_meshSlots, GetDeformer());
713 // set the part of the mesh slot that never change
714 double* fl = GetOpenGLMatrixPtr()->getPointer();
716 SG_QList::iterator<RAS_MeshSlot> mit(m_meshSlots);
718 for (mit.begin(); !mit.end(); ++mit)
720 (*mit)->m_OpenGLMatrix = fl;
722 UpdateBuckets(false);
725 static void UpdateBuckets_recursive(SG_Node* node)
727 NodeList& children = node->GetSGChildren();
729 for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
731 SG_Node* childnode = (*childit);
732 KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
733 if (clientgameobj != NULL) // This is a GameObject
734 clientgameobj->UpdateBuckets(0);
736 // if the childobj is NULL then this may be an inverse parent link
737 // so a non recursive search should still look down this node.
738 UpdateBuckets_recursive(childnode);
742 void KX_GameObject::UpdateBuckets( bool recursive )
747 if (GetSGNode()->IsDirty())
750 SG_QList::iterator<RAS_MeshSlot> mit(m_meshSlots);
751 for (mit.begin(); !mit.end(); ++mit)
754 ms->m_bObjectColor = m_bUseObjectColor;
755 ms->m_RGBAcolor = m_objectColor;
756 ms->m_bVisible = m_bVisible;
757 ms->m_bCulled = m_bCulled || !m_bVisible;
759 ms->m_bucket->ActivateMesh(ms);
761 /* split if necessary */
768 UpdateBuckets_recursive(GetSGNode());
773 void KX_GameObject::RemoveMeshes()
775 for (size_t i=0;i<m_meshes.size();i++)
776 m_meshes[i]->RemoveFromBuckets(this);
778 //note: meshes can be shared, and are deleted by KX_BlenderSceneConverter
783 void KX_GameObject::AddLodMesh(RAS_MeshObject* mesh)
785 m_lodmeshes.push_back(mesh);
788 void KX_GameObject::UpdateLod(MT_Vector3 &cam_pos)
790 // Handle dupligroups
791 if (this->m_pInstanceObjects) {
792 KX_GameObject * instob;
793 int count = this->m_pInstanceObjects->GetCount();
794 for (int i = 0; i < count; i++) {
795 instob = (KX_GameObject*)this->m_pInstanceObjects->GetValue(i);
796 instob->UpdateLod(cam_pos);
800 if (this->m_lodmeshes.empty()) return;
802 MT_Vector3 delta = this->NodeGetWorldPosition() - cam_pos;
803 float distance2 = delta.length2();
806 Object *bob = this->GetBlenderObject();
807 LodLevel *lod = (LodLevel*) bob->lodlevels.first;
808 KX_Scene *kxscene = this->GetScene();
810 for (; lod; lod = lod->next, level++) {
811 if (!lod->source || lod->source->type != OB_MESH) level--;
812 if (!lod->next) break;
813 if (level == (this->m_previousLodLevel) || (level == (this->m_previousLodLevel + 1))) {
814 short hysteresis = 0;
815 if (kxscene->IsActivedLodHysteresis()) {
816 // if exists, LoD level hysteresis will override scene hysteresis
817 if (lod->next->flags & OB_LOD_USE_HYST) {
818 hysteresis = lod->next->obhysteresis;
821 hysteresis = kxscene->GetLodHysteresisValue();
824 float hystvariance = MT_abs(lod->next->distance - lod->distance) * hysteresis / 100;
825 if ((lod->next->distance + hystvariance) * (lod->next->distance + hystvariance) > distance2)
828 else if (level == (this->m_previousLodLevel - 1)) {
829 short hysteresis = 0;
830 if (kxscene->IsActivedLodHysteresis()) {
831 // if exists, LoD level hysteresis will override scene hysteresis
832 if (lod->next->flags & OB_LOD_USE_HYST) {
833 hysteresis = lod->next->obhysteresis;
836 hysteresis = kxscene->GetLodHysteresisValue();
839 float hystvariance = MT_abs(lod->next->distance - lod->distance) * hysteresis / 100;
840 if ((lod->next->distance - hystvariance) * (lod->next->distance - hystvariance) > distance2)
845 RAS_MeshObject *mesh = this->m_lodmeshes[level];
846 this->m_currentLodLevel = level;
847 if (mesh != this->m_meshes[0]) {
848 this->m_previousLodLevel = level;
849 this->GetScene()->ReplaceMesh(this, mesh, true, false);
853 void KX_GameObject::UpdateTransform()
855 // HACK: saves function call for dynamic object, they are handled differently
856 if (m_pPhysicsController && !m_pPhysicsController->IsDynamic())
857 m_pPhysicsController->SetTransform();
858 if (m_pGraphicController)
859 // update the culling tree
860 m_pGraphicController->SetGraphicTransform();
864 void KX_GameObject::UpdateTransformFunc(SG_IObject* node, void* gameobj, void* scene)
866 ((KX_GameObject*)gameobj)->UpdateTransform();
869 void KX_GameObject::SynchronizeTransform()
871 // only used for sensor object, do full synchronization as bullet doesn't do it
872 if (m_pPhysicsController)
873 m_pPhysicsController->SetTransform();
874 if (m_pGraphicController)
875 m_pGraphicController->SetGraphicTransform();
878 void KX_GameObject::SynchronizeTransformFunc(SG_IObject* node, void* gameobj, void* scene)
880 ((KX_GameObject*)gameobj)->SynchronizeTransform();
884 void KX_GameObject::SetDebugColor(unsigned int bgra)
886 for (size_t i=0;i<m_meshes.size();i++)
887 m_meshes[i]->DebugColor(bgra);
892 void KX_GameObject::ResetDebugColor()
894 SetDebugColor(0xff000000);
897 void KX_GameObject::InitIPO(bool ipo_as_force,
901 SGControllerList::iterator it = GetSGNode()->GetSGControllerList().begin();
903 while (it != GetSGNode()->GetSGControllerList().end()) {
904 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_RESET, true);
905 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_AS_FORCE, ipo_as_force);
906 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_ADD, ipo_add);
907 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_LOCAL, ipo_local);
912 void KX_GameObject::UpdateIPO(float curframetime,
915 // just the 'normal' update procedure.
916 GetSGNode()->SetSimulatedTime(curframetime,recurse);
917 GetSGNode()->UpdateWorldData(curframetime);
923 KX_GameObject::UpdateMaterialData(
936 if (((unsigned int)mesh < m_meshes.size()) && mesh >= 0) {
937 list<RAS_MeshMaterial>::iterator mit = m_meshes[mesh]->GetFirstMaterial();
939 for (; mit != m_meshes[mesh]->GetLastMaterial(); ++mit)
941 RAS_IPolyMaterial* poly = mit->m_bucket->GetPolyMaterial();
943 if (poly->GetFlag() & RAS_BLENDERMAT )
945 KX_BlenderMaterial *m = static_cast<KX_BlenderMaterial*>(poly);
947 if (matname_hash == 0)
949 m->UpdateIPO(rgba, specrgb,hard,spec,ref,emit, alpha);
950 // if mesh has only one material attached to it then use original hack with no need to edit vertices (better performance)
951 SetObjectColor(rgba);
955 if (matname_hash == poly->GetMaterialNameHash())
957 m->UpdateIPO(rgba, specrgb,hard,spec,ref,emit, alpha);
958 m_meshes[mesh]->SetVertexColor(poly,rgba);
960 // no break here, because one blender material can be split into several game engine materials
961 // (e.g. one uvsphere material is split into one material at poles with ras_mode TRIANGLE and one material for the body
962 // if here was a break then would miss some vertices if material was split
970 KX_GameObject::GetVisible(
977 static void setVisible_recursive(SG_Node* node, bool v)
979 NodeList& children = node->GetSGChildren();
981 for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
983 SG_Node* childnode = (*childit);
984 KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
985 if (clientgameobj != NULL) // This is a GameObject
986 clientgameobj->SetVisible(v, 0);
988 // if the childobj is NULL then this may be an inverse parent link
989 // so a non recursive search should still look down this node.
990 setVisible_recursive(childnode, v);
996 KX_GameObject::SetVisible(
1003 if (m_pGraphicController)
1004 m_pGraphicController->Activate(m_bVisible);
1006 setVisible_recursive(GetSGNode(), v);
1010 static void setOccluder_recursive(SG_Node* node, bool v)
1012 NodeList& children = node->GetSGChildren();
1014 for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
1016 SG_Node* childnode = (*childit);
1017 KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
1018 if (clientgameobj != NULL) // This is a GameObject
1019 clientgameobj->SetOccluder(v, false);
1021 // if the childobj is NULL then this may be an inverse parent link
1022 // so a non recursive search should still look down this node.
1023 setOccluder_recursive(childnode, v);
1028 KX_GameObject::SetOccluder(
1036 setOccluder_recursive(GetSGNode(), v);
1040 static void setDebug_recursive(SG_Node *node, bool debug)
1042 NodeList& children = node->GetSGChildren();
1043 KX_Scene *scene = KX_GetActiveScene();
1045 for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit) {
1046 SG_Node *childnode = (*childit);
1047 KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
1048 if (clientgameobj != NULL) {
1050 if (!scene->ObjectInDebugList(clientgameobj))
1051 scene->AddObjectDebugProperties(clientgameobj);
1054 scene->RemoveObjectDebugProperties(clientgameobj);
1057 /* if the childobj is NULL then this may be an inverse parent link
1058 * so a non recursive search should still look down this node. */
1059 setDebug_recursive(childnode, debug);
1063 void KX_GameObject::SetUseDebugProperties( bool debug, bool recursive )
1065 KX_Scene *scene = KX_GetActiveScene();
1068 if (!scene->ObjectInDebugList(this))
1069 scene->AddObjectDebugProperties(this);
1072 scene->RemoveObjectDebugProperties(this);
1075 setDebug_recursive(GetSGNode(), debug);
1079 KX_GameObject::SetLayer(
1087 KX_GameObject::GetLayer(
1094 void KX_GameObject::addLinearVelocity(const MT_Vector3& lin_vel,bool local)
1096 if (m_pPhysicsController)
1098 MT_Vector3 lv = local ? NodeGetWorldOrientation() * lin_vel : lin_vel;
1099 m_pPhysicsController->SetLinearVelocity(lv + m_pPhysicsController->GetLinearVelocity(), 0);
1105 void KX_GameObject::setLinearVelocity(const MT_Vector3& lin_vel,bool local)
1107 if (m_pPhysicsController)
1108 m_pPhysicsController->SetLinearVelocity(lin_vel,local);
1113 void KX_GameObject::setAngularVelocity(const MT_Vector3& ang_vel,bool local)
1115 if (m_pPhysicsController)
1116 m_pPhysicsController->SetAngularVelocity(ang_vel,local);
1120 void KX_GameObject::ResolveCombinedVelocities(
1121 const MT_Vector3 & lin_vel,
1122 const MT_Vector3 & ang_vel,
1126 if (m_pPhysicsController)
1129 MT_Vector3 lv = lin_vel_local ? NodeGetWorldOrientation() * lin_vel : lin_vel;
1130 MT_Vector3 av = ang_vel_local ? NodeGetWorldOrientation() * ang_vel : ang_vel;
1131 m_pPhysicsController->ResolveCombinedVelocities(
1132 lv.x(),lv.y(),lv.z(),av.x(),av.y(),av.z());
1137 void KX_GameObject::SetObjectColor(const MT_Vector4& rgbavec)
1139 m_bUseObjectColor = true;
1140 m_objectColor = rgbavec;
1143 const MT_Vector4& KX_GameObject::GetObjectColor()
1145 return m_objectColor;
1148 void KX_GameObject::AlignAxisToVect(const MT_Vector3& dir, int axis, float fac)
1150 MT_Matrix3x3 orimat;
1151 MT_Vector3 vect,ori,z,x,y;
1154 // check on valid node in case a python controller holds a reference to a deleted object
1159 len = vect.length();
1160 if (MT_fuzzyZero(len))
1162 cout << "alignAxisToVect() Error: Null vector!\n";
1172 orimat = GetSGNode()->GetWorldOrientation();
1176 ori.setValue(orimat[0][2], orimat[1][2], orimat[2][2]); //pivot axis
1177 if (MT_abs(vect.dot(ori)) > 1.0-3.0*MT_EPSILON) //is the vector parallel to the pivot?
1178 ori.setValue(orimat[0][1], orimat[1][1], orimat[2][1]); //change the pivot!
1182 x = (vect * fac) + ((orimat * MT_Vector3(1.0, 0.0, 0.0)) * (1.0f - fac));
1184 if (MT_fuzzyZero(len)) x = vect;
1191 ori.setValue(orimat[0][0], orimat[1][0], orimat[2][0]);
1192 if (MT_abs(vect.dot(ori)) > 1.0-3.0*MT_EPSILON)
1193 ori.setValue(orimat[0][2], orimat[1][2], orimat[2][2]);
1197 y = (vect * fac) + ((orimat * MT_Vector3(0.0, 1.0, 0.0)) * (1.0f - fac));
1199 if (MT_fuzzyZero(len)) y = vect;
1206 ori.setValue(orimat[0][1], orimat[1][1], orimat[2][1]);
1207 if (MT_abs(vect.dot(ori)) > 1.0-3.0*MT_EPSILON)
1208 ori.setValue(orimat[0][0], orimat[1][0], orimat[2][0]);
1212 z = (vect * fac) + ((orimat * MT_Vector3(0.0, 0.0, 1.0)) * (1.0f - fac));
1214 if (MT_fuzzyZero(len)) z = vect;
1220 default: //wrong input?
1221 cout << "alignAxisToVect(): Wrong axis '" << axis <<"'\n";
1224 x.normalize(); //normalize the vectors
1227 orimat.setValue( x[0],y[0],z[0],
1230 if (GetSGNode()->GetSGParent() != NULL)
1232 // the object is a child, adapt its local orientation so that
1233 // the global orientation is aligned as we want.
1234 MT_Matrix3x3 invori = GetSGNode()->GetSGParent()->GetWorldOrientation().inverse();
1235 NodeSetLocalOrientation(invori*orimat);
1238 NodeSetLocalOrientation(orimat);
1241 MT_Scalar KX_GameObject::GetMass()
1243 if (m_pPhysicsController)
1245 return m_pPhysicsController->GetMass();
1250 MT_Vector3 KX_GameObject::GetLocalInertia()
1252 MT_Vector3 local_inertia(0.0,0.0,0.0);
1253 if (m_pPhysicsController)
1255 local_inertia = m_pPhysicsController->GetLocalInertia();
1257 return local_inertia;
1260 MT_Vector3 KX_GameObject::GetLinearVelocity(bool local)
1262 MT_Vector3 velocity(0.0,0.0,0.0), locvel;
1264 if (m_pPhysicsController)
1266 velocity = m_pPhysicsController->GetLinearVelocity();
1270 ori = GetSGNode()->GetWorldOrientation();
1272 locvel = velocity * ori;
1279 MT_Vector3 KX_GameObject::GetAngularVelocity(bool local)
1281 MT_Vector3 velocity(0.0,0.0,0.0), locvel;
1283 if (m_pPhysicsController)
1285 velocity = m_pPhysicsController->GetAngularVelocity();
1289 ori = GetSGNode()->GetWorldOrientation();
1291 locvel = velocity * ori;
1298 MT_Vector3 KX_GameObject::GetVelocity(const MT_Point3& point)
1300 if (m_pPhysicsController)
1302 return m_pPhysicsController->GetVelocity(point);
1304 return MT_Vector3(0.0,0.0,0.0);
1307 // scenegraph node stuff
1309 void KX_GameObject::NodeSetLocalPosition(const MT_Point3& trans)
1311 // check on valid node in case a python controller holds a reference to a deleted object
1315 if (m_pPhysicsController && !GetSGNode()->GetSGParent())
1317 // don't update physic controller if the object is a child:
1318 // 1) the transformation will not be right
1319 // 2) in this case, the physic controller is necessarily a static object
1320 // that is updated from the normal kinematic synchronization
1321 m_pPhysicsController->SetPosition(trans);
1324 GetSGNode()->SetLocalPosition(trans);
1330 void KX_GameObject::NodeSetLocalOrientation(const MT_Matrix3x3& rot)
1332 // check on valid node in case a python controller holds a reference to a deleted object
1336 if (m_pPhysicsController && !GetSGNode()->GetSGParent())
1339 m_pPhysicsController->SetOrientation(rot);
1341 GetSGNode()->SetLocalOrientation(rot);
1344 void KX_GameObject::NodeSetGlobalOrientation(const MT_Matrix3x3& rot)
1346 // check on valid node in case a python controller holds a reference to a deleted object
1350 if (GetSGNode()->GetSGParent())
1351 GetSGNode()->SetLocalOrientation(GetSGNode()->GetSGParent()->GetWorldOrientation().inverse()*rot);
1353 NodeSetLocalOrientation(rot);
1356 void KX_GameObject::NodeSetLocalScale(const MT_Vector3& scale)
1358 // check on valid node in case a python controller holds a reference to a deleted object
1362 if (m_pPhysicsController && !GetSGNode()->GetSGParent())
1365 m_pPhysicsController->SetScaling(scale);
1367 GetSGNode()->SetLocalScale(scale);
1372 void KX_GameObject::NodeSetRelativeScale(const MT_Vector3& scale)
1376 GetSGNode()->RelativeScale(scale);
1377 if (m_pPhysicsController && (!GetSGNode()->GetSGParent()))
1380 // we can use the local scale: it's the same thing for a root object
1381 // and the world scale is not yet updated
1382 MT_Vector3 newscale = GetSGNode()->GetLocalScale();
1383 m_pPhysicsController->SetScaling(newscale);
1388 void KX_GameObject::NodeSetWorldScale(const MT_Vector3& scale)
1392 SG_Node* parent = GetSGNode()->GetSGParent();
1395 // Make sure the objects have some scale
1396 MT_Vector3 p_scale = parent->GetWorldScaling();
1397 if (fabs(p_scale[0]) < (MT_Scalar)FLT_EPSILON ||
1398 fabs(p_scale[1]) < (MT_Scalar)FLT_EPSILON ||
1399 fabs(p_scale[2]) < (MT_Scalar)FLT_EPSILON)
1404 p_scale[0] = 1/p_scale[0];
1405 p_scale[1] = 1/p_scale[1];
1406 p_scale[2] = 1/p_scale[2];
1408 NodeSetLocalScale(scale * p_scale);
1412 NodeSetLocalScale(scale);
1416 void KX_GameObject::NodeSetWorldPosition(const MT_Point3& trans)
1420 SG_Node* parent = GetSGNode()->GetSGParent();
1423 // Make sure the objects have some scale
1424 MT_Vector3 scale = parent->GetWorldScaling();
1425 if (fabs(scale[0]) < (MT_Scalar)FLT_EPSILON ||
1426 fabs(scale[1]) < (MT_Scalar)FLT_EPSILON ||
1427 fabs(scale[2]) < (MT_Scalar)FLT_EPSILON)
1431 scale[0] = 1.0/scale[0];
1432 scale[1] = 1.0/scale[1];
1433 scale[2] = 1.0/scale[2];
1434 MT_Matrix3x3 invori = parent->GetWorldOrientation().inverse();
1435 MT_Vector3 newpos = invori*(trans-parent->GetWorldPosition())*scale;
1436 NodeSetLocalPosition(MT_Point3(newpos[0],newpos[1],newpos[2]));
1440 NodeSetLocalPosition(trans);
1445 void KX_GameObject::NodeUpdateGS(double time)
1448 GetSGNode()->UpdateWorldData(time);
1453 const MT_Matrix3x3& KX_GameObject::NodeGetWorldOrientation() const
1455 // check on valid node in case a python controller holds a reference to a deleted object
1457 return dummy_orientation;
1458 return GetSGNode()->GetWorldOrientation();
1461 const MT_Matrix3x3& KX_GameObject::NodeGetLocalOrientation() const
1463 // check on valid node in case a python controller holds a reference to a deleted object
1465 return dummy_orientation;
1466 return GetSGNode()->GetLocalOrientation();
1469 const MT_Vector3& KX_GameObject::NodeGetWorldScaling() const
1471 // check on valid node in case a python controller holds a reference to a deleted object
1473 return dummy_scaling;
1475 return GetSGNode()->GetWorldScaling();
1478 const MT_Vector3& KX_GameObject::NodeGetLocalScaling() const
1480 // check on valid node in case a python controller holds a reference to a deleted object
1482 return dummy_scaling;
1484 return GetSGNode()->GetLocalScale();
1487 const MT_Point3& KX_GameObject::NodeGetWorldPosition() const
1489 // check on valid node in case a python controller holds a reference to a deleted object
1491 return GetSGNode()->GetWorldPosition();
1496 const MT_Point3& KX_GameObject::NodeGetLocalPosition() const
1498 // check on valid node in case a python controller holds a reference to a deleted object
1500 return GetSGNode()->GetLocalPosition();
1506 void KX_GameObject::UnregisterCollisionCallbacks()
1508 if (!GetPhysicsController()) {
1509 printf("Warning, trying to unregister collision callbacks for object without collisions: %s!\n", GetName().ReadPtr());
1513 // Unregister from callbacks
1514 KX_Scene* scene = GetScene();
1515 PHY_IPhysicsEnvironment* pe = scene->GetPhysicsEnvironment();
1516 PHY_IPhysicsController* spc = GetPhysicsController();
1517 // If we are the last to unregister on this physics controller
1518 if (pe->RemoveCollisionCallback(spc)){
1519 // If we are a sensor object
1520 if (m_pClient_info->isSensor())
1521 // Remove sensor body from physics world
1522 pe->RemoveSensor(spc);
1526 void KX_GameObject::RegisterCollisionCallbacks()
1528 if (!GetPhysicsController()) {
1529 printf("Warning, trying to register collision callbacks for object without collisions: %s!\n", GetName().ReadPtr());
1533 // Register from callbacks
1534 KX_Scene* scene = GetScene();
1535 PHY_IPhysicsEnvironment* pe = scene->GetPhysicsEnvironment();
1536 PHY_IPhysicsController* spc = GetPhysicsController();
1537 // If we are the first to register on this physics controller
1538 if (pe->RequestCollisionCallback(spc)){
1539 // If we are a sensor object
1540 if (m_pClient_info->isSensor())
1541 // Add sensor body to physics world
1545 void KX_GameObject::RunCollisionCallbacks(KX_GameObject *collider, const MT_Vector3 &point, const MT_Vector3 &normal)
1549 PyObject* collision_callbacks = m_collisionCallbacks;
1551 if (collision_callbacks && (len=PyList_GET_SIZE(collision_callbacks)))
1553 // Argument tuples are created lazily, only when they are needed.
1554 PyObject *args_3 = NULL;
1555 PyObject *args_1 = NULL; // Only for compatibility with pre-2.74 callbacks that take 1 argument.
1561 // Iterate the list and run the callbacks
1562 for (Py_ssize_t pos=0; pos < len; pos++)
1564 func = PyList_GET_ITEM(collision_callbacks, pos);
1566 // Get the number of arguments, supporting functions, methods and generic callables.
1567 if (PyMethod_Check(func)) {
1568 // Take away the 'self' argument for methods.
1569 co_argcount = ((PyCodeObject *)PyFunction_GET_CODE(PyMethod_GET_FUNCTION(func)))->co_argcount - 1;
1570 } else if (PyFunction_Check(func)) {
1571 co_argcount = ((PyCodeObject *)PyFunction_GET_CODE(func))->co_argcount;
1573 // We'll just assume the callable takes the correct number of arguments.
1577 // Check whether the function expects the colliding object only,
1578 // or also the point and normal.
1579 if (co_argcount <= 1) {
1580 // One argument, or *args (which gives co_argcount == 0)
1581 if (args_1 == NULL) {
1582 args_1 = PyTuple_New(1);
1583 PyTuple_SET_ITEMS(args_1, collider->GetProxy());
1585 ret = PyObject_Call(func, args_1, NULL);
1587 // More than one argument, assume we can give point & normal.
1588 if (args_3 == NULL) {
1589 args_3 = PyTuple_New(3);
1590 PyTuple_SET_ITEMS(args_3,
1591 collider->GetProxy(),
1592 PyObjectFrom(point),
1593 PyObjectFrom(normal));
1595 ret = PyObject_Call(func, args_3, NULL);
1607 if (args_3) Py_DECREF(args_3);
1608 if (args_1) Py_DECREF(args_1);
1613 /* Suspend/ resume: for the dynamic behavior, there is a simple
1614 * method. For the residual motion, there is not. I wonder what the
1615 * correct solution is for Sumo. Remove from the motion-update tree?
1617 * So far, only switch the physics and logic.
1620 void KX_GameObject::Resume(void)
1623 SCA_IObject::Resume();
1624 if (GetPhysicsController())
1625 GetPhysicsController()->RestoreDynamics();
1627 m_suspended = false;
1631 void KX_GameObject::Suspend()
1633 if ((!m_ignore_activity_culling) && (!m_suspended)) {
1634 SCA_IObject::Suspend();
1635 if (GetPhysicsController())
1636 GetPhysicsController()->SuspendDynamics();
1641 static void walk_children(SG_Node* node, CListValue* list, bool recursive)
1645 NodeList& children = node->GetSGChildren();
1647 for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
1649 SG_Node* childnode = (*childit);
1650 CValue* childobj = (CValue*)childnode->GetSGClientObject();
1651 if (childobj != NULL) // This is a GameObject
1654 list->Add(childobj->AddRef());
1657 // if the childobj is NULL then this may be an inverse parent link
1658 // so a non recursive search should still look down this node.
1659 if (recursive || childobj==NULL) {
1660 walk_children(childnode, list, recursive);
1665 CListValue* KX_GameObject::GetChildren()
1667 CListValue* list = new CListValue();
1668 walk_children(GetSGNode(), list, 0); /* GetSGNode() is always valid or it would have raised an exception before this */
1672 CListValue* KX_GameObject::GetChildrenRecursive()
1674 CListValue* list = new CListValue();
1675 walk_children(GetSGNode(), list, 1);
1679 KX_Scene* KX_GameObject::GetScene()
1681 SG_Node* node = this->GetSGNode();
1683 // this happens for object in non active layers, rely on static scene then
1684 return KX_GetActiveScene();
1685 return static_cast<KX_Scene*>(node->GetSGClientInfo());
1688 /* ---------------------------------------------------------------------
1689 * Some stuff taken from the header
1690 * --------------------------------------------------------------------- */
1691 void KX_GameObject::Relink(CTR_Map<CTR_HashedPtr, void*> *map_parameter)
1693 // we will relink the sensors and actuators that use object references
1694 // if the object is part of the replicated hierarchy, use the new
1695 // object reference instead
1696 SCA_SensorList& sensorlist = GetSensors();
1697 SCA_SensorList::iterator sit;
1698 for (sit=sensorlist.begin(); sit != sensorlist.end(); sit++)
1700 (*sit)->Relink(map_parameter);
1702 SCA_ActuatorList& actuatorlist = GetActuators();
1703 SCA_ActuatorList::iterator ait;
1704 for (ait=actuatorlist.begin(); ait != actuatorlist.end(); ait++)
1706 (*ait)->Relink(map_parameter);
1710 #ifdef USE_MATHUTILS
1712 /* These require an SGNode */
1713 #define MATHUTILS_VEC_CB_POS_LOCAL 1
1714 #define MATHUTILS_VEC_CB_POS_GLOBAL 2
1715 #define MATHUTILS_VEC_CB_SCALE_LOCAL 3
1716 #define MATHUTILS_VEC_CB_SCALE_GLOBAL 4
1717 #define MATHUTILS_VEC_CB_INERTIA_LOCAL 5
1718 #define MATHUTILS_VEC_CB_OBJECT_COLOR 6
1719 #define MATHUTILS_VEC_CB_LINVEL_LOCAL 7
1720 #define MATHUTILS_VEC_CB_LINVEL_GLOBAL 8
1721 #define MATHUTILS_VEC_CB_ANGVEL_LOCAL 9
1722 #define MATHUTILS_VEC_CB_ANGVEL_GLOBAL 10
1724 static unsigned char mathutils_kxgameob_vector_cb_index= -1; /* index for our callbacks */
1726 static int mathutils_kxgameob_generic_check(BaseMathObject *bmo)
1728 KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1735 static int mathutils_kxgameob_vector_get(BaseMathObject *bmo, int subtype)
1737 KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1741 #define PHYS_ERR(attr) PyErr_SetString(PyExc_AttributeError, "KX_GameObject." attr ", is missing a physics controller")
1744 case MATHUTILS_VEC_CB_POS_LOCAL:
1745 self->NodeGetLocalPosition().getValue(bmo->data);
1747 case MATHUTILS_VEC_CB_POS_GLOBAL:
1748 self->NodeGetWorldPosition().getValue(bmo->data);
1750 case MATHUTILS_VEC_CB_SCALE_LOCAL:
1751 self->NodeGetLocalScaling().getValue(bmo->data);
1753 case MATHUTILS_VEC_CB_SCALE_GLOBAL:
1754 self->NodeGetWorldScaling().getValue(bmo->data);
1756 case MATHUTILS_VEC_CB_INERTIA_LOCAL:
1757 if (!self->GetPhysicsController()) return PHYS_ERR("localInertia"), -1;
1758 self->GetPhysicsController()->GetLocalInertia().getValue(bmo->data);
1760 case MATHUTILS_VEC_CB_OBJECT_COLOR:
1761 self->GetObjectColor().getValue(bmo->data);
1763 case MATHUTILS_VEC_CB_LINVEL_LOCAL:
1764 if (!self->GetPhysicsController()) return PHYS_ERR("localLinearVelocity"), -1;
1765 self->GetLinearVelocity(true).getValue(bmo->data);
1767 case MATHUTILS_VEC_CB_LINVEL_GLOBAL:
1768 if (!self->GetPhysicsController()) return PHYS_ERR("worldLinearVelocity"), -1;
1769 self->GetLinearVelocity(false).getValue(bmo->data);
1771 case MATHUTILS_VEC_CB_ANGVEL_LOCAL:
1772 if (!self->GetPhysicsController()) return PHYS_ERR("localLinearVelocity"), -1;
1773 self->GetAngularVelocity(true).getValue(bmo->data);
1775 case MATHUTILS_VEC_CB_ANGVEL_GLOBAL:
1776 if (!self->GetPhysicsController()) return PHYS_ERR("worldLinearVelocity"), -1;
1777 self->GetAngularVelocity(false).getValue(bmo->data);
1787 static int mathutils_kxgameob_vector_set(BaseMathObject *bmo, int subtype)
1789 KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1794 case MATHUTILS_VEC_CB_POS_LOCAL:
1795 self->NodeSetLocalPosition(MT_Point3(bmo->data));
1796 self->NodeUpdateGS(0.f);
1798 case MATHUTILS_VEC_CB_POS_GLOBAL:
1799 self->NodeSetWorldPosition(MT_Point3(bmo->data));
1800 self->NodeUpdateGS(0.f);
1802 case MATHUTILS_VEC_CB_SCALE_LOCAL:
1803 self->NodeSetLocalScale(MT_Point3(bmo->data));
1804 self->NodeUpdateGS(0.f);
1806 case MATHUTILS_VEC_CB_SCALE_GLOBAL:
1807 PyErr_SetString(PyExc_AttributeError, "KX_GameObject.worldScale is read-only");
1809 case MATHUTILS_VEC_CB_INERTIA_LOCAL:
1812 case MATHUTILS_VEC_CB_OBJECT_COLOR:
1813 self->SetObjectColor(MT_Vector4(bmo->data));
1815 case MATHUTILS_VEC_CB_LINVEL_LOCAL:
1816 self->setLinearVelocity(MT_Point3(bmo->data),true);
1818 case MATHUTILS_VEC_CB_LINVEL_GLOBAL:
1819 self->setLinearVelocity(MT_Point3(bmo->data),false);
1821 case MATHUTILS_VEC_CB_ANGVEL_LOCAL:
1822 self->setAngularVelocity(MT_Point3(bmo->data),true);
1824 case MATHUTILS_VEC_CB_ANGVEL_GLOBAL:
1825 self->setAngularVelocity(MT_Point3(bmo->data),false);
1832 static int mathutils_kxgameob_vector_get_index(BaseMathObject *bmo, int subtype, int index)
1834 /* lazy, avoid repeteing the case statement */
1835 if (mathutils_kxgameob_vector_get(bmo, subtype) == -1)
1840 static int mathutils_kxgameob_vector_set_index(BaseMathObject *bmo, int subtype, int index)
1842 float f= bmo->data[index];
1844 /* lazy, avoid repeteing the case statement */
1845 if (mathutils_kxgameob_vector_get(bmo, subtype) == -1)
1848 bmo->data[index] = f;
1849 return mathutils_kxgameob_vector_set(bmo, subtype);
1852 static Mathutils_Callback mathutils_kxgameob_vector_cb = {
1853 mathutils_kxgameob_generic_check,
1854 mathutils_kxgameob_vector_get,
1855 mathutils_kxgameob_vector_set,
1856 mathutils_kxgameob_vector_get_index,
1857 mathutils_kxgameob_vector_set_index
1861 #define MATHUTILS_MAT_CB_ORI_LOCAL 1
1862 #define MATHUTILS_MAT_CB_ORI_GLOBAL 2
1864 static unsigned char mathutils_kxgameob_matrix_cb_index= -1; /* index for our callbacks */
1866 static int mathutils_kxgameob_matrix_get(BaseMathObject *bmo, int subtype)
1868 KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1873 case MATHUTILS_MAT_CB_ORI_LOCAL:
1874 self->NodeGetLocalOrientation().getValue3x3(bmo->data);
1876 case MATHUTILS_MAT_CB_ORI_GLOBAL:
1877 self->NodeGetWorldOrientation().getValue3x3(bmo->data);
1885 static int mathutils_kxgameob_matrix_set(BaseMathObject *bmo, int subtype)
1887 KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1891 MT_Matrix3x3 mat3x3;
1893 case MATHUTILS_MAT_CB_ORI_LOCAL:
1894 mat3x3.setValue3x3(bmo->data);
1895 self->NodeSetLocalOrientation(mat3x3);
1896 self->NodeUpdateGS(0.f);
1898 case MATHUTILS_MAT_CB_ORI_GLOBAL:
1899 mat3x3.setValue3x3(bmo->data);
1900 self->NodeSetLocalOrientation(mat3x3);
1901 self->NodeUpdateGS(0.f);
1908 static Mathutils_Callback mathutils_kxgameob_matrix_cb = {
1909 mathutils_kxgameob_generic_check,
1910 mathutils_kxgameob_matrix_get,
1911 mathutils_kxgameob_matrix_set,
1917 void KX_GameObject_Mathutils_Callback_Init(void)
1919 // register mathutils callbacks, ok to run more than once.
1920 mathutils_kxgameob_vector_cb_index= Mathutils_RegisterCallback(&mathutils_kxgameob_vector_cb);
1921 mathutils_kxgameob_matrix_cb_index= Mathutils_RegisterCallback(&mathutils_kxgameob_matrix_cb);
1924 #endif // USE_MATHUTILS
1927 /* ------- python stuff ---------------------------------------------------*/
1928 PyMethodDef KX_GameObject::Methods[] = {
1929 {"applyForce", (PyCFunction) KX_GameObject::sPyApplyForce, METH_VARARGS},
1930 {"applyTorque", (PyCFunction) KX_GameObject::sPyApplyTorque, METH_VARARGS},
1931 {"applyRotation", (PyCFunction) KX_GameObject::sPyApplyRotation, METH_VARARGS},
1932 {"applyMovement", (PyCFunction) KX_GameObject::sPyApplyMovement, METH_VARARGS},
1933 {"getLinearVelocity", (PyCFunction) KX_GameObject::sPyGetLinearVelocity, METH_VARARGS},
1934 {"setLinearVelocity", (PyCFunction) KX_GameObject::sPySetLinearVelocity, METH_VARARGS},
1935 {"getAngularVelocity", (PyCFunction) KX_GameObject::sPyGetAngularVelocity, METH_VARARGS},
1936 {"setAngularVelocity", (PyCFunction) KX_GameObject::sPySetAngularVelocity, METH_VARARGS},
1937 {"getVelocity", (PyCFunction) KX_GameObject::sPyGetVelocity, METH_VARARGS},
1938 {"setDamping", (PyCFunction) KX_GameObject::sPySetDamping, METH_VARARGS},
1939 {"getReactionForce", (PyCFunction) KX_GameObject::sPyGetReactionForce, METH_NOARGS},
1940 {"alignAxisToVect",(PyCFunction) KX_GameObject::sPyAlignAxisToVect, METH_VARARGS},
1941 {"getAxisVect",(PyCFunction) KX_GameObject::sPyGetAxisVect, METH_O},
1942 {"suspendDynamics", (PyCFunction)KX_GameObject::sPySuspendDynamics,METH_NOARGS},
1943 {"restoreDynamics", (PyCFunction)KX_GameObject::sPyRestoreDynamics,METH_NOARGS},
1944 {"enableRigidBody", (PyCFunction)KX_GameObject::sPyEnableRigidBody,METH_NOARGS},
1945 {"disableRigidBody", (PyCFunction)KX_GameObject::sPyDisableRigidBody,METH_NOARGS},
1946 {"applyImpulse", (PyCFunction) KX_GameObject::sPyApplyImpulse, METH_VARARGS},
1947 {"setCollisionMargin", (PyCFunction) KX_GameObject::sPySetCollisionMargin, METH_O},
1948 {"setParent", (PyCFunction)KX_GameObject::sPySetParent,METH_VARARGS},
1949 {"setVisible",(PyCFunction) KX_GameObject::sPySetVisible, METH_VARARGS},
1950 {"setOcclusion",(PyCFunction) KX_GameObject::sPySetOcclusion, METH_VARARGS},
1951 {"removeParent", (PyCFunction)KX_GameObject::sPyRemoveParent,METH_NOARGS},
1954 {"getPhysicsId", (PyCFunction)KX_GameObject::sPyGetPhysicsId,METH_NOARGS},
1955 {"getPropertyNames", (PyCFunction)KX_GameObject::sPyGetPropertyNames,METH_NOARGS},
1956 {"replaceMesh",(PyCFunction) KX_GameObject::sPyReplaceMesh, METH_VARARGS},
1957 {"endObject",(PyCFunction) KX_GameObject::sPyEndObject, METH_NOARGS},
1958 {"reinstancePhysicsMesh", (PyCFunction)KX_GameObject::sPyReinstancePhysicsMesh,METH_VARARGS},
1960 KX_PYMETHODTABLE(KX_GameObject, rayCastTo),
1961 KX_PYMETHODTABLE(KX_GameObject, rayCast),
1962 KX_PYMETHODTABLE_O(KX_GameObject, getDistanceTo),
1963 KX_PYMETHODTABLE_O(KX_GameObject, getVectTo),
1964 KX_PYMETHODTABLE(KX_GameObject, sendMessage),
1965 KX_PYMETHODTABLE(KX_GameObject, addDebugProperty),
1967 KX_PYMETHODTABLE_KEYWORDS(KX_GameObject, playAction),
1968 KX_PYMETHODTABLE(KX_GameObject, stopAction),
1969 KX_PYMETHODTABLE(KX_GameObject, getActionFrame),
1970 KX_PYMETHODTABLE(KX_GameObject, setActionFrame),
1971 KX_PYMETHODTABLE(KX_GameObject, isPlayingAction),
1973 // dict style access for props
1974 {"get",(PyCFunction) KX_GameObject::sPyget, METH_VARARGS},
1976 {NULL,NULL} //Sentinel
1979 PyAttributeDef KX_GameObject::Attributes[] = {
1980 KX_PYATTRIBUTE_INT_RO("currentLodLevel", KX_GameObject, m_currentLodLevel),
1981 KX_PYATTRIBUTE_RO_FUNCTION("name", KX_GameObject, pyattr_get_name),
1982 KX_PYATTRIBUTE_RO_FUNCTION("parent", KX_GameObject, pyattr_get_parent),
1983 KX_PYATTRIBUTE_RO_FUNCTION("groupMembers", KX_GameObject, pyattr_get_group_members),
1984 KX_PYATTRIBUTE_RO_FUNCTION("groupObject", KX_GameObject, pyattr_get_group_object),
1985 KX_PYATTRIBUTE_RO_FUNCTION("scene", KX_GameObject, pyattr_get_scene),
1986 KX_PYATTRIBUTE_RO_FUNCTION("life", KX_GameObject, pyattr_get_life),
1987 KX_PYATTRIBUTE_RW_FUNCTION("mass", KX_GameObject, pyattr_get_mass, pyattr_set_mass),
1988 KX_PYATTRIBUTE_RW_FUNCTION("linVelocityMin", KX_GameObject, pyattr_get_lin_vel_min, pyattr_set_lin_vel_min),
1989 KX_PYATTRIBUTE_RW_FUNCTION("linVelocityMax", KX_GameObject, pyattr_get_lin_vel_max, pyattr_set_lin_vel_max),
1990 KX_PYATTRIBUTE_RW_FUNCTION("visible", KX_GameObject, pyattr_get_visible, pyattr_set_visible),
1991 KX_PYATTRIBUTE_RW_FUNCTION("record_animation", KX_GameObject, pyattr_get_record_animation, pyattr_set_record_animation),
1992 KX_PYATTRIBUTE_BOOL_RW ("occlusion", KX_GameObject, m_bOccluder),
1993 KX_PYATTRIBUTE_RW_FUNCTION("position", KX_GameObject, pyattr_get_worldPosition, pyattr_set_localPosition),
1994 KX_PYATTRIBUTE_RO_FUNCTION("localInertia", KX_GameObject, pyattr_get_localInertia),
1995 KX_PYATTRIBUTE_RW_FUNCTION("orientation",KX_GameObject,pyattr_get_worldOrientation,pyattr_set_localOrientation),
1996 KX_PYATTRIBUTE_RW_FUNCTION("scaling", KX_GameObject, pyattr_get_worldScaling, pyattr_set_localScaling),
1997 KX_PYATTRIBUTE_RW_FUNCTION("timeOffset",KX_GameObject, pyattr_get_timeOffset,pyattr_set_timeOffset),
1998 KX_PYATTRIBUTE_RW_FUNCTION("collisionCallbacks", KX_GameObject, pyattr_get_collisionCallbacks, pyattr_set_collisionCallbacks),
1999 KX_PYATTRIBUTE_RW_FUNCTION("state", KX_GameObject, pyattr_get_state, pyattr_set_state),
2000 KX_PYATTRIBUTE_RO_FUNCTION("meshes", KX_GameObject, pyattr_get_meshes),
2001 KX_PYATTRIBUTE_RW_FUNCTION("localOrientation",KX_GameObject,pyattr_get_localOrientation,pyattr_set_localOrientation),
2002 KX_PYATTRIBUTE_RW_FUNCTION("worldOrientation",KX_GameObject,pyattr_get_worldOrientation,pyattr_set_worldOrientation),
2003 KX_PYATTRIBUTE_RW_FUNCTION("localPosition", KX_GameObject, pyattr_get_localPosition, pyattr_set_localPosition),
2004 KX_PYATTRIBUTE_RW_FUNCTION("worldPosition", KX_GameObject, pyattr_get_worldPosition, pyattr_set_worldPosition),
2005 KX_PYATTRIBUTE_RW_FUNCTION("localScale", KX_GameObject, pyattr_get_localScaling, pyattr_set_localScaling),
2006 KX_PYATTRIBUTE_RW_FUNCTION("worldScale", KX_GameObject, pyattr_get_worldScaling, pyattr_set_worldScaling),
2007 KX_PYATTRIBUTE_RW_FUNCTION("localTransform", KX_GameObject, pyattr_get_localTransform, pyattr_set_localTransform),
2008 KX_PYATTRIBUTE_RW_FUNCTION("worldTransform", KX_GameObject, pyattr_get_worldTransform, pyattr_set_worldTransform),
2009 KX_PYATTRIBUTE_RW_FUNCTION("linearVelocity", KX_GameObject, pyattr_get_localLinearVelocity, pyattr_set_worldLinearVelocity),
2010 KX_PYATTRIBUTE_RW_FUNCTION("localLinearVelocity", KX_GameObject, pyattr_get_localLinearVelocity, pyattr_set_localLinearVelocity),
2011 KX_PYATTRIBUTE_RW_FUNCTION("worldLinearVelocity", KX_GameObject, pyattr_get_worldLinearVelocity, pyattr_set_worldLinearVelocity),
2012 KX_PYATTRIBUTE_RW_FUNCTION("angularVelocity", KX_GameObject, pyattr_get_localAngularVelocity, pyattr_set_worldAngularVelocity),
2013 KX_PYATTRIBUTE_RW_FUNCTION("localAngularVelocity", KX_GameObject, pyattr_get_localAngularVelocity, pyattr_set_localAngularVelocity),
2014 KX_PYATTRIBUTE_RW_FUNCTION("worldAngularVelocity", KX_GameObject, pyattr_get_worldAngularVelocity, pyattr_set_worldAngularVelocity),
2015 KX_PYATTRIBUTE_RW_FUNCTION("linearDamping", KX_GameObject, pyattr_get_linearDamping, pyattr_set_linearDamping),
2016 KX_PYATTRIBUTE_RW_FUNCTION("angularDamping", KX_GameObject, pyattr_get_angularDamping, pyattr_set_angularDamping),
2017 KX_PYATTRIBUTE_RO_FUNCTION("children", KX_GameObject, pyattr_get_children),
2018 KX_PYATTRIBUTE_RO_FUNCTION("childrenRecursive", KX_GameObject, pyattr_get_children_recursive),
2019 KX_PYATTRIBUTE_RO_FUNCTION("attrDict", KX_GameObject, pyattr_get_attrDict),
2020 KX_PYATTRIBUTE_RW_FUNCTION("color", KX_GameObject, pyattr_get_obcolor, pyattr_set_obcolor),
2021 KX_PYATTRIBUTE_RW_FUNCTION("debug", KX_GameObject, pyattr_get_debug, pyattr_set_debug),
2022 KX_PYATTRIBUTE_RW_FUNCTION("debugRecursive", KX_GameObject, pyattr_get_debugRecursive, pyattr_set_debugRecursive),
2024 /* experimental, don't rely on these yet */
2025 KX_PYATTRIBUTE_RO_FUNCTION("sensors", KX_GameObject, pyattr_get_sensors),
2026 KX_PYATTRIBUTE_RO_FUNCTION("controllers", KX_GameObject, pyattr_get_controllers),
2027 KX_PYATTRIBUTE_RO_FUNCTION("actuators", KX_GameObject, pyattr_get_actuators),
2031 PyObject *KX_GameObject::PyReplaceMesh(PyObject *args)
2033 KX_Scene *scene = KX_GetActiveScene();
2036 int use_gfx= 1, use_phys= 0;
2037 RAS_MeshObject *new_mesh;
2039 if (!PyArg_ParseTuple(args,"O|ii:replaceMesh", &value, &use_gfx, &use_phys))
2042 if (!ConvertPythonToMesh(value, &new_mesh, false, "gameOb.replaceMesh(value): KX_GameObject"))
2045 scene->ReplaceMesh(this, new_mesh, (bool)use_gfx, (bool)use_phys);
2049 PyObject *KX_GameObject::PyEndObject()
2051 KX_Scene* scene = GetScene();
2053 scene->DelayedRemoveObject(this);
2059 PyObject *KX_GameObject::PyReinstancePhysicsMesh(PyObject *args)
2061 KX_GameObject *gameobj= NULL;
2062 RAS_MeshObject *mesh= NULL;
2064 PyObject *gameobj_py= NULL;
2065 PyObject *mesh_py= NULL;
2067 if ( !PyArg_ParseTuple(args,"|OO:reinstancePhysicsMesh",&gameobj_py, &mesh_py) ||
2068 (gameobj_py && !ConvertPythonToGameObject(gameobj_py, &gameobj, true, "gameOb.reinstancePhysicsMesh(obj, mesh): KX_GameObject")) ||
2069 (mesh_py && !ConvertPythonToMesh(mesh_py, &mesh, true, "gameOb.reinstancePhysicsMesh(obj, mesh): KX_GameObject"))
2074 /* gameobj and mesh can be NULL */
2075 if (GetPhysicsController() && GetPhysicsController()->ReinstancePhysicsShape(gameobj, mesh))
2081 static PyObject *Map_GetItem(PyObject *self_v, PyObject *item)
2083 KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
2084 const char *attr_str= _PyUnicode_AsString(item);
2086 PyObject *pyconvert;
2089 PyErr_SetString(PyExc_SystemError, "val = gameOb[key]: KX_GameObject, " BGE_PROXY_ERROR_MSG);
2093 /* first see if the attributes a string and try get the cvalue attribute */
2094 if (attr_str && (resultattr=self->GetProperty(attr_str))) {
2095 pyconvert = resultattr->ConvertValueToPython();
2096 return pyconvert ? pyconvert:resultattr->GetProxy();
2098 /* no CValue attribute, try get the python only m_attr_dict attribute */
2099 else if (self->m_attr_dict && (pyconvert=PyDict_GetItem(self->m_attr_dict, item))) {
2103 Py_INCREF(pyconvert);
2107 if (attr_str) PyErr_Format(PyExc_KeyError, "value = gameOb[key]: KX_GameObject, key \"%s\" does not exist", attr_str);
2108 else PyErr_SetString(PyExc_KeyError, "value = gameOb[key]: KX_GameObject, key does not exist");
2115 static int Map_SetItem(PyObject *self_v, PyObject *key, PyObject *val)
2117 KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
2118 const char *attr_str= _PyUnicode_AsString(key);
2123 PyErr_SetString(PyExc_SystemError, "gameOb[key] = value: KX_GameObject, " BGE_PROXY_ERROR_MSG);
2127 if (val==NULL) { /* del ob["key"] */
2130 /* try remove both just in case */
2132 del |= (self->RemoveProperty(attr_str)==true) ? 1:0;
2134 if (self->m_attr_dict)
2135 del |= (PyDict_DelItem(self->m_attr_dict, key)==0) ? 1:0;
2138 if (attr_str) PyErr_Format(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key \"%s\" could not be set", attr_str);
2139 else PyErr_SetString(PyExc_KeyError, "del gameOb[key]: KX_GameObject, key could not be deleted");
2142 else if (self->m_attr_dict) {
2143 PyErr_Clear(); /* PyDict_DelItem sets an error when it fails */
2146 else { /* ob["key"] = value */
2150 if (attr_str && PyObject_TypeCheck(val, &PyObjectPlus::Type)==0) /* don't allow GameObjects for eg to be assigned to CValue props */
2152 CValue *vallie = self->ConvertPythonToValue(val, false, "gameOb[key] = value: ");
2155 CValue* oldprop = self->GetProperty(attr_str);
2158 oldprop->SetValue(vallie);
2160 self->SetProperty(attr_str, vallie);
2165 /* try remove dict value to avoid double ups */
2166 if (self->m_attr_dict) {
2167 if (PyDict_DelItem(self->m_attr_dict, key) != 0)
2171 else if (PyErr_Occurred()) {
2177 if (self->m_attr_dict==NULL) /* lazy init */
2178 self->m_attr_dict= PyDict_New();
2181 if (PyDict_SetItem(self->m_attr_dict, key, val)==0)
2184 self->RemoveProperty(attr_str); /* overwrite the CValue if it exists */
2188 if (attr_str) PyErr_Format(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key \"%s\" not be added to internal dictionary", attr_str);
2189 else PyErr_SetString(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key not be added to internal dictionary");
2194 return -1; /* pythons error value */
2199 return 0; /* success */
2202 static int Seq_Contains(PyObject *self_v, PyObject *value)
2204 KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
2207 PyErr_SetString(PyExc_SystemError, "val in gameOb: KX_GameObject, " BGE_PROXY_ERROR_MSG);
2211 if (PyUnicode_Check(value) && self->GetProperty(_PyUnicode_AsString(value)))
2214 if (self->m_attr_dict && PyDict_GetItem(self->m_attr_dict, value))
2221 PyMappingMethods KX_GameObject::Mapping = {
2222 (lenfunc)NULL , /*inquiry mp_length */
2223 (binaryfunc)Map_GetItem, /*binaryfunc mp_subscript */
2224 (objobjargproc)Map_SetItem, /*objobjargproc mp_ass_subscript */
2227 PySequenceMethods KX_GameObject::Sequence = {
2228 NULL, /* Cant set the len otherwise it can evaluate as false */
2229 NULL, /* sq_concat */
2230 NULL, /* sq_repeat */
2232 NULL, /* sq_slice */
2233 NULL, /* sq_ass_item */
2234 NULL, /* sq_ass_slice */
2235 (objobjproc)Seq_Contains, /* sq_contains */
2236 (binaryfunc) NULL, /* sq_inplace_concat */
2237 (ssizeargfunc) NULL, /* sq_inplace_repeat */
2240 PyTypeObject KX_GameObject::Type = {
2241 PyVarObject_HEAD_INIT(NULL, 0)
2243 sizeof(PyObjectPlus_Proxy),
2258 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
2268 PyObject *KX_GameObject::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2270 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2271 return PyUnicode_From_STR_String(self->GetName());
2274 PyObject *KX_GameObject::pyattr_get_parent(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2276 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2277 KX_GameObject* parent = self->GetParent();
2279 return parent->GetProxy();
2284 PyObject *KX_GameObject::pyattr_get_group_members(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2286 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2287 CListValue* instances = self->GetInstanceObjects();
2289 return instances->GetProxy();
2294 PyObject* KX_GameObject::pyattr_get_collisionCallbacks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2296 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2298 // Only objects with a physics controller should have collision callbacks
2299 if (!self->GetPhysicsController()) {
2300 PyErr_SetString(PyExc_AttributeError, "KX_GameObject.collisionCallbacks: attribute only available for objects with collisions enabled");
2304 // Return the existing callbacks
2305 if (self->m_collisionCallbacks == NULL)
2307 self->m_collisionCallbacks = PyList_New(0);
2308 // Subscribe to collision update from KX_TouchManager
2309 self->RegisterCollisionCallbacks();
2311 Py_INCREF(self->m_collisionCallbacks);
2312 return self->m_collisionCallbacks;
2315 int KX_GameObject::pyattr_set_collisionCallbacks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2317 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2319 // Only objects with a physics controller should have collision callbacks
2320 if (!self->GetPhysicsController()) {
2321 PyErr_SetString(PyExc_AttributeError, "KX_GameObject.collisionCallbacks: attribute only available for objects with collisions enabled");
2322 return PY_SET_ATTR_FAIL;
2325 if (!PyList_CheckExact(value))
2327 PyErr_SetString(PyExc_ValueError, "Expected a list");
2328 return PY_SET_ATTR_FAIL;
2331 if (self->m_collisionCallbacks == NULL) {
2332 self->RegisterCollisionCallbacks();
2334 Py_DECREF(self->m_collisionCallbacks);
2340 self->m_collisionCallbacks = value;
2342 return PY_SET_ATTR_SUCCESS;
2345 PyObject* KX_GameObject::pyattr_get_scene(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2347 KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
2348 KX_Scene *scene = self->GetScene();
2350 return scene->GetProxy();
2355 PyObject *KX_GameObject::pyattr_get_group_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2357 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2358 KX_GameObject* pivot = self->GetDupliGroupObject();
2360 return pivot->GetProxy();
2365 PyObject *KX_GameObject::pyattr_get_life(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2367 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2369 CValue *life = self->GetProperty("::timebomb");
2371 // this convert the timebomb seconds to frames, hard coded 50.0 (assuming 50fps)
2372 // value hardcoded in KX_Scene::AddReplicaObject()
2373 return PyFloat_FromDouble(life->GetNumber() * 50.0);
2378 PyObject *KX_GameObject::pyattr_get_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2380 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2381 PHY_IPhysicsController *spc = self->GetPhysicsController();
2382 return PyFloat_FromDouble(spc ? spc->GetMass() : 0.0);
2385 int KX_GameObject::pyattr_set_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2387 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2388 PHY_IPhysicsController *spc = self->GetPhysicsController();
2389 MT_Scalar val = PyFloat_AsDouble(value);
2390 if (val < 0.0) { /* also accounts for non float */
2391 PyErr_SetString(PyExc_AttributeError, "gameOb.mass = float: KX_GameObject, expected a float zero or above");
2392 return PY_SET_ATTR_FAIL;
2398 return PY_SET_ATTR_SUCCESS;
2401 PyObject *KX_GameObject::pyattr_get_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2403 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2404 PHY_IPhysicsController *spc = self->GetPhysicsController();
2405 return PyFloat_FromDouble(spc ? spc->GetLinVelocityMin() : 0.0f);
2408 int KX_GameObject::pyattr_set_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2410 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2411 PHY_IPhysicsController *spc = self->GetPhysicsController();
2412 MT_Scalar val = PyFloat_AsDouble(value);
2413 if (val < 0.0) { /* also accounts for non float */
2414 PyErr_SetString(PyExc_AttributeError, "gameOb.linVelocityMin = float: KX_GameObject, expected a float zero or above");
2415 return PY_SET_ATTR_FAIL;
2419 spc->SetLinVelocityMin(val);
2421 return PY_SET_ATTR_SUCCESS;
2424 PyObject *KX_GameObject::pyattr_get_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2426 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2427 PHY_IPhysicsController *spc = self->GetPhysicsController();
2428 return PyFloat_FromDouble(spc ? spc->GetLinVelocityMax() : 0.0f);
2431 int KX_GameObject::pyattr_set_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2433 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2434 PHY_IPhysicsController *spc = self->GetPhysicsController();
2435 MT_Scalar val = PyFloat_AsDouble(value);
2436 if (val < 0.0) { /* also accounts for non float */
2437 PyErr_SetString(PyExc_AttributeError, "gameOb.linVelocityMax = float: KX_GameObject, expected a float zero or above");
2438 return PY_SET_ATTR_FAIL;
2442 spc->SetLinVelocityMax(val);
2444 return PY_SET_ATTR_SUCCESS;
2448 PyObject *KX_GameObject::pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2450 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2451 return PyBool_FromLong(self->GetVisible());
2454 int KX_GameObject::pyattr_set_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2456 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2457 int param = PyObject_IsTrue( value );
2459 PyErr_SetString(PyExc_AttributeError, "gameOb.visible = bool: KX_GameObject, expected True or False");
2460 return PY_SET_ATTR_FAIL;
2463 self->SetVisible(param, false);
2464 self->UpdateBuckets(false);
2465 return PY_SET_ATTR_SUCCESS;
2468 PyObject *KX_GameObject::pyattr_get_record_animation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2470 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2471 return PyBool_FromLong(self->IsRecordAnimation());
2474 int KX_GameObject::pyattr_set_record_animation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2476 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2477 int param = PyObject_IsTrue(value);
2479 PyErr_SetString(PyExc_AttributeError, "gameOb.record_animation = bool: KX_GameObject, expected boolean");
2480 return PY_SET_ATTR_FAIL;
2483 self->SetRecordAnimation(param);
2485 return PY_SET_ATTR_SUCCESS;
2490 PyObject *KX_GameObject::pyattr_get_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2492 #ifdef USE_MATHUTILS
2493 return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_POS_GLOBAL);
2495 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2496 return PyObjectFrom(self->NodeGetWorldPosition());
2500 int KX_GameObject::pyattr_set_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2502 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2504 if (!PyVecTo(value, pos))
2505 return PY_SET_ATTR_FAIL;
2507 self->NodeSetWorldPosition(pos);
2508 self->NodeUpdateGS(0.f);
2509 return PY_SET_ATTR_SUCCESS;
2512 PyObject *KX_GameObject::pyattr_get_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2514 #ifdef USE_MATHUTILS
2515 return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_POS_LOCAL);
2517 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2518 return PyObjectFrom(self->NodeGetLocalPosition());
2522 int KX_GameObject::pyattr_set_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2524 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2526 if (!PyVecTo(value, pos))
2527 return PY_SET_ATTR_FAIL;
2529 self->NodeSetLocalPosition(pos);
2530 self->NodeUpdateGS(0.f);
2531 return PY_SET_ATTR_SUCCESS;
2534 PyObject *KX_GameObject::pyattr_get_localInertia(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2536 #ifdef USE_MATHUTILS
2537 return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_INERTIA_LOCAL);
2539 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2540 if (self->GetPhysicsController1())
2541 return PyObjectFrom(self->GetPhysicsController1()->GetLocalInertia());
2542 return Py_BuildValue("fff", 0.0f, 0.0f, 0.0f);
2546 PyObject *KX_GameObject::pyattr_get_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2548 #ifdef USE_MATHUTILS
2549 return Matrix_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, 3, mathutils_kxgameob_matrix_cb_index, MATHUTILS_MAT_CB_ORI_GLOBAL);
2551 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2552 return PyObjectFrom(self->NodeGetWorldOrientation());
2556 int KX_GameObject::pyattr_set_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2558 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2560 /* if value is not a sequence PyOrientationTo makes an error */
2562 if (!PyOrientationTo(value, rot, "gameOb.worldOrientation = sequence: KX_GameObject, "))
2563 return PY_SET_ATTR_FAIL;
2565 self->NodeSetGlobalOrientation(rot);
2567 self->NodeUpdateGS(0.f);
2568 return PY_SET_ATTR_SUCCESS;
2571 PyObject *KX_GameObject::pyattr_get_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2573 #ifdef USE_MATHUTILS
2574 return Matrix_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, 3, mathutils_kxgameob_matrix_cb_index, MATHUTILS_MAT_CB_ORI_LOCAL);
2576 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2577 return PyObjectFrom(self->NodeGetLocalOrientation());
2581 int KX_GameObject::pyattr_set_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2583 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2585 /* if value is not a sequence PyOrientationTo makes an error */
2587 if (!PyOrientationTo(value, rot, "gameOb.localOrientation = sequence: KX_GameObject, "))
2588 return PY_SET_ATTR_FAIL;
2590 self->NodeSetLocalOrientation(rot);
2591 self->NodeUpdateGS(0.f);
2592 return PY_SET_ATTR_SUCCESS;
2595 PyObject *KX_GameObject::pyattr_get_worldScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2597 #ifdef USE_MATHUTILS
2598 return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_SCALE_GLOBAL);
2600 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2601 return PyObjectFrom(self->NodeGetWorldScaling());
2605 int KX_GameObject::pyattr_set_worldScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2607 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2609 if (!PyVecTo(value, scale))
2610 return PY_SET_ATTR_FAIL;
2612 self->NodeSetWorldScale(scale);
2613 self->NodeUpdateGS(0.f);
2614 return PY_SET_ATTR_SUCCESS;
2617 PyObject *KX_GameObject::pyattr_get_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2619 #ifdef USE_MATHUTILS
2620 return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_SCALE_LOCAL);
2622 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2623 return PyObjectFrom(self->NodeGetLocalScaling());
2627 int KX_GameObject::pyattr_set_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2629 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2631 if (!PyVecTo(value, scale))
2632 return PY_SET_ATTR_FAIL;
2634 self->NodeSetLocalScale(scale);
2635 self->NodeUpdateGS(0.f);
2636 return PY_SET_ATTR_SUCCESS;
2639 PyObject *KX_GameObject::pyattr_get_localTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2641 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2647 trans.setOrigin(self->GetSGNode()->GetLocalPosition());
2648 trans.setBasis(self->GetSGNode()->GetLocalOrientation());
2650 MT_Vector3 scaling = self->GetSGNode()->GetLocalScale();
2651 trans.scale(scaling[0], scaling[1], scaling[2]);
2653 trans.getValue(mat);
2655 return PyObjectFrom(MT_Matrix4x4(mat));
2658 int KX_GameObject::pyattr_set_localTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2660 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2662 if (!PyMatTo(value, temp))
2663 return PY_SET_ATTR_FAIL;
2665 float transform[4][4];
2666 float loc[3], size[3];
2668 MT_Matrix3x3 orientation;
2670 temp.getValue(*transform);
2671 mat4_to_loc_rot_size(loc, rot, size, transform);
2673 self->NodeSetLocalPosition(MT_Point3(loc));
2675 //MT_Matrix3x3's constructor expects a 4x4 matrix
2676 orientation = MT_Matrix3x3();
2677 orientation.setValue3x3(*rot);
2678 self->NodeSetLocalOrientation(orientation);
2680 self->NodeSetLocalScale(MT_Vector3(size));
2682 return PY_SET_ATTR_SUCCESS;
2685 PyObject *KX_GameObject::pyattr_get_worldTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2687 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2689 return PyObjectFrom(MT_Matrix4x4(self->GetOpenGLMatrix()));
2692 int KX_GameObject::pyattr_set_worldTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2694 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2696 if (!PyMatTo(value, temp))
2697 return PY_SET_ATTR_FAIL;
2699 float transform[4][4];
2700 float loc[3], size[3];
2702 MT_Matrix3x3 orientation;
2704 temp.getValue(*transform);
2705 mat4_to_loc_rot_size(loc, rot, size, transform);
2707 self->NodeSetWorldPosition(MT_Point3(loc));
2709 //MT_Matrix3x3's constructor expects a 4x4 matrix
2710 orientation = MT_Matrix3x3();
2711 orientation.setValue3x3(*rot);
2712 self->NodeSetGlobalOrientation(orientation);
2714 self->NodeSetWorldScale(MT_Vector3(size));
2716 return PY_SET_ATTR_SUCCESS;
2719 PyObject *KX_GameObject::pyattr_get_worldLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2721 #ifdef USE_MATHUTILS
2722 return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_LINVEL_GLOBAL);
2724 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2725 return PyObjectFrom(GetLinearVelocity(false));
2729 int KX_GameObject::pyattr_set_worldLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2731 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2732 MT_Vector3 velocity;
2733 if (!PyVecTo(value, velocity))
2734 return PY_SET_ATTR_FAIL;
2736 self->setLinearVelocity(velocity, false);
2738 return PY_SET_ATTR_SUCCESS;
2741 PyObject *KX_GameObject::pyattr_get_localLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2743 #ifdef USE_MATHUTILS
2744 return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_LINVEL_LOCAL);
2746 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2747 return PyObjectFrom(GetLinearVelocity(true));
2751 int KX_GameObject::pyattr_set_localLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2753 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2754 MT_Vector3 velocity;
2755 if (!PyVecTo(value, velocity))
2756 return PY_SET_ATTR_FAIL;
2758 self->setLinearVelocity(velocity, true);
2760 return PY_SET_ATTR_SUCCESS;
2763 PyObject *KX_GameObject::pyattr_get_worldAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2765 #ifdef USE_MATHUTILS
2766 return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_ANGVEL_GLOBAL);
2768 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2769 return PyObjectFrom(GetAngularVelocity(false));
2773 int KX_GameObject::pyattr_set_worldAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2775 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2776 MT_Vector3 velocity;
2777 if (!PyVecTo(value, velocity))
2778 return PY_SET_ATTR_FAIL;
2780 self->setAngularVelocity(velocity, false);
2782 return PY_SET_ATTR_SUCCESS;
2785 PyObject *KX_GameObject::pyattr_get_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2787 #ifdef USE_MATHUTILS
2788 return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_ANGVEL_LOCAL);
2790 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2791 return PyObjectFrom(GetAngularVelocity(true));
2795 int KX_GameObject::pyattr_set_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2797 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2798 MT_Vector3 velocity;
2799 if (!PyVecTo(value, velocity))
2800 return PY_SET_ATTR_FAIL;
2802 self->setAngularVelocity(velocity, true);
2804 return PY_SET_ATTR_SUCCESS;
2807 PyObject *KX_GameObject::pyattr_get_linearDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2809 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2810 return PyFloat_FromDouble(self->getLinearDamping());
2813 int KX_GameObject::pyattr_set_linearDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2815 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2816 float val = PyFloat_AsDouble(value);
2817 self->setLinearDamping(val);
2818 return PY_SET_ATTR_SUCCESS;
2821 PyObject *KX_GameObject::pyattr_get_angularDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2823 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2824 return PyFloat_FromDouble(self->getAngularDamping());
2827 int KX_GameObject::pyattr_set_angularDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2829 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2830 float val = PyFloat_AsDouble(value);
2831 self->setAngularDamping(val);
2832 return PY_SET_ATTR_SUCCESS;
2836 PyObject *KX_GameObject::pyattr_get_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2838 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2840 if (self->GetSGNode() && (sg_parent = self->GetSGNode()->GetSGParent()) != NULL && sg_parent->IsSlowParent()) {
2841 return PyFloat_FromDouble(static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->GetTimeOffset());
2843 return PyFloat_FromDouble(0.0);
2847 int KX_GameObject::pyattr_set_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2849 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2850 if (self->GetSGNode()) {
2851 MT_Scalar val = PyFloat_AsDouble(value);
2852 SG_Node *sg_parent= self->GetSGNode()->GetSGParent();
2853 if (val < 0.0) { /* also accounts for non float */
2854 PyErr_SetString(PyExc_AttributeError, "gameOb.timeOffset = float: KX_GameObject, expected a float zero or above");
2855 return PY_SET_ATTR_FAIL;
2857 if (sg_parent && sg_parent->IsSlowParent())
2858 static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->SetTimeOffset(val);
2860 return PY_SET_ATTR_SUCCESS;
2863 PyObject *KX_GameObject::pyattr_get_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2865 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2867 state |= self->GetState();
2868 return PyLong_FromLong(state);
2871 int KX_GameObject::pyattr_set_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2873 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2874 int state_i = PyLong_AsLong(value);
2875 unsigned int state = 0;
2877 if (state_i == -1 && PyErr_Occurred()) {
2878 PyErr_SetString(PyExc_TypeError, "gameOb.state = int: KX_GameObject, expected an int bit field");
2879 return PY_SET_ATTR_FAIL;
2883 if ((state & ((1<<30)-1)) == 0) {
2884 PyErr_SetString(PyExc_AttributeError, "gameOb.state = int: KX_GameObject, state bitfield was not between 0 and 30 (1<<0 and 1<<29)");
2885 return PY_SET_ATTR_FAIL;
2887 self->SetState(state);
2888 return PY_SET_ATTR_SUCCESS;
2891 PyObject *KX_GameObject::pyattr_get_meshes(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2893 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2894 PyObject *meshes= PyList_New(self->m_meshes.size());
2897 for (i=0; i < (int)self->m_meshes.size(); i++)
2899 KX_MeshProxy* meshproxy = new KX_MeshProxy(self->m_meshes[i]);
2900 PyList_SET_ITEM(meshes, i, meshproxy->NewProxy(true));
2906 PyObject *KX_GameObject::pyattr_get_obcolor(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2908 #ifdef USE_MATHUTILS
2909 return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 4, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_OBJECT_COLOR);
2911 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2912 return PyObjectFrom(self->GetObjectColor());
2916 int KX_GameObject::pyattr_set_obcolor(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2918 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2920 if (!PyVecTo(value, obcolor))
2921 return PY_SET_ATTR_FAIL;
2923 self->SetObjectColor(obcolor);
2924 return PY_SET_ATTR_SUCCESS;
2927 /* These are experimental! */
2928 PyObject *KX_GameObject::pyattr_get_sensors(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2930 return KX_PythonSeq_CreatePyObject((static_cast<KX_GameObject*>(self_v))->m_proxy, KX_PYGENSEQ_OB_TYPE_SENSORS);
2933 PyObject *KX_GameObject::pyattr_get_controllers(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2935 return KX_PythonSeq_CreatePyObject((static_cast<KX_GameObject*>(self_v))->m_proxy, KX_PYGENSEQ_OB_TYPE_CONTROLLERS);
2938 PyObject *KX_GameObject::pyattr_get_actuators(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2940 return KX_PythonSeq_CreatePyObject((static_cast<KX_GameObject*>(self_v))->m_proxy, KX_PYGENSEQ_OB_TYPE_ACTUATORS);
2942 /* End experimental */
2944 PyObject *KX_GameObject::pyattr_get_children(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2946 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2947 return self->GetChildren()->NewProxy(true);
2950 PyObject *KX_GameObject::pyattr_get_children_recursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2952 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2953 return self->GetChildrenRecursive()->NewProxy(true);
2956 PyObject *KX_GameObject::pyattr_get_attrDict(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2958 KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2960 if (self->m_attr_dict==NULL)
2961 self->m_attr_dict= PyDict_New();
2963 Py_INCREF(self->m_attr_dict);
2964 return self->m_attr_dict;
2967 PyObject *KX_GameObject::pyattr_get_debug(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2969 KX_Scene *scene = KX_GetActiveScene();
2970 KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
2972 return PyBool_FromLong(scene->ObjectInDebugList(self));
2975 int KX_GameObject::pyattr_set_debug(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2977 KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
2978 int param = PyObject_IsTrue(value);
2981 PyErr_SetString(PyExc_AttributeError, "gameOb.debug = bool: KX_GameObject, expected True or False");
2982 return PY_SET_ATTR_FAIL;
2985 self->SetUseDebugProperties(param, false);
2987 return PY_SET_ATTR_SUCCESS;
2990 PyObject *KX_GameObject::pyattr_get_debugRecursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2992 KX_Scene *scene = KX_GetActiveScene();
2993 KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
2995 return PyBool_FromLong(scene->ObjectInDebugList(self));
2998 int KX_GameObject::pyattr_set_debugRecursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
3000 KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
3001 int param = PyObject_IsTrue(value);
3004 PyErr_SetString(PyExc_AttributeError, "gameOb.debugRecursive = bool: KX_GameObject, expected True or False");
3005 return PY_SET_ATTR_FAIL;
3008 self->SetUseDebugProperties(param, true);
3010 return PY_SET_ATTR_SUCCESS;
3013 PyObject *KX_GameObject::PyApplyForce(PyObject *args)
3018 if (PyArg_ParseTuple(args, "O|i:applyForce", &pyvect, &local)) {
3020 if (PyVecTo(pyvect, force)) {
3021 ApplyForce(force, (local!=0));
3028 PyObject *KX_GameObject::PyApplyTorque(PyObject *args)
3033 if (PyArg_ParseTuple(args, "O|i:applyTorque", &pyvect, &local)) {
3035 if (PyVecTo(pyvect, torque)) {
3036 ApplyTorque(torque, (local!=0));
3043 PyObject *KX_GameObject::PyApplyRotation(PyObject *args)
3048 if (PyArg_ParseTuple(args, "O|i:applyRotation", &pyvect, &local)) {
3049 MT_Vector3 rotation;
3050 if (PyVecTo(pyvect, rotation)) {
3051 ApplyRotation(rotation, (local!=0));
3058 PyObject *KX_GameObject::PyApplyMovement(PyObject *args)
3063 if (PyArg_ParseTuple(args, "O|i:applyMovement", &pyvect, &local)) {
3064 MT_Vector3 movement;
3065 if (PyVecTo(pyvect, movement)) {
3066 ApplyMovement(movement, (local!=0));
3073 PyObject *KX_GameObject::PyGetLinearVelocity(PyObject *args)
3075 // only can get the velocity if we have a physics object connected to us...
3077 if (PyArg_ParseTuple(args,"|i:getLinearVelocity",&local))
3079 return PyObjectFrom(GetLinearVelocity((local!=0)));
3087 PyObject *KX_GameObject::PySetLinearVelocity(PyObject *args)
3092 if (PyArg_ParseTuple(args,"O|i:setLinearVelocity",&pyvect,&local)) {
3093 MT_Vector3 velocity;
3094 if (PyVecTo(pyvect, velocity)) {
3095 setLinearVelocity(velocity, (local!=0));
3102 PyObject *KX_GameObject::PyGetAngularVelocity(PyObject *args)
3104 // only can get the velocity if we have a physics object connected to us...
3106 if (PyArg_ParseTuple(args,"|i:getAngularVelocity",&local))
3108 return PyObjectFrom(GetAngularVelocity((local!=0)));
3116 PyObject *KX_GameObject::PySetAngularVelocity(PyObject *args)
3121 if (PyArg_ParseTuple(args,"O|i:setAngularVelocity",&pyvect,&local)) {
3122 MT_Vector3 velocity;
3123 if (PyVecTo(pyvect, velocity)) {
3124 setAngularVelocity(velocity, (local!=0));
3131 PyObject *KX_GameObject::PySetDamping(PyObject *args)
3136 if (!PyArg_ParseTuple(args,"ff|i:setDamping", &linear, &angular))
3139 setDamping(linear, angular);
3143 PyObject *KX_GameObject::PySetVisible(PyObject *args)
3145 int visible, recursive = 0;
3146 if (!PyArg_ParseTuple(args,"i|i:setVisible",&visible, &recursive))
3149 SetVisible(visible ? true:false, recursive ? true:false);
3150 UpdateBuckets(recursive ? true:false);
3155 PyObject *KX_GameObject::PySetOcclusion(PyObject *args)
3157 int occlusion, recursive = 0;
3158 if (!PyArg_ParseTuple(args,"i|i:setOcclusion",&occlusion, &recursive))
3161 SetOccluder(occlusion ? true:false, recursive ? true:false);
3165 PyObject *KX_GameObject::PyGetVelocity(PyObject *args)
3167 // only can get the velocity if we have a physics object connected to us...
3168 MT_Point3 point(0.0,0.0,0.0);
3169 PyObject *pypos = NULL;
3171 if (!PyArg_ParseTuple(args, "|O:getVelocity", &pypos) || (pypos && !PyVecTo(pypos, point)))
3174 return PyObjectFrom(GetVelocity(point));
3177 PyObject *KX_GameObject::PyGetReactionForce()
3179 // only can get the velocity if we have a physics object connected to us...
3181 // XXX - Currently not working with bullet intergration, see KX_BulletPhysicsController.cpp's getReactionForce
3183 if (GetPhysicsController1())
3184 return PyObjectFrom(GetPhysicsController1()->getReactionForce());
3185 return PyObjectFrom(dummy_point);
3188 return Py_BuildValue("fff", 0.0, 0.0, 0.0);
3194 PyObject *KX_GameObject::PyEnableRigidBody()
3196 if (GetPhysicsController())
3197 GetPhysicsController()->SetRigidBody(true);
3204 PyObject *KX_GameObject::PyDisableRigidBody()
3206 if (GetPhysicsController())
3207 GetPhysicsController()->SetRigidBody(false);
3213 PyObject *KX_GameObject::PySetParent(PyObject *args)
3215 KX_Scene *scene = KX_GetActiveScene();
3218 int addToCompound=1, ghost=1;
3220 if (!PyArg_ParseTuple(args,"O|ii:setParent", &pyobj, &addToCompound, &ghost)) {
3221 return NULL; // Python sets a simple error
3223 if (!ConvertPythonToGameObject(pyobj, &obj, true, "gameOb.setParent(obj): KX_GameObject"))
3226 this->SetParent(scene, obj, addToCompound, ghost);
3230 PyObject *KX_GameObject::PyRemoveParent()
3232 KX_Scene *scene = KX_GetActiveScene();
3234 this->RemoveParent(scene);
3239 PyObject *KX_GameObject::PySetCollisionMargin(PyObject *value)
3241 float collisionMargin = PyFloat_AsDouble(value);
3243 if (collisionMargin==-1 && PyErr_Occurred()) {
3244 PyErr_SetString(PyExc_TypeError, "expected a float");
3248 if (m_pPhysicsController)
3250 m_pPhysicsController->SetMargin(collisionMargin);
3253 PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller");
3259 PyObject *KX_GameObject::PyApplyImpulse(PyObject *args)
3262 PyObject *pyimpulse;
3265 if (!m_pPhysicsController) {
3266 PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller");
3270 if (PyArg_ParseTuple(args, "OO|i:applyImpulse", &pyattach, &pyimpulse, &local))
3274 if (PyVecTo(pyattach, attach) && PyVecTo(pyimpulse, impulse))
3276 m_pPhysicsController->ApplyImpulse(attach, impulse, (local!=0));
3287 PyObject *KX_GameObject::PySuspendDynamics()
3289 if (GetPhysicsController())
3290 GetPhysicsController()->SuspendDynamics();
3296 PyObject *KX_GameObject::PyRestoreDynamics()
3298 if (GetPhysicsController())
3299 GetPhysicsController()->RestoreDynamics();
3304 PyObject *KX_GameObject::PyAlignAxisToVect(PyObject *args)
3307 int axis = 2; //z axis is the default
3310 if (PyArg_ParseTuple(args,"O|if:alignAxisToVect",&pyvect,&axis, &fac))
3313 if (PyVecTo(pyvect, vect)) {
3315 if (fac> 1.0f) fac = 1.0f;
3317 AlignAxisToVect(vect, axis, fac);
3326 PyObject *KX_GameObject::PyGetAxisVect(PyObject *value)
3329 if (PyVecTo(value, vect))
3331 return PyObjectFrom(NodeGetWorldOrientation() * vect);
3337 PyObject *KX_GameObject::PyGetPhysicsId()
3339 PHY_IPhysicsController* ctrl = GetPhysicsController();
3340 unsigned long long physid = 0;
3343 physid = (unsigned long long)ctrl;
3345 return PyLong_FromUnsignedLongLong(physid);
3348 PyObject *KX_GameObject::PyGetPropertyNames()
3350 PyObject *list= ConvertKeysToPython();
3353 PyObject *key, *value;
3356 while (PyDict_Next(m_attr_dict, &pos, &key, &value)) {
3357 PyList_Append(list, key);
3363 KX_PYMETHODDEF_DOC_O(KX_GameObject, getDistanceTo,
3364 "getDistanceTo(other): get distance to another point/KX_GameObject")
3367 if (PyVecTo(value, b))
3369 return PyFloat_FromDouble(NodeGetWorldPosition().distance(b));
3373 KX_GameObject *other;
3374 if (ConvertPythonToGameObject(value, &other, false, "gameOb.getDistanceTo(value): KX_GameObject"))
3376 return PyFloat_FromDouble(NodeGetWorldPosition().distance(other->NodeGetWorldPosition()));
3382 KX_PYMETHODDEF_DOC_O(KX_GameObject, getVectTo,
3383 "getVectTo(other): get vector and the distance to another point/KX_GameObject\n"
3384 "Returns a 3-tuple with (distance,worldVector,localVector)\n")
3386 MT_Point3 toPoint, fromPoint;
3387 MT_Vector3 toDir, locToDir;
3390 PyObject *returnValue;