4 * ***** BEGIN GPL LICENSE BLOCK *****
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21 * All rights reserved.
23 * The Original Code is: all of this file.
25 * Contributor(s): none yet.
27 * ***** END GPL LICENSE BLOCK *****
36 typedef unsigned __int64 uint_ptr;
38 typedef unsigned long uint_ptr;
42 // This warning tells us about truncation of __long__ stl-generated names.
43 // It can occasionally cause DevStudio to have internal compiler warnings.
44 #pragma warning( disable : 4786 )
48 #define KX_INERTIA_INFINITE 10000
49 #include "RAS_IPolygonMaterial.h"
50 #include "KX_BlenderMaterial.h"
51 #include "KX_GameObject.h"
52 #include "RAS_MeshObject.h"
53 #include "KX_MeshProxy.h"
54 #include "KX_PolyProxy.h"
55 #include <stdio.h> // printf
56 #include "SG_Controller.h"
57 #include "KX_IPhysicsController.h"
58 #include "PHY_IGraphicController.h"
60 #include "SG_Controller.h"
61 #include "KX_ClientObjectInfo.h"
62 #include "RAS_BucketManager.h"
63 #include "KX_RayCast.h"
64 #include "KX_PythonInit.h"
65 #include "KX_PyMath.h"
66 #include "SCA_IActuator.h"
67 #include "SCA_ISensor.h"
68 #include "SCA_IController.h"
70 #include "PyObjectPlus.h" /* python stuff */
72 // This file defines relationships between parents and children
73 // in the game engine.
75 #include "KX_SG_NodeRelationships.h"
77 static MT_Point3 dummy_point= MT_Point3(0.0, 0.0, 0.0);
79 KX_GameObject::KX_GameObject(
80 void* sgReplicationInfo,
81 SG_Callbacks callbacks,
87 m_pBlenderObject(NULL),
88 m_pBlenderGroupObject(NULL),
89 m_bSuspendDynamics(false),
90 m_bUseObjectColor(false),
91 m_bIsNegativeScaling(false),
94 m_pPhysicsController1(NULL),
95 m_pGraphicController(NULL),
96 m_pPhysicsEnvironment(NULL),
101 m_ignore_activity_culling = false;
102 m_pClient_info = new KX_ClientObjectInfo(this, KX_ClientObjectInfo::ACTOR);
103 m_pSGNode = new SG_Node(this,sgReplicationInfo,callbacks);
105 // define the relationship between this node and it's parent.
107 KX_NormalParentRelation * parent_relation =
108 KX_NormalParentRelation::New();
109 m_pSGNode->SetParentRelation(parent_relation);
114 KX_GameObject::~KX_GameObject()
118 // is this delete somewhere ?
121 delete m_pClient_info;
126 // must go through controllers and make sure they will not use us anymore
127 // This is important for KX_BulletPhysicsControllers that unregister themselves
128 // from the object when they are deleted.
129 SGControllerList::iterator contit;
130 SGControllerList& controllers = m_pSGNode->GetSGControllerList();
131 for (contit = controllers.begin();contit!=controllers.end();++contit)
133 (*contit)->ClearObject();
135 m_pSGNode->SetSGClientObject(NULL);
137 if (m_pGraphicController)
139 delete m_pGraphicController;
145 CValue* KX_GameObject:: Calc(VALUE_OPERATOR op, CValue *val)
152 CValue* KX_GameObject::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val)
159 const STR_String & KX_GameObject::GetText()
166 float KX_GameObject::GetNumber()
173 STR_String KX_GameObject::GetName()
180 void KX_GameObject::SetName(STR_String name)
183 }; // Set the name of the value
187 void KX_GameObject::ReplicaSetName(STR_String name)
196 KX_IPhysicsController* KX_GameObject::GetPhysicsController()
198 return m_pPhysicsController1;
205 KX_GameObject* KX_GameObject::GetParent()
207 KX_GameObject* result = NULL;
208 SG_Node* node = m_pSGNode;
210 while (node && !result)
212 node = node->GetSGParent();
214 result = (KX_GameObject*)node->GetSGClientObject();
224 void KX_GameObject::SetParent(KX_Scene *scene, KX_GameObject* obj)
226 // check on valid node in case a python controller holds a reference to a deleted object
227 if (obj && GetSGNode() && obj->GetSGNode() && GetSGNode()->GetSGParent() != obj->GetSGNode())
229 // Make sure the objects have some scale
230 MT_Vector3 scale1 = NodeGetWorldScaling();
231 MT_Vector3 scale2 = obj->NodeGetWorldScaling();
232 if (fabs(scale2[0]) < FLT_EPSILON ||
233 fabs(scale2[1]) < FLT_EPSILON ||
234 fabs(scale2[2]) < FLT_EPSILON ||
235 fabs(scale1[0]) < FLT_EPSILON ||
236 fabs(scale1[1]) < FLT_EPSILON ||
237 fabs(scale1[2]) < FLT_EPSILON) { return; }
239 // Remove us from our old parent and set our new parent
241 obj->GetSGNode()->AddChild(GetSGNode());
243 if (m_pPhysicsController1)
245 m_pPhysicsController1->SuspendDynamics(true);
247 // Set us to our new scale, position, and orientation
248 scale2[0] = 1.0/scale2[0];
249 scale2[1] = 1.0/scale2[1];
250 scale2[2] = 1.0/scale2[2];
251 scale1 = scale1 * scale2;
252 MT_Matrix3x3 invori = obj->NodeGetWorldOrientation().inverse();
253 MT_Vector3 newpos = invori*(NodeGetWorldPosition()-obj->NodeGetWorldPosition())*scale2;
255 NodeSetLocalScale(scale1);
256 NodeSetLocalPosition(MT_Point3(newpos[0],newpos[1],newpos[2]));
257 NodeSetLocalOrientation(invori*NodeGetWorldOrientation());
259 // object will now be a child, it must be removed from the parent list
260 CListValue* rootlist = scene->GetRootParentList();
261 if (rootlist->RemoveValue(this))
262 // the object was in parent list, decrement ref count as it's now removed
264 // if the new parent is a compound object, add this object shape to the compound shape.
265 // step 0: verify this object has physical controller
266 if (m_pPhysicsController1)
268 // step 1: find the top parent (not necessarily obj)
269 KX_GameObject* rootobj = (KX_GameObject*)obj->GetSGNode()->GetRootSGParent()->GetSGClientObject();
270 // step 2: verify it has a physical controller and compound shape
271 if (rootobj != NULL &&
272 rootobj->m_pPhysicsController1 != NULL &&
273 rootobj->m_pPhysicsController1->IsCompound())
275 rootobj->m_pPhysicsController1->AddCompoundChild(m_pPhysicsController1);
278 // graphically, the object hasn't change place, no need to update m_pGraphicController
282 void KX_GameObject::RemoveParent(KX_Scene *scene)
284 // check on valid node in case a python controller holds a reference to a deleted object
285 if (GetSGNode() && GetSGNode()->GetSGParent())
287 // get the root object to remove us from compound object if needed
288 KX_GameObject* rootobj = (KX_GameObject*)GetSGNode()->GetRootSGParent()->GetSGClientObject();
289 // Set us to the right spot
290 GetSGNode()->SetLocalScale(GetSGNode()->GetWorldScaling());
291 GetSGNode()->SetLocalOrientation(GetSGNode()->GetWorldOrientation());
292 GetSGNode()->SetLocalPosition(GetSGNode()->GetWorldPosition());
294 // Remove us from our parent
295 GetSGNode()->DisconnectFromParent();
297 // the object is now a root object, add it to the parentlist
298 CListValue* rootlist = scene->GetRootParentList();
299 if (!rootlist->SearchValue(this))
300 // object was not in root list, add it now and increment ref count
301 rootlist->Add(AddRef());
302 if (m_pPhysicsController1)
304 // in case this controller was added as a child shape to the parent
305 if (rootobj != NULL &&
306 rootobj->m_pPhysicsController1 != NULL &&
307 rootobj->m_pPhysicsController1->IsCompound())
309 rootobj->m_pPhysicsController1->RemoveCompoundChild(m_pPhysicsController1);
311 m_pPhysicsController1->RestoreDynamics();
313 // graphically, the object hasn't change place, no need to update m_pGraphicController
317 void KX_GameObject::ProcessReplica(KX_GameObject* replica)
319 replica->m_pPhysicsController1 = NULL;
320 replica->m_pGraphicController = NULL;
321 replica->m_pSGNode = NULL;
322 replica->m_pClient_info = new KX_ClientObjectInfo(*m_pClient_info);
323 replica->m_pClient_info->m_gameobject = replica;
324 replica->m_state = 0;
329 CValue* KX_GameObject::GetReplica()
331 KX_GameObject* replica = new KX_GameObject(*this);
333 // this will copy properties and so on...
334 CValue::AddDataToReplica(replica);
335 ProcessReplica(replica);
342 void KX_GameObject::ApplyForce(const MT_Vector3& force,bool local)
344 if (m_pPhysicsController1)
345 m_pPhysicsController1->ApplyForce(force,local);
350 void KX_GameObject::ApplyTorque(const MT_Vector3& torque,bool local)
352 if (m_pPhysicsController1)
353 m_pPhysicsController1->ApplyTorque(torque,local);
358 void KX_GameObject::ApplyMovement(const MT_Vector3& dloc,bool local)
360 if (m_pPhysicsController1) // (IsDynamic())
362 m_pPhysicsController1->RelativeTranslate(dloc,local);
364 GetSGNode()->RelativeTranslate(dloc,GetSGNode()->GetSGParent(),local);
369 void KX_GameObject::ApplyRotation(const MT_Vector3& drot,bool local)
371 MT_Matrix3x3 rotmat(drot);
373 GetSGNode()->RelativeRotate(rotmat,local);
375 if (m_pPhysicsController1) { // (IsDynamic())
376 m_pPhysicsController1->RelativeRotate(rotmat,local);
383 GetOpenGL Matrix, returns an OpenGL 'compatible' matrix
385 double* KX_GameObject::GetOpenGLMatrix()
387 // todo: optimize and only update if necessary
388 double* fl = m_OpenGL_4x4Matrix.getPointer();
391 trans.setOrigin(GetSGNode()->GetWorldPosition());
392 trans.setBasis(GetSGNode()->GetWorldOrientation());
394 MT_Vector3 scaling = GetSGNode()->GetWorldScaling();
395 m_bIsNegativeScaling = ((scaling[0] < 0.0) ^ (scaling[1] < 0.0) ^ (scaling[2] < 0.0)) ? true : false;
396 trans.scale(scaling[0], scaling[1], scaling[2]);
402 void KX_GameObject::AddMeshUser()
404 for (size_t i=0;i<m_meshes.size();i++)
405 m_meshes[i]->AddMeshUser(this);
407 UpdateBuckets(false);
410 static void UpdateBuckets_recursive(SG_Node* node)
412 NodeList& children = node->GetSGChildren();
414 for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
416 SG_Node* childnode = (*childit);
417 KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
418 if (clientgameobj != NULL) // This is a GameObject
419 clientgameobj->UpdateBuckets(0);
421 // if the childobj is NULL then this may be an inverse parent link
422 // so a non recursive search should still look down this node.
423 UpdateBuckets_recursive(childnode);
427 void KX_GameObject::UpdateBuckets( bool recursive )
429 double* fl = GetOpenGLMatrix();
431 for (size_t i=0;i<m_meshes.size();i++)
432 m_meshes[i]->UpdateBuckets(this, fl, m_bUseObjectColor, m_objectColor, m_bVisible, m_bCulled);
435 UpdateBuckets_recursive(m_pSGNode);
439 void KX_GameObject::RemoveMeshes()
441 for (size_t i=0;i<m_meshes.size();i++)
442 m_meshes[i]->RemoveFromBuckets(this);
444 //note: meshes can be shared, and are deleted by KX_BlenderSceneConverter
449 void KX_GameObject::UpdateTransform()
451 if (m_pPhysicsController1)
452 // only update the transform of static object, dynamic object are handled differently
453 // note that for bullet, this does not even update the transform of static object
454 // but merely sets there collision flag to "kinematic" because the synchronization is
455 // done differently during physics simulation
456 m_pPhysicsController1->SetSumoTransform(true);
457 if (m_pGraphicController)
458 // update the culling tree
459 m_pGraphicController->SetGraphicTransform();
463 void KX_GameObject::UpdateTransformFunc(SG_IObject* node, void* gameobj, void* scene)
465 ((KX_GameObject*)gameobj)->UpdateTransform();
469 void KX_GameObject::SetDebugColor(unsigned int bgra)
471 for (size_t i=0;i<m_meshes.size();i++)
472 m_meshes[i]->DebugColor(bgra);
477 void KX_GameObject::ResetDebugColor()
479 SetDebugColor(0xff000000);
482 void KX_GameObject::InitIPO(bool ipo_as_force,
486 SGControllerList::iterator it = GetSGNode()->GetSGControllerList().begin();
488 while (it != GetSGNode()->GetSGControllerList().end()) {
489 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_RESET, true);
490 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_AS_FORCE, ipo_as_force);
491 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_ADD, ipo_add);
492 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_LOCAL, ipo_local);
497 void KX_GameObject::UpdateIPO(float curframetime,
500 // just the 'normal' update procedure.
501 GetSGNode()->SetSimulatedTime(curframetime,recurse);
502 GetSGNode()->UpdateWorldData(curframetime);
508 KX_GameObject::UpdateMaterialData(
521 if (((unsigned int)mesh < m_meshes.size()) && mesh >= 0) {
522 list<RAS_MeshMaterial>::iterator mit = m_meshes[mesh]->GetFirstMaterial();
524 for(; mit != m_meshes[mesh]->GetLastMaterial(); ++mit)
526 RAS_IPolyMaterial* poly = mit->m_bucket->GetPolyMaterial();
528 if(poly->GetFlag() & RAS_BLENDERMAT )
530 KX_BlenderMaterial *m = static_cast<KX_BlenderMaterial*>(poly);
532 if (matname_hash == 0)
534 m->UpdateIPO(rgba, specrgb,hard,spec,ref,emit, alpha);
535 // if mesh has only one material attached to it then use original hack with no need to edit vertices (better performance)
536 SetObjectColor(rgba);
540 if (matname_hash == poly->GetMaterialNameHash())
542 m->UpdateIPO(rgba, specrgb,hard,spec,ref,emit, alpha);
543 m_meshes[mesh]->SetVertexColor(poly,rgba);
545 // no break here, because one blender material can be split into several game engine materials
546 // (e.g. one uvsphere material is split into one material at poles with ras_mode TRIANGLE and one material for the body
547 // if here was a break then would miss some vertices if material was split
555 KX_GameObject::GetVisible(
562 static void setVisible_recursive(SG_Node* node, bool v)
564 NodeList& children = node->GetSGChildren();
566 for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
568 SG_Node* childnode = (*childit);
569 KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
570 if (clientgameobj != NULL) // This is a GameObject
571 clientgameobj->SetVisible(v, 0);
573 // if the childobj is NULL then this may be an inverse parent link
574 // so a non recursive search should still look down this node.
575 setVisible_recursive(childnode, v);
581 KX_GameObject::SetVisible(
588 setVisible_recursive(m_pSGNode, v);
592 KX_GameObject::GetCulled(
600 KX_GameObject::SetCulled(
609 KX_GameObject::SetLayer(
617 KX_GameObject::GetLayer(
624 void KX_GameObject::addLinearVelocity(const MT_Vector3& lin_vel,bool local)
626 if (m_pPhysicsController1)
628 MT_Vector3 lv = local ? NodeGetWorldOrientation() * lin_vel : lin_vel;
629 m_pPhysicsController1->SetLinearVelocity(lv + m_pPhysicsController1->GetLinearVelocity(), 0);
635 void KX_GameObject::setLinearVelocity(const MT_Vector3& lin_vel,bool local)
637 if (m_pPhysicsController1)
638 m_pPhysicsController1->SetLinearVelocity(lin_vel,local);
643 void KX_GameObject::setAngularVelocity(const MT_Vector3& ang_vel,bool local)
645 if (m_pPhysicsController1)
646 m_pPhysicsController1->SetAngularVelocity(ang_vel,local);
650 void KX_GameObject::ResolveCombinedVelocities(
651 const MT_Vector3 & lin_vel,
652 const MT_Vector3 & ang_vel,
656 if (m_pPhysicsController1)
659 MT_Vector3 lv = lin_vel_local ? NodeGetWorldOrientation() * lin_vel : lin_vel;
660 MT_Vector3 av = ang_vel_local ? NodeGetWorldOrientation() * ang_vel : ang_vel;
661 m_pPhysicsController1->resolveCombinedVelocities(
662 lv.x(),lv.y(),lv.z(),av.x(),av.y(),av.z());
667 void KX_GameObject::SetObjectColor(const MT_Vector4& rgbavec)
669 m_bUseObjectColor = true;
670 m_objectColor = rgbavec;
673 void KX_GameObject::AlignAxisToVect(const MT_Vector3& dir, int axis, float fac)
676 MT_Vector3 vect,ori,z,x,y;
679 // check on valid node in case a python controller holds a reference to a deleted object
685 if (MT_fuzzyZero(len))
687 cout << "alignAxisToVect() Error: Null vector!\n";
697 orimat = GetSGNode()->GetWorldOrientation();
701 ori.setValue(orimat[0][2], orimat[1][2], orimat[2][2]); //pivot axis
702 if (MT_abs(vect.dot(ori)) > 1.0-3.0*MT_EPSILON) //is the vector paralell to the pivot?
703 ori.setValue(orimat[0][1], orimat[1][1], orimat[2][1]); //change the pivot!
707 x = (vect * fac) + ((orimat * MT_Vector3(1.0, 0.0, 0.0)) * (1-fac));
709 if (MT_fuzzyZero(len)) x = vect;
716 ori.setValue(orimat[0][0], orimat[1][0], orimat[2][0]);
717 if (MT_abs(vect.dot(ori)) > 1.0-3.0*MT_EPSILON)
718 ori.setValue(orimat[0][2], orimat[1][2], orimat[2][2]);
722 y = (vect * fac) + ((orimat * MT_Vector3(0.0, 1.0, 0.0)) * (1-fac));
724 if (MT_fuzzyZero(len)) y = vect;
731 ori.setValue(orimat[0][1], orimat[1][1], orimat[2][1]);
732 if (MT_abs(vect.dot(ori)) > 1.0-3.0*MT_EPSILON)
733 ori.setValue(orimat[0][0], orimat[1][0], orimat[2][0]);
737 z = (vect * fac) + ((orimat * MT_Vector3(0.0, 0.0, 1.0)) * (1-fac));
739 if (MT_fuzzyZero(len)) z = vect;
745 default: //wrong input?
746 cout << "alignAxisToVect(): Wrong axis '" << axis <<"'\n";
749 x.normalize(); //normalize the vectors
752 orimat.setValue( x[0],y[0],z[0],
755 if (GetSGNode()->GetSGParent() != NULL)
757 // the object is a child, adapt its local orientation so that
758 // the global orientation is aligned as we want.
759 MT_Matrix3x3 invori = GetSGNode()->GetSGParent()->GetWorldOrientation().inverse();
760 NodeSetLocalOrientation(invori*orimat);
763 NodeSetLocalOrientation(orimat);
766 MT_Scalar KX_GameObject::GetMass()
768 if (m_pPhysicsController1)
770 return m_pPhysicsController1->GetMass();
775 MT_Vector3 KX_GameObject::GetLocalInertia()
777 MT_Vector3 local_inertia(0.0,0.0,0.0);
778 if (m_pPhysicsController1)
780 local_inertia = m_pPhysicsController1->GetLocalInertia();
782 return local_inertia;
785 MT_Vector3 KX_GameObject::GetLinearVelocity(bool local)
787 MT_Vector3 velocity(0.0,0.0,0.0), locvel;
789 if (m_pPhysicsController1)
791 velocity = m_pPhysicsController1->GetLinearVelocity();
795 ori = GetSGNode()->GetWorldOrientation();
797 locvel = velocity * ori;
804 MT_Vector3 KX_GameObject::GetAngularVelocity(bool local)
806 MT_Vector3 velocity(0.0,0.0,0.0), locvel;
808 if (m_pPhysicsController1)
810 velocity = m_pPhysicsController1->GetAngularVelocity();
814 ori = GetSGNode()->GetWorldOrientation();
816 locvel = velocity * ori;
823 MT_Vector3 KX_GameObject::GetVelocity(const MT_Point3& point)
825 if (m_pPhysicsController1)
827 return m_pPhysicsController1->GetVelocity(point);
829 return MT_Vector3(0.0,0.0,0.0);
832 // scenegraph node stuff
834 void KX_GameObject::NodeSetLocalPosition(const MT_Point3& trans)
836 // check on valid node in case a python controller holds a reference to a deleted object
840 if (m_pPhysicsController1 && !GetSGNode()->GetSGParent())
842 // don't update physic controller if the object is a child:
843 // 1) the transformation will not be right
844 // 2) in this case, the physic controller is necessarily a static object
845 // that is updated from the normal kinematic synchronization
846 m_pPhysicsController1->setPosition(trans);
849 GetSGNode()->SetLocalPosition(trans);
855 void KX_GameObject::NodeSetLocalOrientation(const MT_Matrix3x3& rot)
857 // check on valid node in case a python controller holds a reference to a deleted object
861 if (m_pPhysicsController1 && !GetSGNode()->GetSGParent())
864 m_pPhysicsController1->setOrientation(rot);
866 GetSGNode()->SetLocalOrientation(rot);
871 void KX_GameObject::NodeSetLocalScale(const MT_Vector3& scale)
873 // check on valid node in case a python controller holds a reference to a deleted object
877 if (m_pPhysicsController1 && !GetSGNode()->GetSGParent())
880 m_pPhysicsController1->setScaling(scale);
882 GetSGNode()->SetLocalScale(scale);
887 void KX_GameObject::NodeSetRelativeScale(const MT_Vector3& scale)
891 GetSGNode()->RelativeScale(scale);
892 if (m_pPhysicsController1 && (!GetSGNode()->GetSGParent()))
895 // we can use the local scale: it's the same thing for a root object
896 // and the world scale is not yet updated
897 MT_Vector3 newscale = GetSGNode()->GetLocalScale();
898 m_pPhysicsController1->setScaling(newscale);
903 void KX_GameObject::NodeSetWorldPosition(const MT_Point3& trans)
905 SG_Node* parent = m_pSGNode->GetSGParent();
908 // Make sure the objects have some scale
909 MT_Vector3 scale = parent->GetWorldScaling();
910 if (fabs(scale[0]) < FLT_EPSILON ||
911 fabs(scale[1]) < FLT_EPSILON ||
912 fabs(scale[2]) < FLT_EPSILON)
916 scale[0] = 1.0/scale[0];
917 scale[1] = 1.0/scale[1];
918 scale[2] = 1.0/scale[2];
919 MT_Matrix3x3 invori = parent->GetWorldOrientation().inverse();
920 MT_Vector3 newpos = invori*(trans-parent->GetWorldPosition())*scale;
921 NodeSetLocalPosition(MT_Point3(newpos[0],newpos[1],newpos[2]));
925 NodeSetLocalPosition(trans);
930 void KX_GameObject::NodeUpdateGS(double time)
933 GetSGNode()->UpdateWorldData(time);
938 const MT_Matrix3x3& KX_GameObject::NodeGetWorldOrientation() const
940 static MT_Matrix3x3 defaultOrientation = MT_Matrix3x3( 1.0, 0.0, 0.0,
944 // check on valid node in case a python controller holds a reference to a deleted object
946 return defaultOrientation;
947 return GetSGNode()->GetWorldOrientation();
952 const MT_Vector3& KX_GameObject::NodeGetWorldScaling() const
954 static MT_Vector3 defaultScaling = MT_Vector3(1.0, 1.0, 1.0);
956 // check on valid node in case a python controller holds a reference to a deleted object
958 return defaultScaling;
960 return GetSGNode()->GetWorldScaling();
965 const MT_Point3& KX_GameObject::NodeGetWorldPosition() const
967 // check on valid node in case a python controller holds a reference to a deleted object
969 return GetSGNode()->GetWorldPosition();
974 /* Suspend/ resume: for the dynamic behaviour, there is a simple
975 * method. For the residual motion, there is not. I wonder what the
976 * correct solution is for Sumo. Remove from the motion-update tree?
978 * So far, only switch the physics and logic.
981 void KX_GameObject::Resume(void)
984 SCA_IObject::Resume();
985 if(GetPhysicsController())
986 GetPhysicsController()->RestoreDynamics();
992 void KX_GameObject::Suspend()
994 if ((!m_ignore_activity_culling)
996 SCA_IObject::Suspend();
997 if(GetPhysicsController())
998 GetPhysicsController()->SuspendDynamics();
1006 /* ------- python stuff ---------------------------------------------------*/
1008 PyMethodDef KX_GameObject::Methods[] = {
1009 {"setWorldPosition", (PyCFunction) KX_GameObject::sPySetWorldPosition, METH_O},
1010 {"applyForce", (PyCFunction) KX_GameObject::sPyApplyForce, METH_VARARGS},
1011 {"applyTorque", (PyCFunction) KX_GameObject::sPyApplyTorque, METH_VARARGS},
1012 {"applyRotation", (PyCFunction) KX_GameObject::sPyApplyRotation, METH_VARARGS},
1013 {"applyMovement", (PyCFunction) KX_GameObject::sPyApplyMovement, METH_VARARGS},
1014 {"getLinearVelocity", (PyCFunction) KX_GameObject::sPyGetLinearVelocity, METH_VARARGS},
1015 {"setLinearVelocity", (PyCFunction) KX_GameObject::sPySetLinearVelocity, METH_VARARGS},
1016 {"getAngularVelocity", (PyCFunction) KX_GameObject::sPyGetAngularVelocity, METH_VARARGS},
1017 {"setAngularVelocity", (PyCFunction) KX_GameObject::sPySetAngularVelocity, METH_VARARGS},
1018 {"getVelocity", (PyCFunction) KX_GameObject::sPyGetVelocity, METH_VARARGS},
1019 {"getReactionForce", (PyCFunction) KX_GameObject::sPyGetReactionForce, METH_NOARGS},
1020 {"alignAxisToVect",(PyCFunction) KX_GameObject::sPyAlignAxisToVect, METH_VARARGS},
1021 {"getAxisVect",(PyCFunction) KX_GameObject::sPyGetAxisVect, METH_O},
1022 {"suspendDynamics", (PyCFunction)KX_GameObject::sPySuspendDynamics,METH_NOARGS},
1023 {"restoreDynamics", (PyCFunction)KX_GameObject::sPyRestoreDynamics,METH_NOARGS},
1024 {"enableRigidBody", (PyCFunction)KX_GameObject::sPyEnableRigidBody,METH_NOARGS},
1025 {"disableRigidBody", (PyCFunction)KX_GameObject::sPyDisableRigidBody,METH_NOARGS},
1026 {"applyImpulse", (PyCFunction) KX_GameObject::sPyApplyImpulse, METH_VARARGS},
1027 {"setCollisionMargin", (PyCFunction) KX_GameObject::sPySetCollisionMargin, METH_O},
1028 {"setParent", (PyCFunction)KX_GameObject::sPySetParent,METH_O},
1029 {"setVisible",(PyCFunction) KX_GameObject::sPySetVisible, METH_VARARGS},
1030 {"removeParent", (PyCFunction)KX_GameObject::sPyRemoveParent,METH_NOARGS},
1031 {"getChildren", (PyCFunction)KX_GameObject::sPyGetChildren,METH_NOARGS},
1032 {"getChildrenRecursive", (PyCFunction)KX_GameObject::sPyGetChildrenRecursive,METH_NOARGS},
1033 {"getPhysicsId", (PyCFunction)KX_GameObject::sPyGetPhysicsId,METH_NOARGS},
1034 {"getPropertyNames", (PyCFunction)KX_GameObject::sPyGetPropertyNames,METH_NOARGS},
1035 {"replaceMesh",(PyCFunction) KX_GameObject::sPyReplaceMesh, METH_O},
1036 {"endObject",(PyCFunction) KX_GameObject::sPyEndObject, METH_NOARGS},
1038 KX_PYMETHODTABLE(KX_GameObject, rayCastTo),
1039 KX_PYMETHODTABLE(KX_GameObject, rayCast),
1040 KX_PYMETHODTABLE_O(KX_GameObject, getDistanceTo),
1041 KX_PYMETHODTABLE_O(KX_GameObject, getVectTo),
1044 {"getPosition", (PyCFunction) KX_GameObject::sPyGetPosition, METH_NOARGS},
1045 {"setPosition", (PyCFunction) KX_GameObject::sPySetPosition, METH_O},
1046 {"getOrientation", (PyCFunction) KX_GameObject::sPyGetOrientation, METH_NOARGS},
1047 {"setOrientation", (PyCFunction) KX_GameObject::sPySetOrientation, METH_O},
1048 {"getState",(PyCFunction) KX_GameObject::sPyGetState, METH_NOARGS},
1049 {"setState",(PyCFunction) KX_GameObject::sPySetState, METH_O},
1050 {"getParent", (PyCFunction)KX_GameObject::sPyGetParent,METH_NOARGS},
1051 {"getVisible",(PyCFunction) KX_GameObject::sPyGetVisible, METH_NOARGS},
1052 {"getMass", (PyCFunction) KX_GameObject::sPyGetMass, METH_NOARGS},
1053 {"getMesh", (PyCFunction)KX_GameObject::sPyGetMesh,METH_VARARGS},
1054 {NULL,NULL} //Sentinel
1057 PyAttributeDef KX_GameObject::Attributes[] = {
1058 KX_PYATTRIBUTE_RO_FUNCTION("name", KX_GameObject, pyattr_get_name),
1059 KX_PYATTRIBUTE_RO_FUNCTION("parent", KX_GameObject, pyattr_get_parent),
1060 KX_PYATTRIBUTE_RW_FUNCTION("mass", KX_GameObject, pyattr_get_mass, pyattr_set_mass),
1061 KX_PYATTRIBUTE_RW_FUNCTION("visible", KX_GameObject, pyattr_get_visible, pyattr_set_visible),
1062 KX_PYATTRIBUTE_RW_FUNCTION("position", KX_GameObject, pyattr_get_position, pyattr_set_position),
1063 KX_PYATTRIBUTE_RO_FUNCTION("localInertia", KX_GameObject, pyattr_get_localInertia),
1064 KX_PYATTRIBUTE_RW_FUNCTION("orientation",KX_GameObject,pyattr_get_orientation,pyattr_set_orientation),
1065 KX_PYATTRIBUTE_RW_FUNCTION("scaling", KX_GameObject, pyattr_get_scaling, pyattr_set_scaling),
1066 KX_PYATTRIBUTE_RW_FUNCTION("timeOffset",KX_GameObject, pyattr_get_timeOffset,pyattr_set_timeOffset),
1067 KX_PYATTRIBUTE_RW_FUNCTION("state", KX_GameObject, pyattr_get_state, pyattr_set_state),
1068 KX_PYATTRIBUTE_RO_FUNCTION("meshes", KX_GameObject, pyattr_get_meshes),
1070 KX_PYATTRIBUTE_RO_FUNCTION("__dict__", KX_GameObject, pyattr_get_dir_dict),
1072 /* Experemental, dont rely on these yet */
1073 KX_PYATTRIBUTE_RO_FUNCTION("sensors", KX_GameObject, pyattr_get_sensors),
1074 KX_PYATTRIBUTE_RO_FUNCTION("controllers", KX_GameObject, pyattr_get_controllers),
1075 KX_PYATTRIBUTE_RO_FUNCTION("actuators", KX_GameObject, pyattr_get_actuators),
1082 bool KX_GameObject::ConvertPythonVectorArgs(PyObject* args,
1088 bool error = (PyArg_ParseTuple(args,"OO",&pylist,&pylist2)) != 0;
1090 pos = ConvertPythonPylist(pylist);
1091 pos2 = ConvertPythonPylist(pylist2);
1097 PyObject* KX_GameObject::PyReplaceMesh(PyObject* self, PyObject* value)
1099 KX_Scene *scene = KX_GetActiveScene();
1103 meshname = PyString_AsString(value);
1104 if (meshname==NULL) {
1105 PyErr_SetString(PyExc_ValueError, "Expected a mesh name");
1108 mesh_pt = SCA_ILogicBrick::m_sCurrentLogicManager->GetMeshByName(STR_String(meshname));
1110 if (mesh_pt==NULL) {
1111 PyErr_SetString(PyExc_ValueError, "The mesh name given does not exist");
1114 scene->ReplaceMesh(this, (class RAS_MeshObject*)mesh_pt);
1119 PyObject* KX_GameObject::PyEndObject(PyObject* self)
1122 KX_Scene *scene = KX_GetActiveScene();
1123 scene->DelayedRemoveObject(this);
1130 PyObject* KX_GameObject::PyGetPosition(PyObject* self)
1132 ShowDeprecationWarning("getPosition()", "the position property");
1133 return PyObjectFrom(NodeGetWorldPosition());
1137 Py_ssize_t KX_GameObject::Map_Len(PyObject* self_v)
1139 return (static_cast<KX_GameObject*>(self_v))->GetPropertyCount();
1143 PyObject *KX_GameObject::Map_GetItem(PyObject *self_v, PyObject *item)
1145 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1146 const char *attr= PyString_AsString(item);
1148 PyObject* pyconvert;
1152 PyErr_SetString(PyExc_TypeError, "KX_GameObject key but a string");
1156 resultattr = self->GetProperty(attr);
1158 if(resultattr==NULL) {
1159 PyErr_SetString(PyExc_KeyError, "KX_GameObject key does not exist");
1163 pyconvert = resultattr->ConvertValueToPython();
1165 return pyconvert ? pyconvert:resultattr;
1169 int KX_GameObject::Map_SetItem(PyObject *self_v, PyObject *key, PyObject *val)
1171 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1172 const char *attr= PyString_AsString(key);
1175 PyErr_SetString(PyExc_TypeError, "KX_GameObject key but a string");
1179 if (val==NULL) { /* del ob["key"] */
1180 if (self->RemoveProperty(attr)==false) {
1181 PyErr_Format(PyExc_KeyError, "KX_GameObject key \"%s\" not found", attr);
1185 else { /* ob["key"] = value */
1186 CValue* vallie = self->ConvertPythonToValue(val);
1189 return 1; /* ConvertPythonToValue sets the error */
1191 CValue* oldprop = self->GetProperty(attr);
1194 oldprop->SetValue(vallie);
1196 self->SetProperty(attr, vallie);
1205 PyMappingMethods KX_GameObject::Mapping = {
1206 (lenfunc)KX_GameObject::Map_Len, /*inquiry mp_length */
1207 (binaryfunc)KX_GameObject::Map_GetItem, /*binaryfunc mp_subscript */
1208 (objobjargproc)KX_GameObject::Map_SetItem, /*objobjargproc mp_ass_subscript */
1212 PyTypeObject KX_GameObject::Type = {
1213 PyObject_HEAD_INIT(NULL)
1216 sizeof(KX_GameObject),
1236 PyParentObject KX_GameObject::Parents[] = {
1237 &KX_GameObject::Type,
1243 PyObject* KX_GameObject::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1245 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1246 return PyString_FromString(self->GetName().ReadPtr());
1249 PyObject* KX_GameObject::pyattr_get_parent(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1251 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1252 KX_GameObject* parent = self->GetParent();
1254 return parent->AddRef();
1258 PyObject* KX_GameObject::pyattr_get_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1260 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1261 KX_IPhysicsController *spc = self->GetPhysicsController();
1262 return PyFloat_FromDouble(spc ? spc->GetMass() : 0.0f);
1265 int KX_GameObject::pyattr_set_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1267 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1268 KX_IPhysicsController *spc = self->GetPhysicsController();
1269 MT_Scalar val = PyFloat_AsDouble(value);
1270 if (val < 0.0f) { /* also accounts for non float */
1271 PyErr_SetString(PyExc_AttributeError, "expected a float zero or above");
1281 PyObject* KX_GameObject::pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1283 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1284 return PyBool_FromLong(self->GetVisible());
1287 int KX_GameObject::pyattr_set_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1289 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1290 int param = PyObject_IsTrue( value );
1292 PyErr_SetString(PyExc_AttributeError, "expected True or False");
1296 self->SetVisible(param, false);
1297 self->UpdateBuckets(false);
1301 PyObject* KX_GameObject::pyattr_get_position(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1303 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1304 return PyObjectFrom(self->NodeGetWorldPosition());
1307 int KX_GameObject::pyattr_set_position(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1309 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1311 if (!PyVecTo(value, pos))
1314 self->NodeSetLocalPosition(pos);
1315 self->NodeUpdateGS(0.f);
1319 PyObject* KX_GameObject::pyattr_get_localInertia(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1321 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1322 if (self->GetPhysicsController())
1324 return PyObjectFrom(self->GetPhysicsController()->GetLocalInertia());
1329 PyObject* KX_GameObject::pyattr_get_orientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1331 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1332 return PyObjectFrom(self->NodeGetWorldOrientation());
1335 int KX_GameObject::pyattr_set_orientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1337 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1338 if (!PySequence_Check(value)) {
1339 PyErr_SetString(PyExc_AttributeError, "'orientation' attribute needs to be a sequence");
1345 if (PyMatTo(value, rot))
1347 self->NodeSetLocalOrientation(rot);
1348 self->NodeUpdateGS(0.f);
1353 if (PySequence_Size(value) == 4)
1356 if (PyVecTo(value, qrot))
1358 rot.setRotation(qrot);
1359 self->NodeSetLocalOrientation(rot);
1360 self->NodeUpdateGS(0.f);
1366 if (PySequence_Size(value) == 3)
1369 if (PyVecTo(value, erot))
1372 self->NodeSetLocalOrientation(rot);
1373 self->NodeUpdateGS(0.f);
1379 PyErr_SetString(PyExc_AttributeError, "could not set the orientation from a 3x3 matrix, quaternion or euler sequence");
1383 PyObject* KX_GameObject::pyattr_get_scaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1385 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1386 return PyObjectFrom(self->NodeGetWorldScaling());
1389 int KX_GameObject::pyattr_set_scaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1391 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1393 if (!PyVecTo(value, scale))
1396 self->NodeSetLocalScale(scale);
1397 self->NodeUpdateGS(0.f);
1401 PyObject* KX_GameObject::pyattr_get_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1403 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1404 SG_Node* sg_parent= self->GetSGNode()->GetSGParent();
1405 if (sg_parent && sg_parent->IsSlowParent()) {
1406 return PyFloat_FromDouble(static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->GetTimeOffset());
1408 return PyFloat_FromDouble(0.0);
1412 int KX_GameObject::pyattr_set_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1414 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1415 MT_Scalar val = PyFloat_AsDouble(value);
1416 SG_Node* sg_parent= self->GetSGNode()->GetSGParent();
1417 if (val < 0.0f) { /* also accounts for non float */
1418 PyErr_SetString(PyExc_AttributeError, "expected a float zero or above");
1422 if (sg_parent && sg_parent->IsSlowParent())
1423 static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->SetTimeOffset(val);
1428 PyObject* KX_GameObject::pyattr_get_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1430 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1432 state |= self->GetState();
1433 return PyInt_FromLong(state);
1436 int KX_GameObject::pyattr_set_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1438 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1439 int state_i = PyInt_AsLong(value);
1440 unsigned int state = 0;
1442 if (state_i == -1 && PyErr_Occurred()) {
1443 PyErr_SetString(PyExc_TypeError, "expected an int bit field");
1448 if ((state & ((1<<30)-1)) == 0) {
1449 PyErr_SetString(PyExc_AttributeError, "The state bitfield was not between 0 and 30 (1<<0 and 1<<29)");
1452 self->SetState(state);
1456 PyObject* KX_GameObject::pyattr_get_meshes(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1458 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1459 PyObject *meshes= PyList_New(self->m_meshes.size());
1462 for(i=0; i < self->m_meshes.size(); i++)
1464 KX_MeshProxy* meshproxy = new KX_MeshProxy(self->m_meshes[i]);
1465 PyList_SET_ITEM(meshes, i, meshproxy);
1473 PyObject* KX_GameObject::pyattr_get_sensors(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1475 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1476 SCA_SensorList& sensors= self->GetSensors();
1477 PyObject* resultlist = PyList_New(sensors.size());
1479 for (unsigned int index=0;index<sensors.size();index++)
1480 PyList_SET_ITEM(resultlist, index, sensors[index]->AddRef());
1485 PyObject* KX_GameObject::pyattr_get_controllers(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1487 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1488 SCA_ControllerList& controllers= self->GetControllers();
1489 PyObject* resultlist = PyList_New(controllers.size());
1491 for (unsigned int index=0;index<controllers.size();index++)
1492 PyList_SET_ITEM(resultlist, index, controllers[index]->AddRef());
1497 PyObject* KX_GameObject::pyattr_get_actuators(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1499 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1500 SCA_ActuatorList& actuators= self->GetActuators();
1501 PyObject* resultlist = PyList_New(actuators.size());
1503 for (unsigned int index=0;index<actuators.size();index++)
1504 PyList_SET_ITEM(resultlist, index, actuators[index]->AddRef());
1510 /* __dict__ only for the purpose of giving useful dir() results */
1511 PyObject* KX_GameObject::pyattr_get_dir_dict(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1513 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1514 PyObject *dict_str = PyString_FromString("__dict__");
1515 PyObject *dict= py_getattr_dict(self->SCA_IObject::py_getattro(dict_str), Type.tp_dict);
1516 Py_DECREF(dict_str);
1521 /* Not super fast getting as a list then making into dict keys but its only for dir() */
1522 PyObject *list= self->ConvertKeysToPython();
1526 for(i=0; i<PyList_Size(list); i++)
1527 PyDict_SetItem(dict, PyList_GET_ITEM(list, i), Py_None);
1538 PyObject* KX_GameObject::py_getattro(PyObject *attr)
1540 py_getattro_up(SCA_IObject);
1543 int KX_GameObject::py_setattro(PyObject *attr, PyObject *value) // py_setattro method
1545 py_setattro_up(SCA_IObject);
1548 PyObject* KX_GameObject::PyApplyForce(PyObject* self, PyObject* args)
1553 if (PyArg_ParseTuple(args, "O|i:applyForce", &pyvect, &local)) {
1555 if (PyVecTo(pyvect, force)) {
1556 ApplyForce(force, (local!=0));
1563 PyObject* KX_GameObject::PyApplyTorque(PyObject* self, PyObject* args)
1568 if (PyArg_ParseTuple(args, "O|i:applyTorque", &pyvect, &local)) {
1570 if (PyVecTo(pyvect, torque)) {
1571 ApplyTorque(torque, (local!=0));
1578 PyObject* KX_GameObject::PyApplyRotation(PyObject* self, PyObject* args)
1583 if (PyArg_ParseTuple(args, "O|i:applyRotation", &pyvect, &local)) {
1584 MT_Vector3 rotation;
1585 if (PyVecTo(pyvect, rotation)) {
1586 ApplyRotation(rotation, (local!=0));
1593 PyObject* KX_GameObject::PyApplyMovement(PyObject* self, PyObject* args)
1598 if (PyArg_ParseTuple(args, "O|i:applyMovement", &pyvect, &local)) {
1599 MT_Vector3 movement;
1600 if (PyVecTo(pyvect, movement)) {
1601 ApplyMovement(movement, (local!=0));
1608 PyObject* KX_GameObject::PyGetLinearVelocity(PyObject* self, PyObject* args)
1610 // only can get the velocity if we have a physics object connected to us...
1612 if (PyArg_ParseTuple(args,"|i:getLinearVelocity",&local))
1614 return PyObjectFrom(GetLinearVelocity((local!=0)));
1622 PyObject* KX_GameObject::PySetLinearVelocity(PyObject* self, PyObject* args)
1627 if (PyArg_ParseTuple(args,"O|i:setLinearVelocity",&pyvect,&local)) {
1628 MT_Vector3 velocity;
1629 if (PyVecTo(pyvect, velocity)) {
1630 setLinearVelocity(velocity, (local!=0));
1637 PyObject* KX_GameObject::PyGetAngularVelocity(PyObject* self, PyObject* args)
1639 // only can get the velocity if we have a physics object connected to us...
1641 if (PyArg_ParseTuple(args,"|i:getAngularVelocity",&local))
1643 return PyObjectFrom(GetAngularVelocity((local!=0)));
1651 PyObject* KX_GameObject::PySetAngularVelocity(PyObject* self, PyObject* args)
1656 if (PyArg_ParseTuple(args,"O|i:setAngularVelocity",&pyvect,&local)) {
1657 MT_Vector3 velocity;
1658 if (PyVecTo(pyvect, velocity)) {
1659 setAngularVelocity(velocity, (local!=0));
1666 PyObject* KX_GameObject::PySetVisible(PyObject* self, PyObject* args)
1668 int visible, recursive = 0;
1669 if (!PyArg_ParseTuple(args,"i|i:setVisible",&visible, &recursive))
1672 SetVisible(visible ? true:false, recursive ? true:false);
1673 UpdateBuckets(recursive ? true:false);
1678 PyObject* KX_GameObject::PyGetVisible(PyObject* self)
1680 ShowDeprecationWarning("getVisible()", "the visible property");
1681 return PyInt_FromLong(m_bVisible);
1684 PyObject* KX_GameObject::PyGetState(PyObject* self)
1686 ShowDeprecationWarning("getState()", "the state property");
1688 state |= GetState();
1689 return PyInt_FromLong(state);
1692 PyObject* KX_GameObject::PySetState(PyObject* self, PyObject* value)
1694 ShowDeprecationWarning("setState()", "the state property");
1695 int state_i = PyInt_AsLong(value);
1696 unsigned int state = 0;
1698 if (state_i == -1 && PyErr_Occurred()) {
1699 PyErr_SetString(PyExc_TypeError, "expected an int bit field");
1704 if ((state & ((1<<30)-1)) == 0) {
1705 PyErr_SetString(PyExc_AttributeError, "The state bitfield was not between 0 and 30 (1<<0 and 1<<29)");
1713 PyObject* KX_GameObject::PyGetVelocity(PyObject* self, PyObject* args)
1715 // only can get the velocity if we have a physics object connected to us...
1716 MT_Point3 point(0.0,0.0,0.0);
1717 PyObject* pypos = NULL;
1719 if (PyArg_ParseTuple(args, "|O:getVelocity", &pypos))
1722 PyVecTo(pypos, point);
1728 if (m_pPhysicsController1)
1730 return PyObjectFrom(m_pPhysicsController1->GetVelocity(point));
1733 return PyObjectFrom(MT_Vector3(0.0,0.0,0.0));
1739 PyObject* KX_GameObject::PyGetMass(PyObject* self)
1741 ShowDeprecationWarning("getMass()", "the mass property");
1742 return PyFloat_FromDouble((GetPhysicsController() != NULL) ? GetPhysicsController()->GetMass() : 0.0f);
1745 PyObject* KX_GameObject::PyGetReactionForce(PyObject* self)
1747 // only can get the velocity if we have a physics object connected to us...
1749 // XXX - Currently not working with bullet intergration, see KX_BulletPhysicsController.cpp's getReactionForce
1751 if (GetPhysicsController())
1752 return PyObjectFrom(GetPhysicsController()->getReactionForce());
1753 return PyObjectFrom(dummy_point);
1756 return Py_BuildValue("fff", 0.0f, 0.0f, 0.0f);
1762 PyObject* KX_GameObject::PyEnableRigidBody(PyObject* self)
1764 if(GetPhysicsController())
1765 GetPhysicsController()->setRigidBody(true);
1772 PyObject* KX_GameObject::PyDisableRigidBody(PyObject* self)
1774 if(GetPhysicsController())
1775 GetPhysicsController()->setRigidBody(false);
1782 PyObject* KX_GameObject::PyGetParent(PyObject* self)
1784 ShowDeprecationWarning("getParent()", "the parent property");
1785 KX_GameObject* parent = this->GetParent();
1787 return parent->AddRef();
1791 PyObject* KX_GameObject::PySetParent(PyObject* self, PyObject* value)
1793 if (!PyObject_TypeCheck(value, &KX_GameObject::Type)) {
1794 PyErr_SetString(PyExc_TypeError, "expected a KX_GameObject type");
1798 PyErr_SetString(PyExc_ValueError, "cannot set the object to be its own parent!");
1802 // The object we want to set as parent
1803 CValue *m_ob = (CValue*)value;
1804 KX_GameObject *obj = ((KX_GameObject*)m_ob);
1805 KX_Scene *scene = KX_GetActiveScene();
1807 this->SetParent(scene, obj);
1812 PyObject* KX_GameObject::PyRemoveParent(PyObject* self)
1814 KX_Scene *scene = KX_GetActiveScene();
1815 this->RemoveParent(scene);
1820 static void walk_children(SG_Node* node, CListValue* list, bool recursive)
1822 NodeList& children = node->GetSGChildren();
1824 for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
1826 SG_Node* childnode = (*childit);
1827 CValue* childobj = (CValue*)childnode->GetSGClientObject();
1828 if (childobj != NULL) // This is a GameObject
1831 list->Add(childobj->AddRef());
1834 // if the childobj is NULL then this may be an inverse parent link
1835 // so a non recursive search should still look down this node.
1836 if (recursive || childobj==NULL) {
1837 walk_children(childnode, list, recursive);
1842 PyObject* KX_GameObject::PyGetChildren(PyObject* self)
1844 CListValue* list = new CListValue();
1845 walk_children(m_pSGNode, list, 0);
1849 PyObject* KX_GameObject::PyGetChildrenRecursive(PyObject* self)
1851 CListValue* list = new CListValue();
1852 walk_children(m_pSGNode, list, 1);
1856 PyObject* KX_GameObject::PyGetMesh(PyObject* self, PyObject* args)
1858 ShowDeprecationWarning("getMesh()", "the meshes property");
1862 if (!PyArg_ParseTuple(args, "|i:getMesh", &mesh))
1863 return NULL; // python sets a simple error
1865 if (((unsigned int)mesh < m_meshes.size()) && mesh >= 0)
1867 KX_MeshProxy* meshproxy = new KX_MeshProxy(m_meshes[mesh]);
1878 PyObject* KX_GameObject::PySetCollisionMargin(PyObject* self, PyObject* value)
1880 float collisionMargin = PyFloat_AsDouble(value);
1882 if (collisionMargin==-1 && PyErr_Occurred()) {
1883 PyErr_SetString(PyExc_TypeError, "expected a float");
1887 if (m_pPhysicsController1)
1889 m_pPhysicsController1->setMargin(collisionMargin);
1892 PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller");
1898 PyObject* KX_GameObject::PyApplyImpulse(PyObject* self, PyObject* args)
1901 PyObject* pyimpulse;
1903 if (!m_pPhysicsController1) {
1904 PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller");
1908 if (PyArg_ParseTuple(args, "OO:applyImpulse", &pyattach, &pyimpulse))
1912 if (PyVecTo(pyattach, attach) && PyVecTo(pyimpulse, impulse))
1914 m_pPhysicsController1->applyImpulse(attach, impulse);
1925 PyObject* KX_GameObject::PySuspendDynamics(PyObject* self)
1933 PyObject* KX_GameObject::PyRestoreDynamics(PyObject* self)
1941 PyObject* KX_GameObject::PyGetOrientation(PyObject* self) //keywords
1943 ShowDeprecationWarning("getOrientation()", "the orientation property");
1944 return PyObjectFrom(NodeGetWorldOrientation());
1949 PyObject* KX_GameObject::PySetOrientation(PyObject* self, PyObject* value)
1951 ShowDeprecationWarning("setOrientation()", "the orientation property");
1952 MT_Matrix3x3 matrix;
1953 if (PyObject_IsMT_Matrix(value, 3) && PyMatTo(value, matrix))
1955 NodeSetLocalOrientation(matrix);
1961 if (PyVecTo(value, quat))
1963 matrix.setRotation(quat);
1964 NodeSetLocalOrientation(matrix);
1971 PyObject* KX_GameObject::PyAlignAxisToVect(PyObject* self, PyObject* args)
1974 int axis = 2; //z axis is the default
1977 if (PyArg_ParseTuple(args,"O|if:alignAxisToVect",&pyvect,&axis, &fac))
1980 if (PyVecTo(pyvect, vect))
1982 if (fac<=0.0) Py_RETURN_NONE; // Nothing to do.
1983 if (fac> 1.0) fac= 1.0;
1985 AlignAxisToVect(vect,axis,fac);
1993 PyObject* KX_GameObject::PyGetAxisVect(PyObject* self, PyObject* value)
1996 if (PyVecTo(value, vect))
1998 return PyObjectFrom(NodeGetWorldOrientation() * vect);
2003 PyObject* KX_GameObject::PySetPosition(PyObject* self, PyObject* value)
2005 ShowDeprecationWarning("setPosition()", "the position property");
2007 if (PyVecTo(value, pos))
2009 NodeSetLocalPosition(pos);
2017 PyObject* KX_GameObject::PySetWorldPosition(PyObject* self, PyObject* value)
2020 if (PyVecTo(value, pos))
2022 NodeSetWorldPosition(pos);
2030 PyObject* KX_GameObject::PyGetPhysicsId(PyObject* self)
2032 KX_IPhysicsController* ctrl = GetPhysicsController();
2036 physid= (uint_ptr)ctrl->GetUserData();
2038 return PyInt_FromLong((long)physid);
2041 PyObject* KX_GameObject::PyGetPropertyNames(PyObject* self)
2043 return ConvertKeysToPython();
2046 KX_PYMETHODDEF_DOC_O(KX_GameObject, getDistanceTo,
2047 "getDistanceTo(other): get distance to another point/KX_GameObject")
2050 if (PyVecTo(value, b))
2052 return PyFloat_FromDouble(NodeGetWorldPosition().distance(b));
2056 KX_GameObject *other;
2057 if (ConvertPythonToGameObject(value, &other, false))
2059 return PyFloat_FromDouble(NodeGetWorldPosition().distance(other->NodeGetWorldPosition()));
2065 KX_PYMETHODDEF_DOC_O(KX_GameObject, getVectTo,
2066 "getVectTo(other): get vector and the distance to another point/KX_GameObject\n"
2067 "Returns a 3-tuple with (distance,worldVector,localVector)\n")
2069 MT_Point3 toPoint, fromPoint;
2070 MT_Vector3 toDir, locToDir;
2073 PyObject *returnValue;
2075 if (!PyVecTo(value, toPoint))
2079 KX_GameObject *other;
2080 if (ConvertPythonToGameObject(value, &other, false))
2082 toPoint = other->NodeGetWorldPosition();
2085 PyErr_SetString(PyExc_TypeError, "Expected a 3D Vector or GameObject type");
2090 fromPoint = NodeGetWorldPosition();
2091 toDir = toPoint-fromPoint;
2092 distance = toDir.length();
2094 if (MT_fuzzyZero(distance))
2096 //cout << "getVectTo() Error: Null vector!\n";
2097 locToDir = toDir = MT_Vector3(0.0,0.0,0.0);
2101 locToDir = toDir * NodeGetWorldOrientation();
2104 returnValue = PyTuple_New(3);
2105 if (returnValue) { // very unlikely to fail, python sets a memory error here.
2106 PyTuple_SET_ITEM(returnValue, 0, PyFloat_FromDouble(distance));
2107 PyTuple_SET_ITEM(returnValue, 1, PyObjectFrom(toDir));
2108 PyTuple_SET_ITEM(returnValue, 2, PyObjectFrom(locToDir));
2113 bool KX_GameObject::RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data)
2115 KX_GameObject* hitKXObj = client->m_gameobject;
2117 // if X-ray option is selected, the unwnted objects were not tested, so get here only with true hit
2118 // if not, all objects were tested and the front one may not be the correct one.
2119 if (m_xray || m_testPropName.Length() == 0 || hitKXObj->GetProperty(m_testPropName) != NULL)
2121 m_pHitObject = hitKXObj;
2124 // return true to stop RayCast::RayTest from looping, the above test was decisive
2125 // We would want to loop only if we want to get more than one hit point
2129 /* this function is used to pre-filter the object before casting the ray on them.
2130 This is useful for "X-Ray" option when we want to see "through" unwanted object.
2132 bool KX_GameObject::NeedRayCast(KX_ClientObjectInfo* client)
2134 KX_GameObject* hitKXObj = client->m_gameobject;
2136 if (client->m_type > KX_ClientObjectInfo::ACTOR)
2138 // Unknown type of object, skip it.
2139 // Should not occur as the sensor objects are filtered in RayTest()
2140 printf("Invalid client type %d found in ray casting\n", client->m_type);
2144 // if X-Ray option is selected, skip object that don't match the criteria as we see through them
2145 // if not, test all objects because we don't know yet which one will be on front
2146 if (!m_xray || m_testPropName.Length() == 0 || hitKXObj->GetProperty(m_testPropName) != NULL)
2154 KX_PYMETHODDEF_DOC(KX_GameObject, rayCastTo,
2155 "rayCastTo(other,dist,prop): look towards another point/KX_GameObject and return first object hit within dist that matches prop\n"
2156 " prop = property name that object must have; can be omitted => detect any object\n"
2157 " dist = max distance to look (can be negative => look behind); 0 or omitted => detect up to other\n"
2158 " other = 3-tuple or object reference")
2163 char *propName = NULL;
2165 if (!PyArg_ParseTuple(args,"O|fs:rayCastTo", &pyarg, &dist, &propName)) {
2166 return NULL; // python sets simple error
2169 if (!PyVecTo(pyarg, toPoint))
2171 KX_GameObject *other;
2174 if (ConvertPythonToGameObject(pyarg, &other, false))
2176 toPoint = other->NodeGetWorldPosition();
2179 PyErr_SetString(PyExc_TypeError, "the first argument to rayCastTo must be a vector or a KX_GameObject");
2183 MT_Point3 fromPoint = NodeGetWorldPosition();
2186 MT_Vector3 toDir = toPoint-fromPoint;
2188 toPoint = fromPoint + (dist) * toDir;
2191 PHY_IPhysicsEnvironment* pe = GetPhysicsEnvironment();
2192 KX_IPhysicsController *spc = GetPhysicsController();
2193 KX_GameObject *parent = GetParent();
2195 spc = parent->GetPhysicsController();
2199 m_pHitObject = NULL;
2201 m_testPropName = propName;
2203 m_testPropName.SetLength(0);
2204 KX_RayCast::Callback<KX_GameObject> callback(this,spc);
2205 KX_RayCast::RayTest(pe, fromPoint, toPoint, callback);
2208 return m_pHitObject->AddRef();
2213 KX_PYMETHODDEF_DOC(KX_GameObject, rayCast,
2214 "rayCast(to,from,dist,prop,face,xray,poly): cast a ray and return 3-tuple (object,hit,normal) or 4-tuple (object,hit,normal,polygon) of contact point with object within dist that matches prop.\n"
2215 " If no hit, return (None,None,None) or (None,None,None,None).\n"
2216 " to = 3-tuple or object reference for destination of ray (if object, use center of object)\n"
2217 " from = 3-tuple or object reference for origin of ray (if object, use center of object)\n"
2218 " Can be None or omitted => start from self object center\n"
2219 " dist = max distance to look (can be negative => look behind); 0 or omitted => detect up to to\n"
2220 " prop = property name that object must have; can be omitted => detect any object\n"
2221 " face = normal option: 1=>return face normal; 0 or omitted => normal is oriented towards origin\n"
2222 " xray = X-ray option: 1=>skip objects that don't match prop; 0 or omitted => stop on first object\n"
2223 " poly = polygon option: 1=>return value is a 4-tuple and the 4th element is a KX_PolyProxy object\n"
2224 " which can be None if hit object has no mesh or if there is no hit\n"
2225 " If 0 or omitted, return value is a 3-tuple\n"
2226 "Note: The object on which you call this method matters: the ray will ignore it.\n"
2227 " prop and xray option interact as follow:\n"
2228 " prop off, xray off: return closest hit or no hit if there is no object on the full extend of the ray\n"
2229 " prop off, xray on : idem\n"
2230 " prop on, xray off: return closest hit if it matches prop, no hit otherwise\n"
2231 " 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")
2234 MT_Point3 fromPoint;
2236 PyObject* pyfrom = NULL;
2238 char *propName = NULL;
2239 KX_GameObject *other;
2240 int face=0, xray=0, poly=0;
2242 if (!PyArg_ParseTuple(args,"O|Ofsiii:rayCast", &pyto, &pyfrom, &dist, &propName, &face, &xray, &poly)) {
2243 return NULL; // Python sets a simple error
2246 if (!PyVecTo(pyto, toPoint))
2250 if (ConvertPythonToGameObject(pyto, &other, false))
2252 toPoint = other->NodeGetWorldPosition();
2255 PyErr_SetString(PyExc_TypeError, "the first argument to rayCast must be a vector or a KX_GameObject");
2259 if (!pyfrom || pyfrom == Py_None)
2261 fromPoint = NodeGetWorldPosition();
2263 else if (!PyVecTo(pyfrom, fromPoint))
2267 if (ConvertPythonToGameObject(pyfrom, &other, false))
2269 fromPoint = other->NodeGetWorldPosition();
2272 PyErr_SetString(PyExc_TypeError, "the second optional argument to rayCast must be a vector or a KX_GameObject");
2278 MT_Vector3 toDir = toPoint-fromPoint;
2279 if (MT_fuzzyZero(toDir.length2())) {
2280 return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
2283 toPoint = fromPoint + (dist) * toDir;
2284 } else if (MT_fuzzyZero((toPoint-fromPoint).length2())) {
2285 return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
2288 PHY_IPhysicsEnvironment* pe = GetPhysicsEnvironment();
2289 KX_IPhysicsController *spc = GetPhysicsController();
2290 KX_GameObject *parent = GetParent();
2292 spc = parent->GetPhysicsController();
2296 m_pHitObject = NULL;
2298 m_testPropName = propName;
2300 m_testPropName.SetLength(0);
2302 // to get the hit results
2303 KX_RayCast::Callback<KX_GameObject> callback(this,spc,NULL,face);
2304 KX_RayCast::RayTest(pe, fromPoint, toPoint, callback);
2308 PyObject* returnValue = (poly) ? PyTuple_New(4) : PyTuple_New(3);
2309 if (returnValue) { // unlikely this would ever fail, if it does python sets an error
2310 PyTuple_SET_ITEM(returnValue, 0, m_pHitObject->AddRef());
2311 PyTuple_SET_ITEM(returnValue, 1, PyObjectFrom(callback.m_hitPoint));
2312 PyTuple_SET_ITEM(returnValue, 2, PyObjectFrom(callback.m_hitNormal));
2315 if (callback.m_hitMesh)
2317 // if this field is set, then we can trust that m_hitPolygon is a valid polygon
2318 RAS_Polygon* polygon = callback.m_hitMesh->GetPolygon(callback.m_hitPolygon);
2319 KX_PolyProxy* polyproxy = new KX_PolyProxy(callback.m_hitMesh, polygon);
2320 PyTuple_SET_ITEM(returnValue, 3, polyproxy);
2325 PyTuple_SET_ITEM(returnValue, 3, Py_None);
2333 return Py_BuildValue("OOOO", Py_None, Py_None, Py_None, Py_None);
2335 return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
2338 /* ---------------------------------------------------------------------
2339 * Some stuff taken from the header
2340 * --------------------------------------------------------------------- */
2341 void KX_GameObject::Relink(GEN_Map<GEN_HashedPtr, void*> *map_parameter)
2343 // we will relink the sensors and actuators that use object references
2344 // if the object is part of the replicated hierarchy, use the new
2345 // object reference instead
2346 SCA_SensorList& sensorlist = GetSensors();
2347 SCA_SensorList::iterator sit;
2348 for (sit=sensorlist.begin(); sit != sensorlist.end(); sit++)
2350 (*sit)->Relink(map_parameter);
2352 SCA_ActuatorList& actuatorlist = GetActuators();
2353 SCA_ActuatorList::iterator ait;
2354 for (ait=actuatorlist.begin(); ait != actuatorlist.end(); ait++)
2356 (*ait)->Relink(map_parameter);
2360 bool ConvertPythonToGameObject(PyObject * value, KX_GameObject **object, bool py_none_ok)
2363 PyErr_SetString(PyExc_TypeError, "Error in ConvertPythonToGameObject, python pointer NULL, should never happen");
2368 if (value==Py_None) {
2374 PyErr_SetString(PyExc_TypeError, "Expected KX_GameObject or a string for a name of a KX_GameObject, None is invalid");
2379 if (PyString_Check(value)) {
2380 *object = (KX_GameObject *)SCA_ILogicBrick::m_sCurrentLogicManager->GetGameObjectByName(STR_String( PyString_AsString(value) ));
2385 PyErr_SetString(PyExc_ValueError, "Requested name did not match any KX_GameObject");
2390 if (PyObject_TypeCheck(value, &KX_GameObject::Type)) {
2391 *object = static_cast<KX_GameObject*>(value);
2398 PyErr_SetString(PyExc_TypeError, "Expect a KX_GameObject, a string or None");
2400 PyErr_SetString(PyExc_TypeError, "Expect a KX_GameObject or a string");