d0c6792cce0f848111695325e8ac9849959bbba5
[blender.git] / source / gameengine / Ketsji / KX_GameObject.cpp
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
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.
8  *
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.
13  *
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.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  * Game object wrapper
27  */
28
29 /** \file gameengine/Ketsji/KX_GameObject.cpp
30  *  \ingroup ketsji
31  */
32
33 #ifdef _MSC_VER
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 )
37 #endif
38
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"
52 #include "SG_Node.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"
64 #include "KX_Scene.h"
65
66 #include "BKE_object.h"
67
68 #include "BL_ActionManager.h"
69 #include "BL_Action.h"
70
71 #include "PyObjectPlus.h" /* python stuff */
72 #include "BLI_utildefines.h"
73 #include "python_utildefines.h"
74
75 // This file defines relationships between parents and children
76 // in the game engine.
77
78 #include "KX_SG_NodeRelationships.h"
79
80 #include "BLI_math.h"
81
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,
85                                                      0.0, 1.0, 0.0,
86                                                      0.0, 0.0, 1.0);
87
88 KX_GameObject::KX_GameObject(
89         void* sgReplicationInfo,
90         SG_Callbacks callbacks)
91     : SCA_IObject(),
92       m_bDyna(false),
93       m_layer(0),
94       m_currentLodLevel(0),
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),
102       m_bVisible(true),
103       m_bCulled(true),
104       m_bOccluder(false),
105       m_pPhysicsController(NULL),
106       m_pGraphicController(NULL),
107       m_xray(false),
108       m_pHitObject(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)
115
116 #ifdef WITH_PYTHON
117     , m_attr_dict(NULL),
118     m_collisionCallbacks(NULL)
119 #endif
120 {
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);
124
125         // define the relationship between this node and it's parent.
126         
127         KX_NormalParentRelation * parent_relation = 
128                 KX_NormalParentRelation::New();
129         m_pSGNode->SetParentRelation(parent_relation);
130 };
131
132
133
134 KX_GameObject::~KX_GameObject()
135 {
136 #ifdef WITH_PYTHON
137         if (m_attr_dict) {
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);
141         }
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);
147         }
148 #endif // WITH_PYTHON
149
150         RemoveMeshes();
151
152         // is this delete somewhere ?
153         //if (m_sumoObj)
154         //      delete m_sumoObj;
155         delete m_pClient_info;
156         //if (m_pSGNode)
157         //      delete m_pSGNode;
158         if (m_pSGNode)
159         {
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)
166                 {
167                         (*contit)->ClearObject();
168                 }
169                 m_pSGNode->SetSGClientObject(NULL);
170
171                 /* m_pSGNode is freed in KX_Scene::RemoveNodeDestructObject */
172         }
173         if (m_pGraphicController)
174         {
175                 delete m_pGraphicController;
176         }
177
178         if (m_pPhysicsController)
179         {
180                 delete m_pPhysicsController;
181         }
182
183         if (m_pObstacleSimulation)
184         {
185                 m_pObstacleSimulation->DestroyObstacleForObj(this);
186         }
187
188         if (m_actionManager)
189         {
190                 delete m_actionManager;
191         }
192
193         if (m_pDupliGroupObject)
194         {
195                 m_pDupliGroupObject->Release();
196         }
197
198         if (m_pInstanceObjects)
199         {
200                 m_pInstanceObjects->Release();
201         }
202 }
203
204 KX_GameObject* KX_GameObject::GetClientObject(KX_ClientObjectInfo *info)
205 {
206         if (!info)
207                 return NULL;
208         return info->m_gameobject;
209 }
210
211 CValue* KX_GameObject:: Calc(VALUE_OPERATOR op, CValue *val) 
212 {
213         return NULL;
214 }
215
216
217
218 CValue* KX_GameObject::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val)
219 {
220         return NULL;
221 }
222
223
224
225 const STR_String & KX_GameObject::GetText()
226 {
227         return m_text;
228 }
229
230
231
232 double KX_GameObject::GetNumber()
233 {
234         return 0;
235 }
236
237
238
239 STR_String& KX_GameObject::GetName()
240 {
241         return m_name;
242 }
243
244
245 /* Set the name of the value */
246 void KX_GameObject::SetName(const char *name)
247 {
248         m_name = name;
249 }
250
251 PHY_IPhysicsController* KX_GameObject::GetPhysicsController()
252 {
253         return m_pPhysicsController;
254 }
255
256 KX_GameObject* KX_GameObject::GetDupliGroupObject()
257
258         return m_pDupliGroupObject;
259 }
260
261 CListValue* KX_GameObject::GetInstanceObjects()
262
263         return m_pInstanceObjects;
264 }
265
266 void KX_GameObject::AddInstanceObjects(KX_GameObject* obj)
267 {
268         if (!m_pInstanceObjects)
269                 m_pInstanceObjects = new CListValue();
270
271         obj->AddRef();
272         m_pInstanceObjects->Add(obj);
273 }
274
275 void KX_GameObject::RemoveInstanceObject(KX_GameObject* obj)
276 {
277         assert(m_pInstanceObjects);
278         m_pInstanceObjects->RemoveValue(obj);
279         obj->Release();
280 }
281
282 void KX_GameObject::RemoveDupliGroupObject()
283 {
284         if (m_pDupliGroupObject) {
285                 m_pDupliGroupObject->Release();
286                 m_pDupliGroupObject = NULL;
287         }
288 }
289
290 void KX_GameObject::SetDupliGroupObject(KX_GameObject* obj)
291 {
292         obj->AddRef();
293         m_pDupliGroupObject = obj;
294 }
295
296 void KX_GameObject::AddConstraint(bRigidBodyJointConstraint *cons)
297 {
298         m_constraints.push_back(cons);
299 }
300
301 std::vector<bRigidBodyJointConstraint*> KX_GameObject::GetConstraints()
302 {
303         return m_constraints;
304 }
305
306 void KX_GameObject::ClearConstraints()
307 {
308         m_constraints.clear();
309 }
310
311 KX_GameObject* KX_GameObject::GetParent()
312 {
313         KX_GameObject* result = NULL;
314         SG_Node* node = m_pSGNode;
315         
316         while (node && !result)
317         {
318                 node = node->GetSGParent();
319                 if (node)
320                         result = (KX_GameObject*)node->GetSGClientObject();
321         }
322
323         return result;
324         
325 }
326
327 void KX_GameObject::SetParent(KX_Scene *scene, KX_GameObject* obj, bool addToCompound, bool ghost)
328 {
329         // check on valid node in case a python controller holds a reference to a deleted object
330         if (obj && 
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
336         {
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; }
346
347                 // Remove us from our old parent and set our new parent
348                 RemoveParent(scene);
349                 obj->GetSGNode()->AddChild(GetSGNode());
350
351                 if (m_pPhysicsController)
352                 {
353                         m_pPhysicsController->SuspendDynamics(ghost);
354                 }
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;
362
363                 NodeSetLocalScale(scale1);
364                 NodeSetLocalPosition(MT_Point3(newpos[0],newpos[1],newpos[2]));
365                 NodeSetLocalOrientation(invori*NodeGetWorldOrientation());
366                 NodeUpdateGS(0.f);
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
371                         Release();
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)
375                 {
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())
382                         {
383                                 rootobj->m_pPhysicsController->AddCompoundChild(m_pPhysicsController);
384                         }
385                 }
386                 // graphically, the object hasn't change place, no need to update m_pGraphicController
387         }
388 }
389
390 void KX_GameObject::RemoveParent(KX_Scene *scene)
391 {
392         // check on valid node in case a python controller holds a reference to a deleted object
393         if (GetSGNode() && GetSGNode()->GetSGParent())
394         {
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());
401
402                 // Remove us from our parent
403                 GetSGNode()->DisconnectFromParent();
404                 NodeUpdateGS(0.f);
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)
411                 {
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())
416                         {
417                                 rootobj->m_pPhysicsController->RemoveCompoundChild(m_pPhysicsController);
418                         }
419                         m_pPhysicsController->RestoreDynamics();
420                         if (m_pPhysicsController->IsDynamic() && (rootobj != NULL && rootobj->m_pPhysicsController))
421                         {
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();
425                                 MT_Point3 relPoint;
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);
431                         }
432                 }
433                 // graphically, the object hasn't change place, no need to update m_pGraphicController
434         }
435 }
436
437 BL_ActionManager* KX_GameObject::GetActionManager()
438 {
439         // We only want to create an action manager if we need it
440         if (!m_actionManager)
441         {
442                 GetScene()->AddAnimatedObject(this);
443                 m_actionManager = new BL_ActionManager(this);
444         }
445         return m_actionManager;
446 }
447
448 bool KX_GameObject::PlayAction(const char* name,
449                                                                 float start,
450                                                                 float end,
451                                                                 short layer,
452                                                                 short priority,
453                                                                 float blendin,
454                                                                 short play_mode,
455                                                                 float layer_weight,
456                                                                 short ipo_flags,
457                                                                 float playback_speed,
458                                                                 short blend_mode)
459 {
460         return GetActionManager()->PlayAction(name, start, end, layer, priority, blendin, play_mode, layer_weight, ipo_flags, playback_speed, blend_mode);
461 }
462
463 void KX_GameObject::StopAction(short layer)
464 {
465         GetActionManager()->StopAction(layer);
466 }
467
468 bool KX_GameObject::IsActionDone(short layer)
469 {
470         return GetActionManager()->IsActionDone(layer);
471 }
472
473 void KX_GameObject::UpdateActionManager(float curtime)
474 {
475         GetActionManager()->Update(curtime);
476 }
477
478 void KX_GameObject::UpdateActionIPOs()
479 {
480         GetActionManager()->UpdateIPOs();
481 }
482
483 float KX_GameObject::GetActionFrame(short layer)
484 {
485         return GetActionManager()->GetActionFrame(layer);
486 }
487
488 void KX_GameObject::SetActionFrame(short layer, float frame)
489 {
490         GetActionManager()->SetActionFrame(layer, frame);
491 }
492
493 bAction *KX_GameObject::GetCurrentAction(short layer)
494 {
495         return GetActionManager()->GetCurrentAction(layer);
496 }
497
498 void KX_GameObject::SetPlayMode(short layer, short mode)
499 {
500         GetActionManager()->SetPlayMode(layer, mode);
501 }
502
503 void KX_GameObject::SetTimes(short layer, float start, float end)
504 {
505         GetActionManager()->SetTimes(layer, start, end);
506 }
507
508 void KX_GameObject::ProcessReplica()
509 {
510         SCA_IObject::ProcessReplica();
511
512         m_pGraphicController = NULL;
513         m_pPhysicsController = NULL;
514         m_pSGNode = NULL;
515         m_pClient_info = new KX_ClientObjectInfo(*m_pClient_info);
516         m_pClient_info->m_gameobject = this;
517         m_actionManager = NULL;
518         m_state = 0;
519
520         KX_Scene* scene = KX_GetActiveScene();
521         KX_ObstacleSimulation* obssimulation = scene->GetObstacleSimulation();
522         struct Object* blenderobject = GetBlenderObject();
523         if (obssimulation && (blenderobject->gameflag & OB_HASOBSTACLE))
524         {
525                 obssimulation->AddObstacleForObj(this);
526         }
527
528 #ifdef WITH_PYTHON
529         if (m_attr_dict)
530                 m_attr_dict= PyDict_Copy(m_attr_dict);
531 #endif
532                 
533 }
534
535 static void setGraphicController_recursive(SG_Node* node)
536 {
537         NodeList& children = node->GetSGChildren();
538
539         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
540         {
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);
545                 
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);
549         }
550 }
551
552
553 void KX_GameObject::ActivateGraphicController(bool recurse)
554 {
555         if (m_pGraphicController)
556         {
557                 m_pGraphicController->Activate(m_bVisible);
558         }
559         if (recurse)
560         {
561                 setGraphicController_recursive(GetSGNode());
562         }
563 }
564
565 void KX_GameObject::SetUserCollisionGroup(short group)
566 {
567         m_userCollisionGroup = group;
568 }
569 void KX_GameObject::SetUserCollisionMask(short mask)
570 {
571         m_userCollisionMask = mask;
572 }
573
574 bool KX_GameObject::CheckCollision(KX_GameObject* other)
575 {
576         return this->m_userCollisionGroup & other->m_userCollisionMask;
577 }
578
579 CValue* KX_GameObject::GetReplica()
580 {
581         KX_GameObject* replica = new KX_GameObject(*this);
582
583         // this will copy properties and so on...
584         replica->ProcessReplica();
585
586         return replica;
587 }
588
589 float KX_GameObject::getLinearDamping() const
590 {
591         if (m_pPhysicsController)
592                 return m_pPhysicsController->GetLinearDamping();
593         return 0;
594 }
595
596 float KX_GameObject::getAngularDamping() const
597 {
598         if (m_pPhysicsController)
599                 return m_pPhysicsController->GetAngularDamping();
600         return 0;
601 }
602
603 void KX_GameObject::setLinearDamping(float damping)
604 {
605         if (m_pPhysicsController)
606                 m_pPhysicsController->SetLinearDamping(damping);
607 }
608
609
610 void KX_GameObject::setAngularDamping(float damping)
611 {
612         if (m_pPhysicsController)
613                 m_pPhysicsController->SetAngularDamping(damping);
614 }
615
616
617 void KX_GameObject::setDamping(float linear, float angular)
618 {
619         if (m_pPhysicsController)
620                 m_pPhysicsController->SetDamping(linear, angular);
621 }
622
623
624 void KX_GameObject::ApplyForce(const MT_Vector3& force,bool local)
625 {
626         if (m_pPhysicsController)
627                 m_pPhysicsController->ApplyForce(force,local);
628 }
629
630
631
632 void KX_GameObject::ApplyTorque(const MT_Vector3& torque,bool local)
633 {
634         if (m_pPhysicsController)
635                 m_pPhysicsController->ApplyTorque(torque,local);
636 }
637
638
639
640 void KX_GameObject::ApplyMovement(const MT_Vector3& dloc,bool local)
641 {
642         if (GetSGNode()) 
643         {
644                 if (m_pPhysicsController) // (IsDynamic())
645                 {
646                         m_pPhysicsController->RelativeTranslate(dloc,local);
647                 }
648                 GetSGNode()->RelativeTranslate(dloc,GetSGNode()->GetSGParent(),local);
649         }
650 }
651
652
653
654 void KX_GameObject::ApplyRotation(const MT_Vector3& drot,bool local)
655 {
656         MT_Matrix3x3 rotmat(drot);
657         
658         if (GetSGNode()) {
659                 GetSGNode()->RelativeRotate(rotmat,local);
660
661                 if (m_pPhysicsController) { // (IsDynamic())
662                         m_pPhysicsController->RelativeRotate(rotmat,local);
663                 }
664         }
665 }
666
667
668
669 /**
670  * GetOpenGL Matrix, returns an OpenGL 'compatible' matrix
671  */
672 double* KX_GameObject::GetOpenGLMatrix()
673 {
674         // todo: optimize and only update if necessary
675         double* fl = m_OpenGL_4x4Matrix.getPointer();
676         if (GetSGNode()) {
677                 MT_Transform trans;
678         
679                 trans.setOrigin(GetSGNode()->GetWorldPosition());
680                 trans.setBasis(GetSGNode()->GetWorldOrientation());
681         
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]);
685                 trans.getValue(fl);
686                 GetSGNode()->ClearDirty();
687         }
688         return fl;
689 }
690
691 void KX_GameObject::UpdateBlenderObjectMatrix(Object* blendobj)
692 {
693         if (!blendobj)
694                 blendobj = m_pBlenderObject;
695         if (blendobj) {
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]);
704         }
705 }
706
707 void KX_GameObject::AddMeshUser()
708 {
709         for (size_t i=0;i<m_meshes.size();i++)
710         {
711                 m_meshes[i]->AddMeshUser(this, &m_meshSlots, GetDeformer());
712         }
713         // set the part of the mesh slot that never change
714         double* fl = GetOpenGLMatrixPtr()->getPointer();
715
716         SG_QList::iterator<RAS_MeshSlot> mit(m_meshSlots);
717 //      RAS_MeshSlot* ms;
718         for (mit.begin(); !mit.end(); ++mit)
719         {
720                 (*mit)->m_OpenGLMatrix = fl;
721         }
722         UpdateBuckets(false);
723 }
724
725 static void UpdateBuckets_recursive(SG_Node* node)
726 {
727         NodeList& children = node->GetSGChildren();
728
729         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
730         {
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);
735                 
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);
739         }
740 }
741
742 void KX_GameObject::UpdateBuckets( bool recursive )
743 {
744         if (GetSGNode()) {
745                 RAS_MeshSlot *ms;
746
747                 if (GetSGNode()->IsDirty())
748                         GetOpenGLMatrix();
749
750                 SG_QList::iterator<RAS_MeshSlot> mit(m_meshSlots);
751                 for (mit.begin(); !mit.end(); ++mit)
752                 {
753                         ms = *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;
758                         if (!ms->m_bCulled) 
759                                 ms->m_bucket->ActivateMesh(ms);
760                         
761                         /* split if necessary */
762 #ifdef USE_SPLIT
763                         ms->Split();
764 #endif
765                 }
766         
767                 if (recursive) {
768                         UpdateBuckets_recursive(GetSGNode());
769                 }
770         }
771 }
772
773 void KX_GameObject::RemoveMeshes()
774 {
775         for (size_t i=0;i<m_meshes.size();i++)
776                 m_meshes[i]->RemoveFromBuckets(this);
777
778         //note: meshes can be shared, and are deleted by KX_BlenderSceneConverter
779
780         m_meshes.clear();
781 }
782
783 void KX_GameObject::AddLodMesh(RAS_MeshObject* mesh)
784 {
785         m_lodmeshes.push_back(mesh);
786 }
787
788 void KX_GameObject::UpdateLod(MT_Vector3 &cam_pos)
789 {
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);
797                 }
798         }
799
800         if (this->m_lodmeshes.empty()) return;
801
802         MT_Vector3 delta = this->NodeGetWorldPosition() - cam_pos;
803         float distance2 = delta.length2();
804
805         int level = 0;
806         Object *bob = this->GetBlenderObject();
807         LodLevel *lod = (LodLevel*) bob->lodlevels.first;
808         KX_Scene *kxscene = this->GetScene();
809
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;
819                                 }
820                                 else {
821                                         hysteresis = kxscene->GetLodHysteresisValue();
822                                 }
823                         }
824                         float hystvariance = MT_abs(lod->next->distance - lod->distance) * hysteresis / 100;
825                         if ((lod->next->distance + hystvariance) * (lod->next->distance + hystvariance) > distance2)
826                                 break;
827                 }
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;
834                                 }
835                                 else {
836                                         hysteresis = kxscene->GetLodHysteresisValue();
837                                 }
838                         }
839                         float hystvariance = MT_abs(lod->next->distance - lod->distance) * hysteresis / 100;
840                         if ((lod->next->distance - hystvariance) * (lod->next->distance - hystvariance) > distance2)
841                                 break;
842                 }
843         }
844
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);
850         }
851 }
852
853 void KX_GameObject::UpdateTransform()
854 {
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();
861
862 }
863
864 void KX_GameObject::UpdateTransformFunc(SG_IObject* node, void* gameobj, void* scene)
865 {
866         ((KX_GameObject*)gameobj)->UpdateTransform();
867 }
868
869 void KX_GameObject::SynchronizeTransform()
870 {
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();
876 }
877
878 void KX_GameObject::SynchronizeTransformFunc(SG_IObject* node, void* gameobj, void* scene)
879 {
880         ((KX_GameObject*)gameobj)->SynchronizeTransform();
881 }
882
883
884 void KX_GameObject::SetDebugColor(unsigned int bgra)
885 {
886         for (size_t i=0;i<m_meshes.size();i++)
887                 m_meshes[i]->DebugColor(bgra);
888 }
889
890
891
892 void KX_GameObject::ResetDebugColor()
893 {
894         SetDebugColor(0xff000000);
895 }
896
897 void KX_GameObject::InitIPO(bool ipo_as_force,
898                             bool ipo_add,
899                             bool ipo_local)
900 {
901         SGControllerList::iterator it = GetSGNode()->GetSGControllerList().begin();
902
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);
908                 it++;
909         }
910
911
912 void KX_GameObject::UpdateIPO(float curframetime,
913                                                           bool recurse) 
914 {
915         // just the 'normal' update procedure.
916         GetSGNode()->SetSimulatedTime(curframetime,recurse);
917         GetSGNode()->UpdateWorldData(curframetime);
918         UpdateTransform();
919 }
920
921 // IPO update
922 void 
923 KX_GameObject::UpdateMaterialData(
924                 dword matname_hash,
925                 MT_Vector4 rgba,
926                 MT_Vector3 specrgb,
927                 MT_Scalar hard,
928                 MT_Scalar spec,
929                 MT_Scalar ref,
930                 MT_Scalar emit,
931                 MT_Scalar alpha
932
933         )
934 {
935         int mesh = 0;
936         if (((unsigned int)mesh < m_meshes.size()) && mesh >= 0) {
937                 list<RAS_MeshMaterial>::iterator mit = m_meshes[mesh]->GetFirstMaterial();
938
939                 for (; mit != m_meshes[mesh]->GetLastMaterial(); ++mit)
940                 {
941                         RAS_IPolyMaterial* poly = mit->m_bucket->GetPolyMaterial();
942
943                         if (poly->GetFlag() & RAS_BLENDERMAT )
944                         {
945                                 KX_BlenderMaterial *m =  static_cast<KX_BlenderMaterial*>(poly);
946                                 
947                                 if (matname_hash == 0)
948                                 {
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);
952                                 }
953                                 else
954                                 {
955                                         if (matname_hash == poly->GetMaterialNameHash())
956                                         {
957                                                 m->UpdateIPO(rgba, specrgb,hard,spec,ref,emit, alpha);
958                                                 m_meshes[mesh]->SetVertexColor(poly,rgba);
959                                                 
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
963                                         }
964                                 }
965                         }
966                 }
967         }
968 }
969 bool
970 KX_GameObject::GetVisible(
971         void
972         )
973 {
974         return m_bVisible;
975 }
976
977 static void setVisible_recursive(SG_Node* node, bool v)
978 {
979         NodeList& children = node->GetSGChildren();
980
981         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
982         {
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);
987                 
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);
991         }
992 }
993
994
995 void
996 KX_GameObject::SetVisible(
997         bool v,
998         bool recursive
999         )
1000 {
1001         if (GetSGNode()) {
1002                 m_bVisible = v;
1003                 if (m_pGraphicController)
1004                         m_pGraphicController->Activate(m_bVisible);
1005                 if (recursive)
1006                         setVisible_recursive(GetSGNode(), v);
1007         }
1008 }
1009
1010 static void setOccluder_recursive(SG_Node* node, bool v)
1011 {
1012         NodeList& children = node->GetSGChildren();
1013
1014         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
1015         {
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);
1020                 
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);
1024         }
1025 }
1026
1027 void
1028 KX_GameObject::SetOccluder(
1029         bool v,
1030         bool recursive
1031         )
1032 {
1033         if (GetSGNode()) {
1034                 m_bOccluder = v;
1035                 if (recursive)
1036                         setOccluder_recursive(GetSGNode(), v);
1037         }
1038 }
1039
1040 static void setDebug_recursive(SG_Node *node, bool debug)
1041 {
1042         NodeList& children = node->GetSGChildren();
1043         KX_Scene *scene = KX_GetActiveScene();
1044
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) {
1049                         if (debug) {
1050                                 if (!scene->ObjectInDebugList(clientgameobj))
1051                                         scene->AddObjectDebugProperties(clientgameobj);
1052                         }
1053                         else
1054                                 scene->RemoveObjectDebugProperties(clientgameobj);
1055                 }
1056
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);
1060         }
1061 }
1062
1063 void KX_GameObject::SetUseDebugProperties( bool debug, bool recursive )
1064 {
1065         KX_Scene *scene = KX_GetActiveScene();
1066
1067         if (debug) {
1068                 if (!scene->ObjectInDebugList(this))
1069                         scene->AddObjectDebugProperties(this);
1070         }
1071         else
1072                 scene->RemoveObjectDebugProperties(this);
1073
1074         if (recursive)
1075                 setDebug_recursive(GetSGNode(), debug);
1076 }
1077
1078 void
1079 KX_GameObject::SetLayer(
1080         int l
1081         )
1082 {
1083         m_layer = l;
1084 }
1085
1086 int
1087 KX_GameObject::GetLayer(
1088         void
1089         )
1090 {
1091         return m_layer;
1092 }
1093
1094 void KX_GameObject::addLinearVelocity(const MT_Vector3& lin_vel,bool local)
1095 {
1096         if (m_pPhysicsController)
1097         {
1098                 MT_Vector3 lv = local ? NodeGetWorldOrientation() * lin_vel : lin_vel;
1099                 m_pPhysicsController->SetLinearVelocity(lv + m_pPhysicsController->GetLinearVelocity(), 0);
1100         }
1101 }
1102
1103
1104
1105 void KX_GameObject::setLinearVelocity(const MT_Vector3& lin_vel,bool local)
1106 {
1107         if (m_pPhysicsController)
1108                 m_pPhysicsController->SetLinearVelocity(lin_vel,local);
1109 }
1110
1111
1112
1113 void KX_GameObject::setAngularVelocity(const MT_Vector3& ang_vel,bool local)
1114 {
1115         if (m_pPhysicsController)
1116                 m_pPhysicsController->SetAngularVelocity(ang_vel,local);
1117 }
1118
1119
1120 void KX_GameObject::ResolveCombinedVelocities(
1121         const MT_Vector3 & lin_vel,
1122         const MT_Vector3 & ang_vel,
1123         bool lin_vel_local,
1124         bool ang_vel_local
1125 ) {
1126         if (m_pPhysicsController)
1127         {
1128
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());
1133         }
1134 }
1135
1136
1137 void KX_GameObject::SetObjectColor(const MT_Vector4& rgbavec)
1138 {
1139         m_bUseObjectColor = true;
1140         m_objectColor = rgbavec;
1141 }
1142
1143 const MT_Vector4& KX_GameObject::GetObjectColor()
1144 {
1145         return m_objectColor;
1146 }
1147
1148 void KX_GameObject::AlignAxisToVect(const MT_Vector3& dir, int axis, float fac)
1149 {
1150         MT_Matrix3x3 orimat;
1151         MT_Vector3 vect,ori,z,x,y;
1152         MT_Scalar len;
1153
1154         // check on valid node in case a python controller holds a reference to a deleted object
1155         if (!GetSGNode())
1156                 return;
1157
1158         vect = dir;
1159         len = vect.length();
1160         if (MT_fuzzyZero(len))
1161         {
1162                 cout << "alignAxisToVect() Error: Null vector!\n";
1163                 return;
1164         }
1165         
1166         if (fac <= 0.0f) {
1167                 return;
1168         }
1169         
1170         // normalize
1171         vect /= len;
1172         orimat = GetSGNode()->GetWorldOrientation();
1173         switch (axis)
1174         {
1175                 case 0: //x axis
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!
1179                         if (fac == 1.0f) {
1180                                 x = vect;
1181                         } else {
1182                                 x = (vect * fac) + ((orimat * MT_Vector3(1.0, 0.0, 0.0)) * (1.0f - fac));
1183                                 len = x.length();
1184                                 if (MT_fuzzyZero(len)) x = vect;
1185                                 else x /= len;
1186                         }
1187                         y = ori.cross(x);
1188                         z = x.cross(y);
1189                         break;
1190                 case 1: //y axis
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]);
1194                         if (fac == 1.0f) {
1195                                 y = vect;
1196                         } else {
1197                                 y = (vect * fac) + ((orimat * MT_Vector3(0.0, 1.0, 0.0)) * (1.0f - fac));
1198                                 len = y.length();
1199                                 if (MT_fuzzyZero(len)) y = vect;
1200                                 else y /= len;
1201                         }
1202                         z = ori.cross(y);
1203                         x = y.cross(z);
1204                         break;
1205                 case 2: //z axis
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]);
1209                         if (fac == 1.0f) {
1210                                 z = vect;
1211                         } else {
1212                                 z = (vect * fac) + ((orimat * MT_Vector3(0.0, 0.0, 1.0)) * (1.0f - fac));
1213                                 len = z.length();
1214                                 if (MT_fuzzyZero(len)) z = vect;
1215                                 else z /= len;
1216                         }
1217                         x = ori.cross(z);
1218                         y = z.cross(x);
1219                         break;
1220                 default: //wrong input?
1221                         cout << "alignAxisToVect(): Wrong axis '" << axis <<"'\n";
1222                         return;
1223         }
1224         x.normalize(); //normalize the vectors
1225         y.normalize();
1226         z.normalize();
1227         orimat.setValue(        x[0],y[0],z[0],
1228                                                 x[1],y[1],z[1],
1229                                                 x[2],y[2],z[2]);
1230         if (GetSGNode()->GetSGParent() != NULL)
1231         {
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);
1236         }
1237         else
1238                 NodeSetLocalOrientation(orimat);
1239 }
1240
1241 MT_Scalar KX_GameObject::GetMass()
1242 {
1243         if (m_pPhysicsController)
1244         {
1245                 return m_pPhysicsController->GetMass();
1246         }
1247         return 0.0;
1248 }
1249
1250 MT_Vector3 KX_GameObject::GetLocalInertia()
1251 {
1252         MT_Vector3 local_inertia(0.0,0.0,0.0);
1253         if (m_pPhysicsController)
1254         {
1255                 local_inertia = m_pPhysicsController->GetLocalInertia();
1256         }
1257         return local_inertia;
1258 }
1259
1260 MT_Vector3 KX_GameObject::GetLinearVelocity(bool local)
1261 {
1262         MT_Vector3 velocity(0.0,0.0,0.0), locvel;
1263         MT_Matrix3x3 ori;
1264         if (m_pPhysicsController)
1265         {
1266                 velocity = m_pPhysicsController->GetLinearVelocity();
1267                 
1268                 if (local)
1269                 {
1270                         ori = GetSGNode()->GetWorldOrientation();
1271                         
1272                         locvel = velocity * ori;
1273                         return locvel;
1274                 }
1275         }
1276         return velocity;
1277 }
1278
1279 MT_Vector3 KX_GameObject::GetAngularVelocity(bool local)
1280 {
1281         MT_Vector3 velocity(0.0,0.0,0.0), locvel;
1282         MT_Matrix3x3 ori;
1283         if (m_pPhysicsController)
1284         {
1285                 velocity = m_pPhysicsController->GetAngularVelocity();
1286                 
1287                 if (local)
1288                 {
1289                         ori = GetSGNode()->GetWorldOrientation();
1290                         
1291                         locvel = velocity * ori;
1292                         return locvel;
1293                 }
1294         }
1295         return velocity;
1296 }
1297
1298 MT_Vector3 KX_GameObject::GetVelocity(const MT_Point3& point)
1299 {
1300         if (m_pPhysicsController)
1301         {
1302                 return m_pPhysicsController->GetVelocity(point);
1303         }
1304         return MT_Vector3(0.0,0.0,0.0);
1305 }
1306
1307 // scenegraph node stuff
1308
1309 void KX_GameObject::NodeSetLocalPosition(const MT_Point3& trans)
1310 {
1311         // check on valid node in case a python controller holds a reference to a deleted object
1312         if (!GetSGNode())
1313                 return;
1314
1315         if (m_pPhysicsController && !GetSGNode()->GetSGParent())
1316         {
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);
1322         }
1323
1324         GetSGNode()->SetLocalPosition(trans);
1325
1326 }
1327
1328
1329
1330 void KX_GameObject::NodeSetLocalOrientation(const MT_Matrix3x3& rot)
1331 {
1332         // check on valid node in case a python controller holds a reference to a deleted object
1333         if (!GetSGNode())
1334                 return;
1335
1336         if (m_pPhysicsController && !GetSGNode()->GetSGParent())
1337         {
1338                 // see note above
1339                 m_pPhysicsController->SetOrientation(rot);
1340         }
1341         GetSGNode()->SetLocalOrientation(rot);
1342 }
1343
1344 void KX_GameObject::NodeSetGlobalOrientation(const MT_Matrix3x3& rot)
1345 {
1346         // check on valid node in case a python controller holds a reference to a deleted object
1347         if (!GetSGNode())
1348                 return;
1349
1350         if (GetSGNode()->GetSGParent())
1351                 GetSGNode()->SetLocalOrientation(GetSGNode()->GetSGParent()->GetWorldOrientation().inverse()*rot);
1352         else
1353                 NodeSetLocalOrientation(rot);
1354 }
1355
1356 void KX_GameObject::NodeSetLocalScale(const MT_Vector3& scale)
1357 {
1358         // check on valid node in case a python controller holds a reference to a deleted object
1359         if (!GetSGNode())
1360                 return;
1361
1362         if (m_pPhysicsController && !GetSGNode()->GetSGParent())
1363         {
1364                 // see note above
1365                 m_pPhysicsController->SetScaling(scale);
1366         }
1367         GetSGNode()->SetLocalScale(scale);
1368 }
1369
1370
1371
1372 void KX_GameObject::NodeSetRelativeScale(const MT_Vector3& scale)
1373 {
1374         if (GetSGNode())
1375         {
1376                 GetSGNode()->RelativeScale(scale);
1377                 if (m_pPhysicsController && (!GetSGNode()->GetSGParent()))
1378                 {
1379                         // see note above
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);
1384                 }
1385         }
1386 }
1387
1388 void KX_GameObject::NodeSetWorldScale(const MT_Vector3& scale)
1389 {
1390         if (!GetSGNode())
1391                 return;
1392         SG_Node* parent = GetSGNode()->GetSGParent();
1393         if (parent != NULL)
1394         {
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)
1400                 { 
1401                         return; 
1402                 }
1403
1404                 p_scale[0] = 1/p_scale[0];
1405                 p_scale[1] = 1/p_scale[1];
1406                 p_scale[2] = 1/p_scale[2];
1407
1408                 NodeSetLocalScale(scale * p_scale);
1409         }
1410         else
1411         {
1412                 NodeSetLocalScale(scale);
1413         }
1414 }
1415
1416 void KX_GameObject::NodeSetWorldPosition(const MT_Point3& trans)
1417 {
1418         if (!GetSGNode())
1419                 return;
1420         SG_Node* parent = GetSGNode()->GetSGParent();
1421         if (parent != NULL)
1422         {
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)
1428                 { 
1429                         return; 
1430                 }
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]));
1437         }
1438         else
1439         {
1440                 NodeSetLocalPosition(trans);
1441         }
1442 }
1443
1444
1445 void KX_GameObject::NodeUpdateGS(double time)
1446 {
1447         if (GetSGNode())
1448                 GetSGNode()->UpdateWorldData(time);
1449 }
1450
1451
1452
1453 const MT_Matrix3x3& KX_GameObject::NodeGetWorldOrientation() const
1454 {
1455         // check on valid node in case a python controller holds a reference to a deleted object
1456         if (!GetSGNode())
1457                 return dummy_orientation;
1458         return GetSGNode()->GetWorldOrientation();
1459 }
1460
1461 const MT_Matrix3x3& KX_GameObject::NodeGetLocalOrientation() const
1462 {
1463         // check on valid node in case a python controller holds a reference to a deleted object
1464         if (!GetSGNode())
1465                 return dummy_orientation;
1466         return GetSGNode()->GetLocalOrientation();
1467 }
1468
1469 const MT_Vector3& KX_GameObject::NodeGetWorldScaling() const
1470 {
1471         // check on valid node in case a python controller holds a reference to a deleted object
1472         if (!GetSGNode())
1473                 return dummy_scaling;
1474
1475         return GetSGNode()->GetWorldScaling();
1476 }
1477
1478 const MT_Vector3& KX_GameObject::NodeGetLocalScaling() const
1479 {
1480         // check on valid node in case a python controller holds a reference to a deleted object
1481         if (!GetSGNode())
1482                 return dummy_scaling;
1483
1484         return GetSGNode()->GetLocalScale();
1485 }
1486
1487 const MT_Point3& KX_GameObject::NodeGetWorldPosition() const
1488 {
1489         // check on valid node in case a python controller holds a reference to a deleted object
1490         if (GetSGNode())
1491                 return GetSGNode()->GetWorldPosition();
1492         else
1493                 return dummy_point;
1494 }
1495
1496 const MT_Point3& KX_GameObject::NodeGetLocalPosition() const
1497 {
1498         // check on valid node in case a python controller holds a reference to a deleted object
1499         if (GetSGNode())
1500                 return GetSGNode()->GetLocalPosition();
1501         else
1502                 return dummy_point;
1503 }
1504
1505
1506 void KX_GameObject::UnregisterCollisionCallbacks()
1507 {
1508         if (!GetPhysicsController()) {
1509                 printf("Warning, trying to unregister collision callbacks for object without collisions: %s!\n", GetName().ReadPtr());
1510                 return;
1511         }
1512
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);
1523         }
1524 }
1525
1526 void KX_GameObject::RegisterCollisionCallbacks()
1527 {
1528         if (!GetPhysicsController()) {
1529                 printf("Warning, trying to register collision callbacks for object without collisions: %s!\n", GetName().ReadPtr());
1530                 return;
1531         }
1532
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
1542                         pe->AddSensor(spc);
1543         }
1544 }
1545 void KX_GameObject::RunCollisionCallbacks(KX_GameObject *collider, const MT_Vector3 &point, const MT_Vector3 &normal)
1546 {
1547         #ifdef WITH_PYTHON
1548         Py_ssize_t len;
1549         PyObject* collision_callbacks = m_collisionCallbacks;
1550
1551         if (collision_callbacks && (len=PyList_GET_SIZE(collision_callbacks)))
1552         {
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.
1556
1557                 PyObject *func;
1558                 PyObject *ret;
1559                 int co_argcount;
1560
1561                 // Iterate the list and run the callbacks
1562                 for (Py_ssize_t pos=0; pos < len; pos++)
1563                 {
1564                         func = PyList_GET_ITEM(collision_callbacks, pos);
1565
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;
1572                         } else {
1573                                 // We'll just assume the callable takes the correct number of arguments.
1574                                 co_argcount = 3;
1575                         }
1576
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());
1584                                 }
1585                                 ret = PyObject_Call(func, args_1, NULL);
1586                         } else {
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));
1594                                 }
1595                                 ret = PyObject_Call(func, args_3, NULL);
1596                         }
1597
1598                         if (ret == NULL) {
1599                                 PyErr_Print();
1600                                 PyErr_Clear();
1601                         }
1602                         else {
1603                                 Py_DECREF(ret);
1604                         }
1605                 }
1606
1607                 if (args_3) Py_DECREF(args_3);
1608                 if (args_1) Py_DECREF(args_1);
1609         }
1610         #endif
1611 }
1612
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?
1616  *
1617  * So far, only switch the physics and logic.
1618  * */
1619
1620 void KX_GameObject::Resume(void)
1621 {
1622         if (m_suspended) {
1623                 SCA_IObject::Resume();
1624                 if (GetPhysicsController())
1625                         GetPhysicsController()->RestoreDynamics();
1626
1627                 m_suspended = false;
1628         }
1629 }
1630
1631 void KX_GameObject::Suspend()
1632 {
1633         if ((!m_ignore_activity_culling) && (!m_suspended)) {
1634                 SCA_IObject::Suspend();
1635                 if (GetPhysicsController())
1636                         GetPhysicsController()->SuspendDynamics();
1637                 m_suspended = true;
1638         }
1639 }
1640
1641 static void walk_children(SG_Node* node, CListValue* list, bool recursive)
1642 {
1643         if (!node)
1644                 return;
1645         NodeList& children = node->GetSGChildren();
1646
1647         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
1648         {
1649                 SG_Node* childnode = (*childit);
1650                 CValue* childobj = (CValue*)childnode->GetSGClientObject();
1651                 if (childobj != NULL) // This is a GameObject
1652                 {
1653                         // add to the list
1654                         list->Add(childobj->AddRef());
1655                 }
1656                 
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);
1661                 }
1662         }
1663 }
1664
1665 CListValue* KX_GameObject::GetChildren()
1666 {
1667         CListValue* list = new CListValue();
1668         walk_children(GetSGNode(), list, 0); /* GetSGNode() is always valid or it would have raised an exception before this */
1669         return list;
1670 }
1671
1672 CListValue* KX_GameObject::GetChildrenRecursive()
1673 {
1674         CListValue* list = new CListValue();
1675         walk_children(GetSGNode(), list, 1);
1676         return list;
1677 }
1678
1679 KX_Scene* KX_GameObject::GetScene()
1680 {
1681         SG_Node* node = this->GetSGNode();
1682     if (node == NULL)
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());
1686 }
1687
1688 /* ---------------------------------------------------------------------
1689  * Some stuff taken from the header
1690  * --------------------------------------------------------------------- */
1691 void KX_GameObject::Relink(CTR_Map<CTR_HashedPtr, void*> *map_parameter)
1692 {
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++)
1699         {
1700                 (*sit)->Relink(map_parameter);
1701         }
1702         SCA_ActuatorList& actuatorlist = GetActuators();
1703         SCA_ActuatorList::iterator ait;
1704         for (ait=actuatorlist.begin(); ait != actuatorlist.end(); ait++)
1705         {
1706                 (*ait)->Relink(map_parameter);
1707         }
1708 }
1709
1710 #ifdef USE_MATHUTILS
1711
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
1723
1724 static unsigned char mathutils_kxgameob_vector_cb_index= -1; /* index for our callbacks */
1725
1726 static int mathutils_kxgameob_generic_check(BaseMathObject *bmo)
1727 {
1728         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1729         if (self == NULL)
1730                 return -1;
1731         
1732         return 0;
1733 }
1734
1735 static int mathutils_kxgameob_vector_get(BaseMathObject *bmo, int subtype)
1736 {
1737         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1738         if (self == NULL)
1739                 return -1;
1740
1741 #define PHYS_ERR(attr) PyErr_SetString(PyExc_AttributeError, "KX_GameObject." attr ", is missing a physics controller")
1742
1743         switch (subtype) {
1744                 case MATHUTILS_VEC_CB_POS_LOCAL:
1745                         self->NodeGetLocalPosition().getValue(bmo->data);
1746                         break;
1747                 case MATHUTILS_VEC_CB_POS_GLOBAL:
1748                         self->NodeGetWorldPosition().getValue(bmo->data);
1749                         break;
1750                 case MATHUTILS_VEC_CB_SCALE_LOCAL:
1751                         self->NodeGetLocalScaling().getValue(bmo->data);
1752                         break;
1753                 case MATHUTILS_VEC_CB_SCALE_GLOBAL:
1754                         self->NodeGetWorldScaling().getValue(bmo->data);
1755                         break;
1756                 case MATHUTILS_VEC_CB_INERTIA_LOCAL:
1757                         if (!self->GetPhysicsController()) return PHYS_ERR("localInertia"), -1;
1758                         self->GetPhysicsController()->GetLocalInertia().getValue(bmo->data);
1759                         break;
1760                 case MATHUTILS_VEC_CB_OBJECT_COLOR:
1761                         self->GetObjectColor().getValue(bmo->data);
1762                         break;
1763                 case MATHUTILS_VEC_CB_LINVEL_LOCAL:
1764                         if (!self->GetPhysicsController()) return PHYS_ERR("localLinearVelocity"), -1;
1765                         self->GetLinearVelocity(true).getValue(bmo->data);
1766                         break;
1767                 case MATHUTILS_VEC_CB_LINVEL_GLOBAL:
1768                         if (!self->GetPhysicsController()) return PHYS_ERR("worldLinearVelocity"), -1;
1769                         self->GetLinearVelocity(false).getValue(bmo->data);
1770                         break;
1771                 case MATHUTILS_VEC_CB_ANGVEL_LOCAL:
1772                         if (!self->GetPhysicsController()) return PHYS_ERR("localLinearVelocity"), -1;
1773                         self->GetAngularVelocity(true).getValue(bmo->data);
1774                         break;
1775                 case MATHUTILS_VEC_CB_ANGVEL_GLOBAL:
1776                         if (!self->GetPhysicsController()) return PHYS_ERR("worldLinearVelocity"), -1;
1777                         self->GetAngularVelocity(false).getValue(bmo->data);
1778                         break;
1779                         
1780         }
1781         
1782 #undef PHYS_ERR
1783         
1784         return 0;
1785 }
1786
1787 static int mathutils_kxgameob_vector_set(BaseMathObject *bmo, int subtype)
1788 {
1789         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1790         if (self == NULL)
1791                 return -1;
1792         
1793         switch (subtype) {
1794                 case MATHUTILS_VEC_CB_POS_LOCAL:
1795                         self->NodeSetLocalPosition(MT_Point3(bmo->data));
1796                         self->NodeUpdateGS(0.f);
1797                         break;
1798                 case MATHUTILS_VEC_CB_POS_GLOBAL:
1799                         self->NodeSetWorldPosition(MT_Point3(bmo->data));
1800                         self->NodeUpdateGS(0.f);
1801                         break;
1802                 case MATHUTILS_VEC_CB_SCALE_LOCAL:
1803                         self->NodeSetLocalScale(MT_Point3(bmo->data));
1804                         self->NodeUpdateGS(0.f);
1805                         break;
1806                 case MATHUTILS_VEC_CB_SCALE_GLOBAL:
1807                         PyErr_SetString(PyExc_AttributeError, "KX_GameObject.worldScale is read-only");
1808                         return -1;
1809                 case MATHUTILS_VEC_CB_INERTIA_LOCAL:
1810                         /* read only */
1811                         break;
1812                 case MATHUTILS_VEC_CB_OBJECT_COLOR:
1813                         self->SetObjectColor(MT_Vector4(bmo->data));
1814                         break;
1815                 case MATHUTILS_VEC_CB_LINVEL_LOCAL:
1816                         self->setLinearVelocity(MT_Point3(bmo->data),true);
1817                         break;
1818                 case MATHUTILS_VEC_CB_LINVEL_GLOBAL:
1819                         self->setLinearVelocity(MT_Point3(bmo->data),false);
1820                         break;
1821                 case MATHUTILS_VEC_CB_ANGVEL_LOCAL:
1822                         self->setAngularVelocity(MT_Point3(bmo->data),true);
1823                         break;
1824                 case MATHUTILS_VEC_CB_ANGVEL_GLOBAL:
1825                         self->setAngularVelocity(MT_Point3(bmo->data),false);
1826                         break;
1827         }
1828         
1829         return 0;
1830 }
1831
1832 static int mathutils_kxgameob_vector_get_index(BaseMathObject *bmo, int subtype, int index)
1833 {
1834         /* lazy, avoid repeteing the case statement */
1835         if (mathutils_kxgameob_vector_get(bmo, subtype) == -1)
1836                 return -1;
1837         return 0;
1838 }
1839
1840 static int mathutils_kxgameob_vector_set_index(BaseMathObject *bmo, int subtype, int index)
1841 {
1842         float f= bmo->data[index];
1843         
1844         /* lazy, avoid repeteing the case statement */
1845         if (mathutils_kxgameob_vector_get(bmo, subtype) == -1)
1846                 return -1;
1847         
1848         bmo->data[index] = f;
1849         return mathutils_kxgameob_vector_set(bmo, subtype);
1850 }
1851
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
1858 };
1859
1860 /* Matrix */
1861 #define MATHUTILS_MAT_CB_ORI_LOCAL 1
1862 #define MATHUTILS_MAT_CB_ORI_GLOBAL 2
1863
1864 static unsigned char mathutils_kxgameob_matrix_cb_index= -1; /* index for our callbacks */
1865
1866 static int mathutils_kxgameob_matrix_get(BaseMathObject *bmo, int subtype)
1867 {
1868         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1869         if (self == NULL)
1870                 return -1;
1871
1872         switch (subtype) {
1873                 case MATHUTILS_MAT_CB_ORI_LOCAL:
1874                         self->NodeGetLocalOrientation().getValue3x3(bmo->data);
1875                         break;
1876                 case MATHUTILS_MAT_CB_ORI_GLOBAL:
1877                         self->NodeGetWorldOrientation().getValue3x3(bmo->data);
1878                         break;
1879         }
1880         
1881         return 0;
1882 }
1883
1884
1885 static int mathutils_kxgameob_matrix_set(BaseMathObject *bmo, int subtype)
1886 {
1887         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1888         if (self == NULL)
1889                 return -1;
1890         
1891         MT_Matrix3x3 mat3x3;
1892         switch (subtype) {
1893                 case MATHUTILS_MAT_CB_ORI_LOCAL:
1894                         mat3x3.setValue3x3(bmo->data);
1895                         self->NodeSetLocalOrientation(mat3x3);
1896                         self->NodeUpdateGS(0.f);
1897                         break;
1898                 case MATHUTILS_MAT_CB_ORI_GLOBAL:
1899                         mat3x3.setValue3x3(bmo->data);
1900                         self->NodeSetLocalOrientation(mat3x3);
1901                         self->NodeUpdateGS(0.f);
1902                         break;
1903         }
1904         
1905         return 0;
1906 }
1907
1908 static Mathutils_Callback mathutils_kxgameob_matrix_cb = {
1909         mathutils_kxgameob_generic_check,
1910         mathutils_kxgameob_matrix_get,
1911         mathutils_kxgameob_matrix_set,
1912         NULL,
1913         NULL
1914 };
1915
1916
1917 void KX_GameObject_Mathutils_Callback_Init(void)
1918 {
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);
1922 }
1923
1924 #endif // USE_MATHUTILS
1925
1926 #ifdef WITH_PYTHON
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},
1952
1953
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},
1959         
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),
1966
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),
1972         
1973         // dict style access for props
1974         {"get",(PyCFunction) KX_GameObject::sPyget, METH_VARARGS},
1975         
1976         {NULL,NULL} //Sentinel
1977 };
1978
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),
2023         
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),
2028         {NULL} //Sentinel
2029 };
2030
2031 PyObject *KX_GameObject::PyReplaceMesh(PyObject *args)
2032 {
2033         KX_Scene *scene = KX_GetActiveScene();
2034         
2035         PyObject *value;
2036         int use_gfx= 1, use_phys= 0;
2037         RAS_MeshObject *new_mesh;
2038         
2039         if (!PyArg_ParseTuple(args,"O|ii:replaceMesh", &value, &use_gfx, &use_phys))
2040                 return NULL;
2041         
2042         if (!ConvertPythonToMesh(value, &new_mesh, false, "gameOb.replaceMesh(value): KX_GameObject"))
2043                 return NULL;
2044         
2045         scene->ReplaceMesh(this, new_mesh, (bool)use_gfx, (bool)use_phys);
2046         Py_RETURN_NONE;
2047 }
2048
2049 PyObject *KX_GameObject::PyEndObject()
2050 {
2051         KX_Scene* scene = GetScene();
2052         
2053         scene->DelayedRemoveObject(this);
2054         
2055         Py_RETURN_NONE;
2056
2057 }
2058
2059 PyObject *KX_GameObject::PyReinstancePhysicsMesh(PyObject *args)
2060 {
2061         KX_GameObject *gameobj= NULL;
2062         RAS_MeshObject *mesh= NULL;
2063         
2064         PyObject *gameobj_py= NULL;
2065         PyObject *mesh_py= NULL;
2066
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"))
2070                 ) {
2071                 return NULL;
2072         }
2073
2074         /* gameobj and mesh can be NULL */
2075         if (GetPhysicsController() && GetPhysicsController()->ReinstancePhysicsShape(gameobj, mesh))
2076                 Py_RETURN_TRUE;
2077
2078         Py_RETURN_FALSE;
2079 }
2080
2081 static PyObject *Map_GetItem(PyObject *self_v, PyObject *item)
2082 {
2083         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
2084         const char *attr_str= _PyUnicode_AsString(item);
2085         CValue* resultattr;
2086         PyObject *pyconvert;
2087         
2088         if (self == NULL) {
2089                 PyErr_SetString(PyExc_SystemError, "val = gameOb[key]: KX_GameObject, " BGE_PROXY_ERROR_MSG);
2090                 return NULL;
2091         }
2092         
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();
2097         }
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))) {
2100                 
2101                 if (attr_str)
2102                         PyErr_Clear();
2103                 Py_INCREF(pyconvert);
2104                 return pyconvert;
2105         }
2106         else {
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");
2109                 return NULL;
2110         }
2111                 
2112 }
2113
2114
2115 static int Map_SetItem(PyObject *self_v, PyObject *key, PyObject *val)
2116 {
2117         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
2118         const char *attr_str= _PyUnicode_AsString(key);
2119         if (attr_str==NULL)
2120                 PyErr_Clear();
2121         
2122         if (self == NULL) {
2123                 PyErr_SetString(PyExc_SystemError, "gameOb[key] = value: KX_GameObject, " BGE_PROXY_ERROR_MSG);
2124                 return -1;
2125         }
2126         
2127         if (val==NULL) { /* del ob["key"] */
2128                 int del= 0;
2129                 
2130                 /* try remove both just in case */
2131                 if (attr_str)
2132                         del |= (self->RemoveProperty(attr_str)==true) ? 1:0;
2133                 
2134                 if (self->m_attr_dict)
2135                         del |= (PyDict_DelItem(self->m_attr_dict, key)==0) ? 1:0;
2136                 
2137                 if (del==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");
2140                         return -1;
2141                 }
2142                 else if (self->m_attr_dict) {
2143                         PyErr_Clear(); /* PyDict_DelItem sets an error when it fails */
2144                 }
2145         }
2146         else { /* ob["key"] = value */
2147                 bool set = false;
2148                 
2149                 /* as CValue */
2150                 if (attr_str && PyObject_TypeCheck(val, &PyObjectPlus::Type)==0) /* don't allow GameObjects for eg to be assigned to CValue props */
2151                 {
2152                         CValue *vallie = self->ConvertPythonToValue(val, false, "gameOb[key] = value: ");
2153                         
2154                         if (vallie) {
2155                                 CValue* oldprop = self->GetProperty(attr_str);
2156                                 
2157                                 if (oldprop)
2158                                         oldprop->SetValue(vallie);
2159                                 else
2160                                         self->SetProperty(attr_str, vallie);
2161                                 
2162                                 vallie->Release();
2163                                 set = true;
2164                                 
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)
2168                                                 PyErr_Clear();
2169                                 }
2170                         }
2171                         else if (PyErr_Occurred()) {
2172                                 return -1;
2173                         }
2174                 }
2175                 
2176                 if (set == false) {
2177                         if (self->m_attr_dict==NULL) /* lazy init */
2178                                 self->m_attr_dict= PyDict_New();
2179                         
2180                         
2181                         if (PyDict_SetItem(self->m_attr_dict, key, val)==0)
2182                         {
2183                                 if (attr_str)
2184                                         self->RemoveProperty(attr_str); /* overwrite the CValue if it exists */
2185                                 set = true;
2186                         }
2187                         else {
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");
2190                         }
2191                 }
2192                 
2193                 if (set == false) {
2194                         return -1; /* pythons error value */
2195                 }
2196                 
2197         }
2198         
2199         return 0; /* success */
2200 }
2201
2202 static int Seq_Contains(PyObject *self_v, PyObject *value)
2203 {
2204         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
2205         
2206         if (self == NULL) {
2207                 PyErr_SetString(PyExc_SystemError, "val in gameOb: KX_GameObject, " BGE_PROXY_ERROR_MSG);
2208                 return -1;
2209         }
2210         
2211         if (PyUnicode_Check(value) && self->GetProperty(_PyUnicode_AsString(value)))
2212                 return 1;
2213         
2214         if (self->m_attr_dict && PyDict_GetItem(self->m_attr_dict, value))
2215                 return 1;
2216         
2217         return 0;
2218 }
2219
2220
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 */
2225 };
2226
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 */
2231         NULL,           /* sq_item */
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 */
2238 };
2239
2240 PyTypeObject KX_GameObject::Type = {
2241         PyVarObject_HEAD_INIT(NULL, 0)
2242         "KX_GameObject",
2243         sizeof(PyObjectPlus_Proxy),
2244         0,
2245         py_base_dealloc,
2246         0,
2247         0,
2248         0,
2249         0,
2250         py_base_repr,
2251         0,
2252         &Sequence,
2253         &Mapping,
2254         0,0,0,
2255         NULL,
2256         NULL,
2257         0,
2258         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
2259         0,0,0,0,0,0,0,
2260         Methods,
2261         0,
2262         0,
2263         &SCA_IObject::Type,
2264         0,0,0,0,0,0,
2265         py_base_new
2266 };
2267
2268 PyObject *KX_GameObject::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2269 {
2270         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2271         return PyUnicode_From_STR_String(self->GetName());
2272 }
2273
2274 PyObject *KX_GameObject::pyattr_get_parent(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2275 {
2276         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2277         KX_GameObject* parent = self->GetParent();
2278         if (parent) {
2279                 return parent->GetProxy();
2280         }
2281         Py_RETURN_NONE;
2282 }
2283
2284 PyObject *KX_GameObject::pyattr_get_group_members(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2285 {
2286         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2287         CListValue* instances = self->GetInstanceObjects();
2288         if (instances) {
2289                 return instances->GetProxy();
2290         }
2291         Py_RETURN_NONE;
2292 }
2293
2294 PyObject* KX_GameObject::pyattr_get_collisionCallbacks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2295 {
2296         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2297
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");
2301                 return NULL;
2302         }
2303
2304         // Return the existing callbacks
2305         if (self->m_collisionCallbacks == NULL)
2306         {
2307                 self->m_collisionCallbacks = PyList_New(0);
2308                 // Subscribe to collision update from KX_TouchManager
2309                 self->RegisterCollisionCallbacks();
2310         }
2311         Py_INCREF(self->m_collisionCallbacks);
2312         return self->m_collisionCallbacks;
2313 }
2314
2315 int KX_GameObject::pyattr_set_collisionCallbacks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2316 {
2317         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2318
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;
2323         }
2324
2325         if (!PyList_CheckExact(value))
2326         {
2327                 PyErr_SetString(PyExc_ValueError, "Expected a list");
2328                 return PY_SET_ATTR_FAIL;
2329         }
2330
2331         if (self->m_collisionCallbacks == NULL) {
2332                 self->RegisterCollisionCallbacks();
2333         } else {
2334                 Py_DECREF(self->m_collisionCallbacks);
2335         }
2336
2337         Py_INCREF(value);
2338
2339
2340         self->m_collisionCallbacks = value;
2341
2342         return PY_SET_ATTR_SUCCESS;
2343 }
2344
2345 PyObject* KX_GameObject::pyattr_get_scene(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2346 {
2347         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
2348         KX_Scene *scene = self->GetScene();
2349         if (scene) {
2350                 return scene->GetProxy();
2351         }
2352         Py_RETURN_NONE;
2353 }
2354
2355 PyObject *KX_GameObject::pyattr_get_group_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2356 {
2357         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2358         KX_GameObject* pivot = self->GetDupliGroupObject();
2359         if (pivot) {
2360                 return pivot->GetProxy();
2361         }
2362         Py_RETURN_NONE;
2363 }
2364
2365 PyObject *KX_GameObject::pyattr_get_life(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2366 {
2367         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2368
2369         CValue *life = self->GetProperty("::timebomb");
2370         if (life)
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);
2374         else
2375                 Py_RETURN_NONE;
2376 }
2377
2378 PyObject *KX_GameObject::pyattr_get_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2379 {
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);
2383 }
2384
2385 int KX_GameObject::pyattr_set_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2386 {
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;
2393         }
2394
2395         if (spc)
2396                 spc->SetMass(val);
2397
2398         return PY_SET_ATTR_SUCCESS;
2399 }
2400
2401 PyObject *KX_GameObject::pyattr_get_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2402 {
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);
2406 }
2407
2408 int KX_GameObject::pyattr_set_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2409 {
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;
2416         }
2417
2418         if (spc)
2419                 spc->SetLinVelocityMin(val);
2420
2421         return PY_SET_ATTR_SUCCESS;
2422 }
2423
2424 PyObject *KX_GameObject::pyattr_get_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2425 {
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);
2429 }
2430
2431 int KX_GameObject::pyattr_set_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2432 {
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;
2439         }
2440
2441         if (spc)
2442                 spc->SetLinVelocityMax(val);
2443
2444         return PY_SET_ATTR_SUCCESS;
2445 }
2446
2447
2448 PyObject *KX_GameObject::pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2449 {
2450         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2451         return PyBool_FromLong(self->GetVisible());
2452 }
2453
2454 int KX_GameObject::pyattr_set_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2455 {
2456         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2457         int param = PyObject_IsTrue( value );
2458         if (param == -1) {
2459                 PyErr_SetString(PyExc_AttributeError, "gameOb.visible = bool: KX_GameObject, expected True or False");
2460                 return PY_SET_ATTR_FAIL;
2461         }
2462
2463         self->SetVisible(param, false);
2464         self->UpdateBuckets(false);
2465         return PY_SET_ATTR_SUCCESS;
2466 }
2467
2468 PyObject *KX_GameObject::pyattr_get_record_animation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2469 {
2470         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2471         return PyBool_FromLong(self->IsRecordAnimation());
2472 }
2473
2474 int KX_GameObject::pyattr_set_record_animation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2475 {
2476         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2477         int param = PyObject_IsTrue(value);
2478         if (param == -1) {
2479                 PyErr_SetString(PyExc_AttributeError, "gameOb.record_animation = bool: KX_GameObject, expected boolean");
2480                 return PY_SET_ATTR_FAIL;
2481         }
2482
2483         self->SetRecordAnimation(param);
2484
2485         return PY_SET_ATTR_SUCCESS;
2486 }
2487
2488
2489
2490 PyObject *KX_GameObject::pyattr_get_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2491 {
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);
2494 #else
2495         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2496         return PyObjectFrom(self->NodeGetWorldPosition());
2497 #endif
2498 }
2499
2500 int KX_GameObject::pyattr_set_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2501 {
2502         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2503         MT_Point3 pos;
2504         if (!PyVecTo(value, pos))
2505                 return PY_SET_ATTR_FAIL;
2506         
2507         self->NodeSetWorldPosition(pos);
2508         self->NodeUpdateGS(0.f);
2509         return PY_SET_ATTR_SUCCESS;
2510 }
2511
2512 PyObject *KX_GameObject::pyattr_get_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2513 {
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);
2516 #else
2517         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2518         return PyObjectFrom(self->NodeGetLocalPosition());
2519 #endif
2520 }
2521
2522 int KX_GameObject::pyattr_set_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2523 {
2524         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2525         MT_Point3 pos;
2526         if (!PyVecTo(value, pos))
2527                 return PY_SET_ATTR_FAIL;
2528         
2529         self->NodeSetLocalPosition(pos);
2530         self->NodeUpdateGS(0.f);
2531         return PY_SET_ATTR_SUCCESS;
2532 }
2533
2534 PyObject *KX_GameObject::pyattr_get_localInertia(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2535 {
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);
2538 #else
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);
2543 #endif
2544 }
2545
2546 PyObject *KX_GameObject::pyattr_get_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2547 {
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);
2550 #else
2551         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2552         return PyObjectFrom(self->NodeGetWorldOrientation());
2553 #endif
2554 }
2555
2556 int KX_GameObject::pyattr_set_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2557 {
2558         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2559         
2560         /* if value is not a sequence PyOrientationTo makes an error */
2561         MT_Matrix3x3 rot;
2562         if (!PyOrientationTo(value, rot, "gameOb.worldOrientation = sequence: KX_GameObject, "))
2563                 return PY_SET_ATTR_FAIL;
2564
2565         self->NodeSetGlobalOrientation(rot);
2566         
2567         self->NodeUpdateGS(0.f);
2568         return PY_SET_ATTR_SUCCESS;
2569 }
2570
2571 PyObject *KX_GameObject::pyattr_get_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2572 {
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);
2575 #else
2576         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2577         return PyObjectFrom(self->NodeGetLocalOrientation());
2578 #endif
2579 }
2580
2581 int KX_GameObject::pyattr_set_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2582 {
2583         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2584         
2585         /* if value is not a sequence PyOrientationTo makes an error */
2586         MT_Matrix3x3 rot;
2587         if (!PyOrientationTo(value, rot, "gameOb.localOrientation = sequence: KX_GameObject, "))
2588                 return PY_SET_ATTR_FAIL;
2589
2590         self->NodeSetLocalOrientation(rot);
2591         self->NodeUpdateGS(0.f);
2592         return PY_SET_ATTR_SUCCESS;
2593 }
2594
2595 PyObject *KX_GameObject::pyattr_get_worldScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2596 {
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);
2599 #else
2600         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2601         return PyObjectFrom(self->NodeGetWorldScaling());
2602 #endif
2603 }
2604
2605 int KX_GameObject::pyattr_set_worldScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2606 {
2607         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2608         MT_Vector3 scale;
2609         if (!PyVecTo(value, scale))
2610                 return PY_SET_ATTR_FAIL;
2611
2612         self->NodeSetWorldScale(scale);
2613         self->NodeUpdateGS(0.f);
2614         return PY_SET_ATTR_SUCCESS;
2615 }
2616
2617 PyObject *KX_GameObject::pyattr_get_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2618 {
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);
2621 #else
2622         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2623         return PyObjectFrom(self->NodeGetLocalScaling());
2624 #endif
2625 }
2626
2627 int KX_GameObject::pyattr_set_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2628 {
2629         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2630         MT_Vector3 scale;
2631         if (!PyVecTo(value, scale))
2632                 return PY_SET_ATTR_FAIL;
2633
2634         self->NodeSetLocalScale(scale);
2635         self->NodeUpdateGS(0.f);
2636         return PY_SET_ATTR_SUCCESS;
2637 }
2638
2639 PyObject *KX_GameObject::pyattr_get_localTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2640 {
2641         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2642
2643         double mat[16];
2644
2645         MT_Transform trans;
2646         
2647         trans.setOrigin(self->GetSGNode()->GetLocalPosition());
2648         trans.setBasis(self->GetSGNode()->GetLocalOrientation());
2649         
2650         MT_Vector3 scaling = self->GetSGNode()->GetLocalScale();
2651         trans.scale(scaling[0], scaling[1], scaling[2]);
2652
2653         trans.getValue(mat);
2654
2655         return PyObjectFrom(MT_Matrix4x4(mat));
2656 }
2657
2658 int KX_GameObject::pyattr_set_localTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2659 {
2660         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2661         MT_Matrix4x4 temp;
2662         if (!PyMatTo(value, temp))
2663                 return PY_SET_ATTR_FAIL;
2664
2665         float transform[4][4];
2666         float loc[3], size[3];
2667         float rot[3][3];
2668         MT_Matrix3x3 orientation;
2669
2670         temp.getValue(*transform);
2671         mat4_to_loc_rot_size(loc, rot, size, transform);
2672
2673         self->NodeSetLocalPosition(MT_Point3(loc));
2674
2675         //MT_Matrix3x3's constructor expects a 4x4 matrix
2676         orientation = MT_Matrix3x3();
2677         orientation.setValue3x3(*rot);
2678         self->NodeSetLocalOrientation(orientation);
2679
2680         self->NodeSetLocalScale(MT_Vector3(size));
2681
2682         return PY_SET_ATTR_SUCCESS;
2683 }
2684
2685 PyObject *KX_GameObject::pyattr_get_worldTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2686 {
2687         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2688
2689         return PyObjectFrom(MT_Matrix4x4(self->GetOpenGLMatrix()));
2690 }
2691
2692 int KX_GameObject::pyattr_set_worldTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2693 {
2694         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2695         MT_Matrix4x4 temp;
2696         if (!PyMatTo(value, temp))
2697                 return PY_SET_ATTR_FAIL;
2698
2699         float transform[4][4];
2700         float loc[3], size[3];
2701         float rot[3][3];
2702         MT_Matrix3x3 orientation;
2703
2704         temp.getValue(*transform);
2705         mat4_to_loc_rot_size(loc, rot, size, transform);
2706
2707         self->NodeSetWorldPosition(MT_Point3(loc));
2708
2709         //MT_Matrix3x3's constructor expects a 4x4 matrix
2710         orientation = MT_Matrix3x3();
2711         orientation.setValue3x3(*rot);
2712         self->NodeSetGlobalOrientation(orientation);
2713
2714         self->NodeSetWorldScale(MT_Vector3(size));
2715
2716         return PY_SET_ATTR_SUCCESS;
2717 }
2718
2719 PyObject *KX_GameObject::pyattr_get_worldLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2720 {
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);
2723 #else
2724         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2725         return PyObjectFrom(GetLinearVelocity(false));
2726 #endif
2727 }
2728
2729 int KX_GameObject::pyattr_set_worldLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2730 {
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;
2735
2736         self->setLinearVelocity(velocity, false);
2737
2738         return PY_SET_ATTR_SUCCESS;
2739 }
2740
2741 PyObject *KX_GameObject::pyattr_get_localLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2742 {
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);
2745 #else
2746         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2747         return PyObjectFrom(GetLinearVelocity(true));
2748 #endif
2749 }
2750
2751 int KX_GameObject::pyattr_set_localLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2752 {
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;
2757
2758         self->setLinearVelocity(velocity, true);
2759
2760         return PY_SET_ATTR_SUCCESS;
2761 }
2762
2763 PyObject *KX_GameObject::pyattr_get_worldAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2764 {
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);
2767 #else
2768         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2769         return PyObjectFrom(GetAngularVelocity(false));
2770 #endif
2771 }
2772
2773 int KX_GameObject::pyattr_set_worldAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2774 {
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;
2779
2780         self->setAngularVelocity(velocity, false);
2781
2782         return PY_SET_ATTR_SUCCESS;
2783 }
2784
2785 PyObject *KX_GameObject::pyattr_get_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2786 {
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);
2789 #else
2790         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2791         return PyObjectFrom(GetAngularVelocity(true));
2792 #endif
2793 }
2794
2795 int KX_GameObject::pyattr_set_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2796 {
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;
2801
2802         self->setAngularVelocity(velocity, true);
2803
2804         return PY_SET_ATTR_SUCCESS;
2805 }
2806
2807 PyObject *KX_GameObject::pyattr_get_linearDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2808 {
2809         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2810         return PyFloat_FromDouble(self->getLinearDamping());
2811 }
2812
2813 int KX_GameObject::pyattr_set_linearDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2814 {
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;
2819 }
2820
2821 PyObject *KX_GameObject::pyattr_get_angularDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2822 {
2823         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2824         return PyFloat_FromDouble(self->getAngularDamping());
2825 }
2826
2827 int KX_GameObject::pyattr_set_angularDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2828 {
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;
2833 }
2834
2835
2836 PyObject *KX_GameObject::pyattr_get_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2837 {
2838         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2839         SG_Node* sg_parent;
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());
2842         } else {
2843                 return PyFloat_FromDouble(0.0);
2844         }
2845 }
2846
2847 int KX_GameObject::pyattr_set_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2848 {
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;
2856                 }
2857                 if (sg_parent && sg_parent->IsSlowParent())
2858                         static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->SetTimeOffset(val);
2859         }
2860         return PY_SET_ATTR_SUCCESS;
2861 }
2862
2863 PyObject *KX_GameObject::pyattr_get_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2864 {
2865         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2866         int state = 0;
2867         state |= self->GetState();
2868         return PyLong_FromLong(state);
2869 }
2870
2871 int KX_GameObject::pyattr_set_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2872 {
2873         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2874         int state_i = PyLong_AsLong(value);
2875         unsigned int state = 0;
2876         
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;
2880         }
2881         
2882         state |= state_i;
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;
2886         }
2887         self->SetState(state);
2888         return PY_SET_ATTR_SUCCESS;
2889 }
2890
2891 PyObject *KX_GameObject::pyattr_get_meshes(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2892 {
2893         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2894         PyObject *meshes= PyList_New(self->m_meshes.size());
2895         int i;
2896         
2897         for (i=0; i < (int)self->m_meshes.size(); i++)
2898         {
2899                 KX_MeshProxy* meshproxy = new KX_MeshProxy(self->m_meshes[i]);
2900                 PyList_SET_ITEM(meshes, i, meshproxy->NewProxy(true));
2901         }
2902         
2903         return meshes;
2904 }
2905
2906 PyObject *KX_GameObject::pyattr_get_obcolor(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2907 {
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);
2910 #else
2911         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2912         return PyObjectFrom(self->GetObjectColor());
2913 #endif
2914 }
2915
2916 int KX_GameObject::pyattr_set_obcolor(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2917 {
2918         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2919         MT_Vector4 obcolor;
2920         if (!PyVecTo(value, obcolor))
2921                 return PY_SET_ATTR_FAIL;
2922
2923         self->SetObjectColor(obcolor);
2924         return PY_SET_ATTR_SUCCESS;
2925 }
2926
2927 /* These are experimental! */
2928 PyObject *KX_GameObject::pyattr_get_sensors(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2929 {
2930         return KX_PythonSeq_CreatePyObject((static_cast<KX_GameObject*>(self_v))->m_proxy, KX_PYGENSEQ_OB_TYPE_SENSORS);
2931 }
2932
2933 PyObject *KX_GameObject::pyattr_get_controllers(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2934 {
2935         return KX_PythonSeq_CreatePyObject((static_cast<KX_GameObject*>(self_v))->m_proxy, KX_PYGENSEQ_OB_TYPE_CONTROLLERS);
2936 }
2937
2938 PyObject *KX_GameObject::pyattr_get_actuators(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2939 {
2940         return KX_PythonSeq_CreatePyObject((static_cast<KX_GameObject*>(self_v))->m_proxy, KX_PYGENSEQ_OB_TYPE_ACTUATORS);
2941 }
2942 /* End experimental */
2943
2944 PyObject *KX_GameObject::pyattr_get_children(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2945 {
2946         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2947         return self->GetChildren()->NewProxy(true);
2948 }
2949
2950 PyObject *KX_GameObject::pyattr_get_children_recursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2951 {
2952         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2953         return self->GetChildrenRecursive()->NewProxy(true);
2954 }
2955
2956 PyObject *KX_GameObject::pyattr_get_attrDict(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2957 {
2958         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2959         
2960         if (self->m_attr_dict==NULL)
2961                 self->m_attr_dict= PyDict_New();
2962         
2963         Py_INCREF(self->m_attr_dict);
2964         return self->m_attr_dict;
2965 }
2966
2967 PyObject *KX_GameObject::pyattr_get_debug(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2968 {
2969         KX_Scene *scene = KX_GetActiveScene();
2970         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
2971
2972         return PyBool_FromLong(scene->ObjectInDebugList(self));
2973 }
2974
2975 int KX_GameObject::pyattr_set_debug(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2976 {
2977         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
2978         int param = PyObject_IsTrue(value);
2979
2980         if (param == -1) {
2981                 PyErr_SetString(PyExc_AttributeError, "gameOb.debug = bool: KX_GameObject, expected True or False");
2982                 return PY_SET_ATTR_FAIL;
2983         }
2984
2985         self->SetUseDebugProperties(param, false);
2986
2987         return PY_SET_ATTR_SUCCESS;
2988 }
2989
2990 PyObject *KX_GameObject::pyattr_get_debugRecursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2991 {
2992         KX_Scene *scene = KX_GetActiveScene();
2993         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
2994
2995         return PyBool_FromLong(scene->ObjectInDebugList(self));
2996 }
2997
2998 int KX_GameObject::pyattr_set_debugRecursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2999 {
3000         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
3001         int param = PyObject_IsTrue(value);
3002
3003         if (param == -1) {
3004                 PyErr_SetString(PyExc_AttributeError, "gameOb.debugRecursive = bool: KX_GameObject, expected True or False");
3005                 return PY_SET_ATTR_FAIL;
3006         }
3007
3008         self->SetUseDebugProperties(param, true);
3009
3010         return PY_SET_ATTR_SUCCESS;
3011 }
3012
3013 PyObject *KX_GameObject::PyApplyForce(PyObject *args)
3014 {
3015         int local = 0;
3016         PyObject *pyvect;
3017
3018         if (PyArg_ParseTuple(args, "O|i:applyForce", &pyvect, &local)) {
3019                 MT_Vector3 force;
3020                 if (PyVecTo(pyvect, force)) {
3021                         ApplyForce(force, (local!=0));
3022                         Py_RETURN_NONE;
3023                 }
3024         }
3025         return NULL;
3026 }
3027
3028 PyObject *KX_GameObject::PyApplyTorque(PyObject *args)
3029 {
3030         int local = 0;
3031         PyObject *pyvect;
3032
3033         if (PyArg_ParseTuple(args, "O|i:applyTorque", &pyvect, &local)) {
3034                 MT_Vector3 torque;
3035                 if (PyVecTo(pyvect, torque)) {
3036                         ApplyTorque(torque, (local!=0));
3037                         Py_RETURN_NONE;
3038                 }
3039         }
3040         return NULL;
3041 }
3042
3043 PyObject *KX_GameObject::PyApplyRotation(PyObject *args)
3044 {
3045         int local = 0;
3046         PyObject *pyvect;
3047
3048         if (PyArg_ParseTuple(args, "O|i:applyRotation", &pyvect, &local)) {
3049                 MT_Vector3 rotation;
3050                 if (PyVecTo(pyvect, rotation)) {
3051                         ApplyRotation(rotation, (local!=0));
3052                         Py_RETURN_NONE;
3053                 }
3054         }
3055         return NULL;
3056 }
3057
3058 PyObject *KX_GameObject::PyApplyMovement(PyObject *args)
3059 {
3060         int local = 0;
3061         PyObject *pyvect;
3062
3063         if (PyArg_ParseTuple(args, "O|i:applyMovement", &pyvect, &local)) {
3064                 MT_Vector3 movement;
3065                 if (PyVecTo(pyvect, movement)) {
3066                         ApplyMovement(movement, (local!=0));
3067                         Py_RETURN_NONE;
3068                 }
3069         }
3070         return NULL;
3071 }
3072
3073 PyObject *KX_GameObject::PyGetLinearVelocity(PyObject *args)
3074 {
3075         // only can get the velocity if we have a physics object connected to us...
3076         int local = 0;
3077         if (PyArg_ParseTuple(args,"|i:getLinearVelocity",&local))
3078         {
3079                 return PyObjectFrom(GetLinearVelocity((local!=0)));
3080         }
3081         else
3082         {
3083                 return NULL;
3084         }
3085 }
3086
3087 PyObject *KX_GameObject::PySetLinearVelocity(PyObject *args)
3088 {
3089         int local = 0;
3090         PyObject *pyvect;
3091         
3092         if (PyArg_ParseTuple(args,"O|i:setLinearVelocity",&pyvect,&local)) {
3093                 MT_Vector3 velocity;
3094                 if (PyVecTo(pyvect, velocity)) {
3095                         setLinearVelocity(velocity, (local!=0));
3096                         Py_RETURN_NONE;
3097                 }
3098         }
3099         return NULL;
3100 }
3101
3102 PyObject *KX_GameObject::PyGetAngularVelocity(PyObject *args)
3103 {
3104         // only can get the velocity if we have a physics object connected to us...
3105         int local = 0;
3106         if (PyArg_ParseTuple(args,"|i:getAngularVelocity",&local))
3107         {
3108                 return PyObjectFrom(GetAngularVelocity((local!=0)));
3109         }
3110         else
3111         {
3112                 return NULL;
3113         }
3114 }
3115
3116 PyObject *KX_GameObject::PySetAngularVelocity(PyObject *args)
3117 {
3118         int local = 0;
3119         PyObject *pyvect;
3120         
3121         if (PyArg_ParseTuple(args,"O|i:setAngularVelocity",&pyvect,&local)) {
3122                 MT_Vector3 velocity;
3123                 if (PyVecTo(pyvect, velocity)) {
3124                         setAngularVelocity(velocity, (local!=0));
3125                         Py_RETURN_NONE;
3126                 }
3127         }
3128         return NULL;
3129 }
3130
3131 PyObject *KX_GameObject::PySetDamping(PyObject *args)
3132 {
3133         float linear;
3134         float angular;
3135
3136         if (!PyArg_ParseTuple(args,"ff|i:setDamping", &linear, &angular))
3137                 return NULL;
3138
3139         setDamping(linear, angular);
3140         Py_RETURN_NONE;
3141 }
3142
3143 PyObject *KX_GameObject::PySetVisible(PyObject *args)
3144 {
3145         int visible, recursive = 0;
3146         if (!PyArg_ParseTuple(args,"i|i:setVisible",&visible, &recursive))
3147                 return NULL;
3148         
3149         SetVisible(visible ? true:false, recursive ? true:false);
3150         UpdateBuckets(recursive ? true:false);
3151         Py_RETURN_NONE;
3152         
3153 }
3154
3155 PyObject *KX_GameObject::PySetOcclusion(PyObject *args)
3156 {
3157         int occlusion, recursive = 0;
3158         if (!PyArg_ParseTuple(args,"i|i:setOcclusion",&occlusion, &recursive))
3159                 return NULL;
3160         
3161         SetOccluder(occlusion ? true:false, recursive ? true:false);
3162         Py_RETURN_NONE;
3163 }
3164
3165 PyObject *KX_GameObject::PyGetVelocity(PyObject *args)
3166 {
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;
3170         
3171         if (!PyArg_ParseTuple(args, "|O:getVelocity", &pypos) || (pypos && !PyVecTo(pypos, point)))
3172                 return NULL;
3173
3174         return PyObjectFrom(GetVelocity(point));
3175 }
3176
3177 PyObject *KX_GameObject::PyGetReactionForce()
3178 {
3179         // only can get the velocity if we have a physics object connected to us...
3180         
3181         // XXX - Currently not working with bullet intergration, see KX_BulletPhysicsController.cpp's getReactionForce
3182 #if 0
3183         if (GetPhysicsController1())
3184                 return PyObjectFrom(GetPhysicsController1()->getReactionForce());
3185         return PyObjectFrom(dummy_point);
3186 #endif
3187         
3188         return Py_BuildValue("fff", 0.0, 0.0, 0.0);
3189         
3190 }
3191
3192
3193
3194 PyObject *KX_GameObject::PyEnableRigidBody()
3195 {
3196         if (GetPhysicsController())
3197                 GetPhysicsController()->SetRigidBody(true);
3198
3199         Py_RETURN_NONE;
3200 }
3201
3202
3203
3204 PyObject *KX_GameObject::PyDisableRigidBody()
3205 {
3206         if (GetPhysicsController())
3207                 GetPhysicsController()->SetRigidBody(false);
3208
3209         Py_RETURN_NONE;
3210 }
3211
3212
3213 PyObject *KX_GameObject::PySetParent(PyObject *args)
3214 {
3215         KX_Scene *scene = KX_GetActiveScene();
3216         PyObject *pyobj;
3217         KX_GameObject *obj;
3218         int addToCompound=1, ghost=1;
3219         
3220         if (!PyArg_ParseTuple(args,"O|ii:setParent", &pyobj, &addToCompound, &ghost)) {
3221                 return NULL; // Python sets a simple error
3222         }
3223         if (!ConvertPythonToGameObject(pyobj, &obj, true, "gameOb.setParent(obj): KX_GameObject"))
3224                 return NULL;
3225         if (obj)
3226                 this->SetParent(scene, obj, addToCompound, ghost);
3227         Py_RETURN_NONE;
3228 }
3229
3230 PyObject *KX_GameObject::PyRemoveParent()
3231 {
3232         KX_Scene *scene = KX_GetActiveScene();
3233         
3234         this->RemoveParent(scene);
3235         Py_RETURN_NONE;
3236 }
3237
3238
3239 PyObject *KX_GameObject::PySetCollisionMargin(PyObject *value)
3240 {
3241         float collisionMargin = PyFloat_AsDouble(value);
3242         
3243         if (collisionMargin==-1 && PyErr_Occurred()) {
3244                 PyErr_SetString(PyExc_TypeError, "expected a float");
3245                 return NULL;
3246         }
3247         
3248         if (m_pPhysicsController)
3249         {
3250                 m_pPhysicsController->SetMargin(collisionMargin);
3251                 Py_RETURN_NONE;
3252         }
3253         PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller");
3254         return NULL;
3255 }
3256
3257
3258
3259 PyObject *KX_GameObject::PyApplyImpulse(PyObject *args)
3260 {
3261         PyObject *pyattach;
3262         PyObject *pyimpulse;
3263         int local = 0;
3264         
3265         if (!m_pPhysicsController)      {
3266                 PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller");
3267                 return NULL;
3268         }
3269         
3270         if (PyArg_ParseTuple(args, "OO|i:applyImpulse", &pyattach, &pyimpulse, &local))
3271         {
3272                 MT_Point3  attach;
3273                 MT_Vector3 impulse;
3274                 if (PyVecTo(pyattach, attach) && PyVecTo(pyimpulse, impulse))
3275                 {
3276                         m_pPhysicsController->ApplyImpulse(attach, impulse, (local!=0));
3277                         Py_RETURN_NONE;
3278                 }
3279
3280         }
3281         
3282         return NULL;
3283 }
3284
3285
3286
3287 PyObject *KX_GameObject::PySuspendDynamics()
3288 {
3289         if (GetPhysicsController())
3290                 GetPhysicsController()->SuspendDynamics();
3291         Py_RETURN_NONE;
3292 }
3293
3294
3295
3296 PyObject *KX_GameObject::PyRestoreDynamics()
3297 {
3298         if (GetPhysicsController())
3299                 GetPhysicsController()->RestoreDynamics();
3300         Py_RETURN_NONE;
3301 }
3302
3303
3304 PyObject *KX_GameObject::PyAlignAxisToVect(PyObject *args)
3305 {
3306         PyObject *pyvect;
3307         int axis = 2; //z axis is the default
3308         float fac = 1.0f;
3309         
3310         if (PyArg_ParseTuple(args,"O|if:alignAxisToVect",&pyvect,&axis, &fac))
3311         {
3312                 MT_Vector3 vect;
3313                 if (PyVecTo(pyvect, vect)) {
3314                         if (fac > 0.0f) {
3315                                 if (fac> 1.0f) fac = 1.0f;
3316
3317                                 AlignAxisToVect(vect, axis, fac);
3318                                 NodeUpdateGS(0.f);
3319                         }
3320                         Py_RETURN_NONE;
3321                 }
3322         }
3323         return NULL;
3324 }
3325
3326 PyObject *KX_GameObject::PyGetAxisVect(PyObject *value)
3327 {
3328         MT_Vector3 vect;
3329         if (PyVecTo(value, vect))
3330         {
3331                 return PyObjectFrom(NodeGetWorldOrientation() * vect);
3332         }
3333         return NULL;
3334 }
3335
3336
3337 PyObject *KX_GameObject::PyGetPhysicsId()
3338 {
3339         PHY_IPhysicsController* ctrl = GetPhysicsController();
3340         unsigned long long physid = 0;
3341         if (ctrl)
3342         {
3343                 physid = (unsigned long long)ctrl;
3344         }
3345         return PyLong_FromUnsignedLongLong(physid);
3346 }
3347
3348 PyObject *KX_GameObject::PyGetPropertyNames()
3349 {
3350         PyObject *list= ConvertKeysToPython();
3351         
3352         if (m_attr_dict) {
3353                 PyObject *key, *value;
3354                 Py_ssize_t pos = 0;
3355
3356                 while (PyDict_Next(m_attr_dict, &pos, &key, &value)) {
3357                         PyList_Append(list, key);
3358                 }
3359         }
3360         return list;
3361 }
3362
3363 KX_PYMETHODDEF_DOC_O(KX_GameObject, getDistanceTo,
3364 "getDistanceTo(other): get distance to another point/KX_GameObject")
3365 {
3366         MT_Point3 b;
3367         if (PyVecTo(value, b))
3368         {
3369                 return PyFloat_FromDouble(NodeGetWorldPosition().distance(b));
3370         }
3371         PyErr_Clear();
3372         
3373         KX_GameObject *other;
3374         if (ConvertPythonToGameObject(value, &other, false, "gameOb.getDistanceTo(value): KX_GameObject"))
3375         {
3376                 return PyFloat_FromDouble(NodeGetWorldPosition().distance(other->NodeGetWorldPosition()));
3377         }
3378         
3379         return NULL;
3380 }
3381
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")
3385 {
3386         MT_Point3 toPoint, fromPoint;
3387         MT_Vector3 toDir, locToDir;
3388         MT_Scalar distance;
3389
3390         PyObject *returnValue;
3391