BGE: Added getActionName() function to KX_GameObject()
[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 <climits> // USHRT_MAX
51 #include "SG_Controller.h"
52 #include "PHY_IGraphicController.h"
53 #include "SG_Node.h"
54 #include "KX_ClientObjectInfo.h"
55 #include "RAS_BucketManager.h"
56 #include "KX_RayCast.h"
57 #include "KX_PythonInit.h"
58 #include "KX_PyMath.h"
59 #include "KX_PythonSeq.h"
60 #include "SCA_IActuator.h"
61 #include "SCA_ISensor.h"
62 #include "SCA_IController.h"
63 #include "NG_NetworkScene.h" //Needed for sendMessage()
64 #include "KX_ObstacleSimulation.h"
65 #include "KX_Scene.h"
66
67 #include "BKE_object.h"
68
69 #include "BL_ActionManager.h"
70 #include "BL_Action.h"
71
72 #include "EXP_PyObjectPlus.h" /* python stuff */
73 #include "BLI_utildefines.h"
74
75 #ifdef WITH_PYTHON
76 #  include "EXP_PythonCallBack.h"
77 #  include "python_utildefines.h"
78 #endif
79
80 // This file defines relationships between parents and children
81 // in the game engine.
82
83 #include "KX_SG_NodeRelationships.h"
84
85 #include "BLI_math.h"
86
87 static MT_Point3 dummy_point= MT_Point3(0.0, 0.0, 0.0);
88 static MT_Vector3 dummy_scaling = MT_Vector3(1.0, 1.0, 1.0);
89 static MT_Matrix3x3 dummy_orientation = MT_Matrix3x3(1.0, 0.0, 0.0,
90                                                      0.0, 1.0, 0.0,
91                                                      0.0, 0.0, 1.0);
92
93 KX_GameObject::KX_GameObject(
94         void* sgReplicationInfo,
95         SG_Callbacks callbacks)
96     : SCA_IObject(),
97       m_bDyna(false),
98       m_layer(0),
99       m_currentLodLevel(0),
100       m_previousLodLevel(0),
101       m_pBlenderObject(NULL),
102       m_pBlenderGroupObject(NULL),
103       m_bUseObjectColor(false),
104       m_bIsNegativeScaling(false),
105       m_objectColor(1.0, 1.0, 1.0, 1.0),
106       m_bVisible(true),
107       m_bCulled(true),
108       m_bOccluder(false),
109       m_pPhysicsController(NULL),
110       m_pGraphicController(NULL),
111       m_xray(false),
112       m_pHitObject(NULL),
113       m_pObstacleSimulation(NULL),
114       m_pInstanceObjects(NULL),
115       m_pDupliGroupObject(NULL),
116       m_actionManager(NULL),
117       m_bRecordAnimation(false),
118       m_isDeformable(false)
119
120 #ifdef WITH_PYTHON
121     , m_attr_dict(NULL),
122     m_collisionCallbacks(NULL)
123 #endif
124 {
125         m_ignore_activity_culling = false;
126         m_pClient_info = new KX_ClientObjectInfo(this, KX_ClientObjectInfo::ACTOR);
127         m_pSGNode = new SG_Node(this,sgReplicationInfo,callbacks);
128
129         // define the relationship between this node and it's parent.
130         
131         KX_NormalParentRelation * parent_relation = 
132                 KX_NormalParentRelation::New();
133         m_pSGNode->SetParentRelation(parent_relation);
134 };
135
136
137
138 KX_GameObject::~KX_GameObject()
139 {
140 #ifdef WITH_PYTHON
141         if (m_attr_dict) {
142                 PyDict_Clear(m_attr_dict); /* in case of circular refs or other weird cases */
143                 /* Py_CLEAR: Py_DECREF's and NULL's */
144                 Py_CLEAR(m_attr_dict);
145         }
146         // Unregister collision callbacks
147         // Do this before we start freeing physics information like m_pClient_info
148         if (m_collisionCallbacks){
149                 UnregisterCollisionCallbacks();
150                 Py_CLEAR(m_collisionCallbacks);
151         }
152 #endif // WITH_PYTHON
153
154         RemoveMeshes();
155
156         // is this delete somewhere ?
157         //if (m_sumoObj)
158         //      delete m_sumoObj;
159         delete m_pClient_info;
160         //if (m_pSGNode)
161         //      delete m_pSGNode;
162         if (m_pSGNode)
163         {
164                 // must go through controllers and make sure they will not use us anymore
165                 // This is important for KX_BulletPhysicsControllers that unregister themselves
166                 // from the object when they are deleted.
167                 SGControllerList::iterator contit;
168                 SGControllerList& controllers = m_pSGNode->GetSGControllerList();
169                 for (contit = controllers.begin();contit!=controllers.end();++contit)
170                 {
171                         (*contit)->ClearObject();
172                 }
173                 m_pSGNode->SetSGClientObject(NULL);
174
175                 /* m_pSGNode is freed in KX_Scene::RemoveNodeDestructObject */
176         }
177         if (m_pGraphicController)
178         {
179                 delete m_pGraphicController;
180         }
181
182         if (m_pPhysicsController)
183         {
184                 delete m_pPhysicsController;
185         }
186
187         if (m_pObstacleSimulation)
188         {
189                 m_pObstacleSimulation->DestroyObstacleForObj(this);
190         }
191
192         if (m_actionManager)
193         {
194                 delete m_actionManager;
195         }
196
197         if (m_pDupliGroupObject)
198         {
199                 m_pDupliGroupObject->Release();
200         }
201
202         if (m_pInstanceObjects)
203         {
204                 m_pInstanceObjects->Release();
205         }
206 }
207
208 KX_GameObject* KX_GameObject::GetClientObject(KX_ClientObjectInfo *info)
209 {
210         if (!info)
211                 return NULL;
212         return info->m_gameobject;
213 }
214
215 CValue* KX_GameObject:: Calc(VALUE_OPERATOR op, CValue *val) 
216 {
217         return NULL;
218 }
219
220
221
222 CValue* KX_GameObject::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val)
223 {
224         return NULL;
225 }
226
227
228
229 const STR_String & KX_GameObject::GetText()
230 {
231         return m_text;
232 }
233
234
235
236 double KX_GameObject::GetNumber()
237 {
238         return 0;
239 }
240
241
242
243 STR_String& KX_GameObject::GetName()
244 {
245         return m_name;
246 }
247
248
249 /* Set the name of the value */
250 void KX_GameObject::SetName(const char *name)
251 {
252         m_name = name;
253 }
254
255 PHY_IPhysicsController* KX_GameObject::GetPhysicsController()
256 {
257         return m_pPhysicsController;
258 }
259
260 KX_GameObject* KX_GameObject::GetDupliGroupObject()
261
262         return m_pDupliGroupObject;
263 }
264
265 CListValue* KX_GameObject::GetInstanceObjects()
266
267         return m_pInstanceObjects;
268 }
269
270 void KX_GameObject::AddInstanceObjects(KX_GameObject* obj)
271 {
272         if (!m_pInstanceObjects)
273                 m_pInstanceObjects = new CListValue();
274
275         obj->AddRef();
276         m_pInstanceObjects->Add(obj);
277 }
278
279 void KX_GameObject::RemoveInstanceObject(KX_GameObject* obj)
280 {
281         assert(m_pInstanceObjects);
282         m_pInstanceObjects->RemoveValue(obj);
283         obj->Release();
284 }
285
286 void KX_GameObject::RemoveDupliGroupObject()
287 {
288         if (m_pDupliGroupObject) {
289                 m_pDupliGroupObject->Release();
290                 m_pDupliGroupObject = NULL;
291         }
292 }
293
294 void KX_GameObject::SetDupliGroupObject(KX_GameObject* obj)
295 {
296         obj->AddRef();
297         m_pDupliGroupObject = obj;
298 }
299
300 void KX_GameObject::AddConstraint(bRigidBodyJointConstraint *cons)
301 {
302         m_constraints.push_back(cons);
303 }
304
305 std::vector<bRigidBodyJointConstraint*> KX_GameObject::GetConstraints()
306 {
307         return m_constraints;
308 }
309
310 void KX_GameObject::ClearConstraints()
311 {
312         m_constraints.clear();
313 }
314
315 KX_GameObject* KX_GameObject::GetParent()
316 {
317         KX_GameObject* result = NULL;
318         SG_Node* node = m_pSGNode;
319         
320         while (node && !result)
321         {
322                 node = node->GetSGParent();
323                 if (node)
324                         result = (KX_GameObject*)node->GetSGClientObject();
325         }
326
327         return result;
328         
329 }
330
331 void KX_GameObject::SetParent(KX_Scene *scene, KX_GameObject* obj, bool addToCompound, bool ghost)
332 {
333         // check on valid node in case a python controller holds a reference to a deleted object
334         if (obj && 
335                 GetSGNode() &&                  // object is not zombi
336                 obj->GetSGNode() &&             // object is not zombi
337                 GetSGNode()->GetSGParent() != obj->GetSGNode() &&       // not already parented to same object
338                 !GetSGNode()->IsAncessor(obj->GetSGNode()) &&           // no parenting loop
339                 this != obj)                                                                            // not the object itself
340         {
341                 // Make sure the objects have some scale
342                 MT_Vector3 scale1 = NodeGetWorldScaling();
343                 MT_Vector3 scale2 = obj->NodeGetWorldScaling();
344                 if (fabs(scale2[0]) < (MT_Scalar)FLT_EPSILON ||
345                         fabs(scale2[1]) < (MT_Scalar)FLT_EPSILON ||
346                         fabs(scale2[2]) < (MT_Scalar)FLT_EPSILON ||
347                         fabs(scale1[0]) < (MT_Scalar)FLT_EPSILON ||
348                         fabs(scale1[1]) < (MT_Scalar)FLT_EPSILON ||
349                         fabs(scale1[2]) < (MT_Scalar)FLT_EPSILON) { return; }
350
351                 // Remove us from our old parent and set our new parent
352                 RemoveParent(scene);
353                 obj->GetSGNode()->AddChild(GetSGNode());
354
355                 if (m_pPhysicsController)
356                 {
357                         m_pPhysicsController->SuspendDynamics(ghost);
358                 }
359                 // Set us to our new scale, position, and orientation
360                 scale2[0] = 1.0/scale2[0];
361                 scale2[1] = 1.0/scale2[1];
362                 scale2[2] = 1.0/scale2[2];
363                 scale1 = scale1 * scale2;
364                 MT_Matrix3x3 invori = obj->NodeGetWorldOrientation().inverse();
365                 MT_Vector3 newpos = invori*(NodeGetWorldPosition()-obj->NodeGetWorldPosition())*scale2;
366
367                 NodeSetLocalScale(scale1);
368                 NodeSetLocalPosition(MT_Point3(newpos[0],newpos[1],newpos[2]));
369                 NodeSetLocalOrientation(invori*NodeGetWorldOrientation());
370                 NodeUpdateGS(0.f);
371                 // object will now be a child, it must be removed from the parent list
372                 CListValue* rootlist = scene->GetRootParentList();
373                 if (rootlist->RemoveValue(this))
374                         // the object was in parent list, decrement ref count as it's now removed
375                         Release();
376                 // if the new parent is a compound object, add this object shape to the compound shape.
377                 // step 0: verify this object has physical controller
378                 if (m_pPhysicsController && addToCompound)
379                 {
380                         // step 1: find the top parent (not necessarily obj)
381                         KX_GameObject* rootobj = (KX_GameObject*)obj->GetSGNode()->GetRootSGParent()->GetSGClientObject();
382                         // step 2: verify it has a physical controller and compound shape
383                         if (rootobj != NULL && 
384                                 rootobj->m_pPhysicsController != NULL &&
385                                 rootobj->m_pPhysicsController->IsCompound())
386                         {
387                                 rootobj->m_pPhysicsController->AddCompoundChild(m_pPhysicsController);
388                         }
389                 }
390                 // graphically, the object hasn't change place, no need to update m_pGraphicController
391         }
392 }
393
394 void KX_GameObject::RemoveParent(KX_Scene *scene)
395 {
396         // check on valid node in case a python controller holds a reference to a deleted object
397         if (GetSGNode() && GetSGNode()->GetSGParent())
398         {
399                 // get the root object to remove us from compound object if needed
400                 KX_GameObject* rootobj = (KX_GameObject*)GetSGNode()->GetRootSGParent()->GetSGClientObject();
401                 // Set us to the right spot 
402                 GetSGNode()->SetLocalScale(GetSGNode()->GetWorldScaling());
403                 GetSGNode()->SetLocalOrientation(GetSGNode()->GetWorldOrientation());
404                 GetSGNode()->SetLocalPosition(GetSGNode()->GetWorldPosition());
405
406                 // Remove us from our parent
407                 GetSGNode()->DisconnectFromParent();
408                 NodeUpdateGS(0.f);
409                 // the object is now a root object, add it to the parentlist
410                 CListValue* rootlist = scene->GetRootParentList();
411                 if (!rootlist->SearchValue(this))
412                         // object was not in root list, add it now and increment ref count
413                         rootlist->Add(AddRef());
414                 if (m_pPhysicsController)
415                 {
416                         // in case this controller was added as a child shape to the parent
417                         if (rootobj != NULL && 
418                                 rootobj->m_pPhysicsController != NULL &&
419                                 rootobj->m_pPhysicsController->IsCompound())
420                         {
421                                 rootobj->m_pPhysicsController->RemoveCompoundChild(m_pPhysicsController);
422                         }
423                         m_pPhysicsController->RestoreDynamics();
424                         if (m_pPhysicsController->IsDynamic() && (rootobj != NULL && rootobj->m_pPhysicsController))
425                         {
426                                 // dynamic object should remember the velocity they had while being parented
427                                 MT_Point3 childPoint = GetSGNode()->GetWorldPosition();
428                                 MT_Point3 rootPoint = rootobj->GetSGNode()->GetWorldPosition();
429                                 MT_Point3 relPoint;
430                                 relPoint = (childPoint-rootPoint);
431                                 MT_Vector3 linVel = rootobj->m_pPhysicsController->GetVelocity(relPoint);
432                                 MT_Vector3 angVel = rootobj->m_pPhysicsController->GetAngularVelocity();
433                                 m_pPhysicsController->SetLinearVelocity(linVel, false);
434                                 m_pPhysicsController->SetAngularVelocity(angVel, false);
435                         }
436                 }
437                 // graphically, the object hasn't change place, no need to update m_pGraphicController
438         }
439 }
440
441 BL_ActionManager* KX_GameObject::GetActionManager()
442 {
443         // We only want to create an action manager if we need it
444         if (!m_actionManager)
445         {
446                 GetScene()->AddAnimatedObject(this);
447                 m_actionManager = new BL_ActionManager(this);
448         }
449         return m_actionManager;
450 }
451
452 bool KX_GameObject::PlayAction(const char* name,
453                                                                 float start,
454                                                                 float end,
455                                                                 short layer,
456                                                                 short priority,
457                                                                 float blendin,
458                                                                 short play_mode,
459                                                                 float layer_weight,
460                                                                 short ipo_flags,
461                                                                 float playback_speed,
462                                                                 short blend_mode)
463 {
464         return GetActionManager()->PlayAction(name, start, end, layer, priority, blendin, play_mode, layer_weight, ipo_flags, playback_speed, blend_mode);
465 }
466
467 void KX_GameObject::StopAction(short layer)
468 {
469         GetActionManager()->StopAction(layer);
470 }
471
472 void KX_GameObject::RemoveTaggedActions()
473 {
474         GetActionManager()->RemoveTaggedActions();
475 }
476
477 bool KX_GameObject::IsActionDone(short layer)
478 {
479         return GetActionManager()->IsActionDone(layer);
480 }
481
482 void KX_GameObject::UpdateActionManager(float curtime)
483 {
484         GetActionManager()->Update(curtime);
485 }
486
487 void KX_GameObject::UpdateActionIPOs()
488 {
489         GetActionManager()->UpdateIPOs();
490 }
491
492 float KX_GameObject::GetActionFrame(short layer)
493 {
494         return GetActionManager()->GetActionFrame(layer);
495 }
496
497 const char *KX_GameObject::GetActionName(short layer)
498 {
499         return GetActionManager()->GetActionName(layer);
500 }
501
502 void KX_GameObject::SetActionFrame(short layer, float frame)
503 {
504         GetActionManager()->SetActionFrame(layer, frame);
505 }
506
507 bAction *KX_GameObject::GetCurrentAction(short layer)
508 {
509         return GetActionManager()->GetCurrentAction(layer);
510 }
511
512 void KX_GameObject::SetPlayMode(short layer, short mode)
513 {
514         GetActionManager()->SetPlayMode(layer, mode);
515 }
516
517 void KX_GameObject::SetTimes(short layer, float start, float end)
518 {
519         GetActionManager()->SetTimes(layer, start, end);
520 }
521
522 void KX_GameObject::ProcessReplica()
523 {
524         SCA_IObject::ProcessReplica();
525
526         m_pGraphicController = NULL;
527         m_pPhysicsController = NULL;
528         m_pSGNode = NULL;
529         m_pClient_info = new KX_ClientObjectInfo(*m_pClient_info);
530         m_pClient_info->m_gameobject = this;
531         m_actionManager = NULL;
532         m_state = 0;
533
534         KX_Scene* scene = KX_GetActiveScene();
535         KX_ObstacleSimulation* obssimulation = scene->GetObstacleSimulation();
536         struct Object* blenderobject = GetBlenderObject();
537         if (obssimulation && (blenderobject->gameflag & OB_HASOBSTACLE))
538         {
539                 obssimulation->AddObstacleForObj(this);
540         }
541
542 #ifdef WITH_PYTHON
543         if (m_attr_dict)
544                 m_attr_dict= PyDict_Copy(m_attr_dict);
545 #endif
546                 
547 }
548
549 static void setGraphicController_recursive(SG_Node* node)
550 {
551         NodeList& children = node->GetSGChildren();
552
553         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
554         {
555                 SG_Node* childnode = (*childit);
556                 KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
557                 if (clientgameobj != NULL) // This is a GameObject
558                         clientgameobj->ActivateGraphicController(false);
559                 
560                 // if the childobj is NULL then this may be an inverse parent link
561                 // so a non recursive search should still look down this node.
562                 setGraphicController_recursive(childnode);
563         }
564 }
565
566
567 void KX_GameObject::ActivateGraphicController(bool recurse)
568 {
569         if (m_pGraphicController)
570         {
571                 m_pGraphicController->Activate(m_bVisible);
572         }
573         if (recurse)
574         {
575                 setGraphicController_recursive(GetSGNode());
576         }
577 }
578
579 void KX_GameObject::SetUserCollisionGroup(unsigned short group)
580 {
581         m_userCollisionGroup = group;
582         if (m_pPhysicsController)
583                 m_pPhysicsController->RefreshCollisions();
584 }
585 void KX_GameObject::SetUserCollisionMask(unsigned short mask)
586 {
587         m_userCollisionMask = mask;
588         if (m_pPhysicsController)
589                 m_pPhysicsController->RefreshCollisions();
590 }
591
592 unsigned short KX_GameObject::GetUserCollisionGroup()
593 {
594         return m_userCollisionGroup;
595 }
596 unsigned short KX_GameObject::GetUserCollisionMask()
597 {
598         return m_userCollisionMask;
599 }
600
601 bool KX_GameObject::CheckCollision(KX_GameObject* other)
602 {
603         return this->m_userCollisionGroup & other->m_userCollisionMask;
604 }
605
606 CValue* KX_GameObject::GetReplica()
607 {
608         KX_GameObject* replica = new KX_GameObject(*this);
609
610         // this will copy properties and so on...
611         replica->ProcessReplica();
612
613         return replica;
614 }
615
616 bool KX_GameObject::IsDynamicsSuspended() const
617 {
618         if (m_pPhysicsController)
619                 return m_pPhysicsController->IsSuspended();
620         return false;
621 }
622
623 float KX_GameObject::getLinearDamping() const
624 {
625         if (m_pPhysicsController)
626                 return m_pPhysicsController->GetLinearDamping();
627         return 0;
628 }
629
630 float KX_GameObject::getAngularDamping() const
631 {
632         if (m_pPhysicsController)
633                 return m_pPhysicsController->GetAngularDamping();
634         return 0;
635 }
636
637 void KX_GameObject::setLinearDamping(float damping)
638 {
639         if (m_pPhysicsController)
640                 m_pPhysicsController->SetLinearDamping(damping);
641 }
642
643
644 void KX_GameObject::setAngularDamping(float damping)
645 {
646         if (m_pPhysicsController)
647                 m_pPhysicsController->SetAngularDamping(damping);
648 }
649
650
651 void KX_GameObject::setDamping(float linear, float angular)
652 {
653         if (m_pPhysicsController)
654                 m_pPhysicsController->SetDamping(linear, angular);
655 }
656
657
658 void KX_GameObject::ApplyForce(const MT_Vector3& force,bool local)
659 {
660         if (m_pPhysicsController)
661                 m_pPhysicsController->ApplyForce(force,local);
662 }
663
664
665
666 void KX_GameObject::ApplyTorque(const MT_Vector3& torque,bool local)
667 {
668         if (m_pPhysicsController)
669                 m_pPhysicsController->ApplyTorque(torque,local);
670 }
671
672
673
674 void KX_GameObject::ApplyMovement(const MT_Vector3& dloc,bool local)
675 {
676         if (GetSGNode()) 
677         {
678                 if (m_pPhysicsController) // (IsDynamic())
679                 {
680                         m_pPhysicsController->RelativeTranslate(dloc,local);
681                 }
682                 GetSGNode()->RelativeTranslate(dloc,GetSGNode()->GetSGParent(),local);
683         }
684 }
685
686
687
688 void KX_GameObject::ApplyRotation(const MT_Vector3& drot,bool local)
689 {
690         MT_Matrix3x3 rotmat(drot);
691         
692         if (GetSGNode()) {
693                 GetSGNode()->RelativeRotate(rotmat,local);
694
695                 if (m_pPhysicsController) { // (IsDynamic())
696                         m_pPhysicsController->RelativeRotate(rotmat,local);
697                 }
698         }
699 }
700
701
702
703 /**
704  * GetOpenGL Matrix, returns an OpenGL 'compatible' matrix
705  */
706 double* KX_GameObject::GetOpenGLMatrix()
707 {
708         // todo: optimize and only update if necessary
709         double* fl = m_OpenGL_4x4Matrix.getPointer();
710         if (GetSGNode()) {
711                 MT_Transform trans;
712         
713                 trans.setOrigin(GetSGNode()->GetWorldPosition());
714                 trans.setBasis(GetSGNode()->GetWorldOrientation());
715         
716                 MT_Vector3 scaling = GetSGNode()->GetWorldScaling();
717                 m_bIsNegativeScaling = ((scaling[0] < 0.0) ^ (scaling[1] < 0.0) ^ (scaling[2] < 0.0)) ? true : false;
718                 trans.scale(scaling[0], scaling[1], scaling[2]);
719                 trans.getValue(fl);
720                 GetSGNode()->ClearDirty();
721         }
722         return fl;
723 }
724
725 void KX_GameObject::UpdateBlenderObjectMatrix(Object* blendobj)
726 {
727         if (!blendobj)
728                 blendobj = m_pBlenderObject;
729         if (blendobj) {
730                 const MT_Matrix3x3& rot = NodeGetWorldOrientation();
731                 const MT_Vector3& scale = NodeGetWorldScaling();
732                 const MT_Vector3& pos = NodeGetWorldPosition();
733                 rot.getValue(blendobj->obmat[0]);
734                 pos.getValue(blendobj->obmat[3]);
735                 mul_v3_fl(blendobj->obmat[0], scale[0]);
736                 mul_v3_fl(blendobj->obmat[1], scale[1]);
737                 mul_v3_fl(blendobj->obmat[2], scale[2]);
738         }
739 }
740
741 void KX_GameObject::AddMeshUser()
742 {
743         for (size_t i=0;i<m_meshes.size();i++)
744         {
745                 m_meshes[i]->AddMeshUser(this, &m_meshSlots, GetDeformer());
746         }
747         // set the part of the mesh slot that never change
748         double* fl = GetOpenGLMatrixPtr()->getPointer();
749
750         SG_QList::iterator<RAS_MeshSlot> mit(m_meshSlots);
751 //      RAS_MeshSlot* ms;
752         for (mit.begin(); !mit.end(); ++mit)
753         {
754                 (*mit)->m_OpenGLMatrix = fl;
755         }
756         UpdateBuckets(false);
757 }
758
759 static void UpdateBuckets_recursive(SG_Node* node)
760 {
761         NodeList& children = node->GetSGChildren();
762
763         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
764         {
765                 SG_Node* childnode = (*childit);
766                 KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
767                 if (clientgameobj != NULL) // This is a GameObject
768                         clientgameobj->UpdateBuckets(0);
769                 
770                 // if the childobj is NULL then this may be an inverse parent link
771                 // so a non recursive search should still look down this node.
772                 UpdateBuckets_recursive(childnode);
773         }
774 }
775
776 void KX_GameObject::UpdateBuckets( bool recursive )
777 {
778         if (GetSGNode()) {
779                 RAS_MeshSlot *ms;
780
781                 if (GetSGNode()->IsDirty())
782                         GetOpenGLMatrix();
783
784                 SG_QList::iterator<RAS_MeshSlot> mit(m_meshSlots);
785                 for (mit.begin(); !mit.end(); ++mit)
786                 {
787                         ms = *mit;
788                         ms->m_bObjectColor = m_bUseObjectColor;
789                         ms->m_RGBAcolor = m_objectColor;
790                         ms->m_bVisible = m_bVisible;
791                         ms->m_bCulled = m_bCulled || !m_bVisible;
792                         if (!ms->m_bCulled) 
793                                 ms->m_bucket->ActivateMesh(ms);
794                         
795                         /* split if necessary */
796 #ifdef USE_SPLIT
797                         ms->Split();
798 #endif
799                 }
800         
801                 if (recursive) {
802                         UpdateBuckets_recursive(GetSGNode());
803                 }
804         }
805 }
806
807 void KX_GameObject::RemoveMeshes()
808 {
809         for (size_t i=0;i<m_meshes.size();i++)
810                 m_meshes[i]->RemoveFromBuckets(this);
811
812         //note: meshes can be shared, and are deleted by KX_BlenderSceneConverter
813
814         m_meshes.clear();
815 }
816
817 void KX_GameObject::AddLodMesh(RAS_MeshObject* mesh)
818 {
819         m_lodmeshes.push_back(mesh);
820 }
821
822
823 static float calcHysteresis(KX_Scene *kxscene, LodLevel *lod)
824 {
825         float hystvariance = 0.0f;
826
827         if (!kxscene->IsActivedLodHysteresis())
828                 return hystvariance;
829                         
830         short hysteresis = 0;
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         else
835                 hysteresis = kxscene->GetLodHysteresisValue();
836
837         return hystvariance = MT_abs(lod->next->distance - lod->distance) * hysteresis / 100;
838 }
839
840 void KX_GameObject::UpdateLod(MT_Vector3 &cam_pos)
841 {
842         // Handle dupligroups
843         if (m_pInstanceObjects) {
844                 KX_GameObject *instob;
845                 int count = m_pInstanceObjects->GetCount();
846                 for (int i = 0; i < count; i++) {
847                         instob = (KX_GameObject*)m_pInstanceObjects->GetValue(i);
848                         instob->UpdateLod(cam_pos);
849                 }
850         }
851
852         if (m_lodmeshes.empty())
853                 return;
854
855         MT_Vector3 delta = NodeGetWorldPosition() - cam_pos;
856         float distance2 = delta.length2();
857
858         int level = 0;
859         float hystvariance = 0.0f;
860         Object *bob = GetBlenderObject();
861         LodLevel *lod = (LodLevel *)bob->lodlevels.first;
862         KX_Scene *kxscene = GetScene();
863
864         for (; lod; lod = lod->next, level++) {
865                 if (!lod->source || lod->source->type != OB_MESH)
866                         level--;
867
868                 if (!lod->next)
869                         break;
870
871                 if (level == m_previousLodLevel || level == (m_previousLodLevel + 1)) {
872                         hystvariance = calcHysteresis(kxscene, lod);
873                         float newdistance = lod->next->distance + hystvariance;
874                         if (newdistance * newdistance > distance2)
875                                 break;
876                 }
877                 else if (level == (m_previousLodLevel - 1)) {
878                         hystvariance = calcHysteresis(kxscene, lod);
879                         float newdistance = lod->next->distance - hystvariance;
880                         if (newdistance * newdistance > distance2)
881                                 break;
882                 }
883         }
884
885         RAS_MeshObject *mesh = m_lodmeshes[level];
886         m_currentLodLevel = level;
887         if (mesh != m_meshes[0]) {
888                 m_previousLodLevel = level;
889                 GetScene()->ReplaceMesh(this, mesh, true, false);
890         }
891 }
892
893 void KX_GameObject::UpdateTransform()
894 {
895         // HACK: saves function call for dynamic object, they are handled differently
896         if (m_pPhysicsController && !m_pPhysicsController->IsDynamic())
897                 m_pPhysicsController->SetTransform();
898         if (m_pGraphicController)
899                 // update the culling tree
900                 m_pGraphicController->SetGraphicTransform();
901
902 }
903
904 void KX_GameObject::UpdateTransformFunc(SG_IObject* node, void* gameobj, void* scene)
905 {
906         ((KX_GameObject*)gameobj)->UpdateTransform();
907 }
908
909 void KX_GameObject::SynchronizeTransform()
910 {
911         // only used for sensor object, do full synchronization as bullet doesn't do it
912         if (m_pPhysicsController)
913                 m_pPhysicsController->SetTransform();
914         if (m_pGraphicController)
915                 m_pGraphicController->SetGraphicTransform();
916 }
917
918 void KX_GameObject::SynchronizeTransformFunc(SG_IObject* node, void* gameobj, void* scene)
919 {
920         ((KX_GameObject*)gameobj)->SynchronizeTransform();
921 }
922
923
924 void KX_GameObject::SetDebugColor(unsigned int bgra)
925 {
926         for (size_t i=0;i<m_meshes.size();i++)
927                 m_meshes[i]->DebugColor(bgra);
928 }
929
930
931
932 void KX_GameObject::ResetDebugColor()
933 {
934         SetDebugColor(0xff000000);
935 }
936
937 void KX_GameObject::InitIPO(bool ipo_as_force,
938                             bool ipo_add,
939                             bool ipo_local)
940 {
941         SGControllerList::iterator it = GetSGNode()->GetSGControllerList().begin();
942
943         while (it != GetSGNode()->GetSGControllerList().end()) {
944                 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_RESET, true);
945                 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_AS_FORCE, ipo_as_force);
946                 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_ADD, ipo_add);
947                 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_LOCAL, ipo_local);
948                 it++;
949         }
950
951
952 void KX_GameObject::UpdateIPO(float curframetime,
953                                                           bool recurse) 
954 {
955         // just the 'normal' update procedure.
956         GetSGNode()->SetSimulatedTime(curframetime,recurse);
957         GetSGNode()->UpdateWorldData(curframetime);
958         UpdateTransform();
959 }
960
961 // IPO update
962 void 
963 KX_GameObject::UpdateMaterialData(
964                 dword matname_hash,
965                 MT_Vector4 rgba,
966                 MT_Vector3 specrgb,
967                 MT_Scalar hard,
968                 MT_Scalar spec,
969                 MT_Scalar ref,
970                 MT_Scalar emit,
971                 MT_Scalar alpha
972
973         )
974 {
975         int mesh = 0;
976         if (((unsigned int)mesh < m_meshes.size()) && mesh >= 0) {
977                 list<RAS_MeshMaterial>::iterator mit = m_meshes[mesh]->GetFirstMaterial();
978
979                 for (; mit != m_meshes[mesh]->GetLastMaterial(); ++mit)
980                 {
981                         RAS_IPolyMaterial* poly = mit->m_bucket->GetPolyMaterial();
982
983                         if (poly->GetFlag() & RAS_BLENDERMAT )
984                         {
985                                 KX_BlenderMaterial *m =  static_cast<KX_BlenderMaterial*>(poly);
986                                 
987                                 if (matname_hash == 0)
988                                 {
989                                         m->UpdateIPO(rgba, specrgb,hard,spec,ref,emit, alpha);
990                                         // if mesh has only one material attached to it then use original hack with no need to edit vertices (better performance)
991                                         SetObjectColor(rgba);
992                                 }
993                                 else
994                                 {
995                                         if (matname_hash == poly->GetMaterialNameHash())
996                                         {
997                                                 m->UpdateIPO(rgba, specrgb,hard,spec,ref,emit, alpha);
998                                                 m_meshes[mesh]->SetVertexColor(poly,rgba);
999                                                 
1000                                                 // no break here, because one blender material can be split into several game engine materials
1001                                                 // (e.g. one uvsphere material is split into one material at poles with ras_mode TRIANGLE and one material for the body
1002                                                 // if here was a break then would miss some vertices if material was split
1003                                         }
1004                                 }
1005                         }
1006                 }
1007         }
1008 }
1009 bool
1010 KX_GameObject::GetVisible(
1011         void
1012         )
1013 {
1014         return m_bVisible;
1015 }
1016
1017 static void setVisible_recursive(SG_Node* node, bool v)
1018 {
1019         NodeList& children = node->GetSGChildren();
1020
1021         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
1022         {
1023                 SG_Node* childnode = (*childit);
1024                 KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
1025                 if (clientgameobj != NULL) // This is a GameObject
1026                         clientgameobj->SetVisible(v, 0);
1027                 
1028                 // if the childobj is NULL then this may be an inverse parent link
1029                 // so a non recursive search should still look down this node.
1030                 setVisible_recursive(childnode, v);
1031         }
1032 }
1033
1034
1035 void
1036 KX_GameObject::SetVisible(
1037         bool v,
1038         bool recursive
1039         )
1040 {
1041         if (GetSGNode()) {
1042                 m_bVisible = v;
1043                 if (m_pGraphicController)
1044                         m_pGraphicController->Activate(m_bVisible);
1045                 if (recursive)
1046                         setVisible_recursive(GetSGNode(), v);
1047         }
1048 }
1049
1050 static void setOccluder_recursive(SG_Node* node, bool v)
1051 {
1052         NodeList& children = node->GetSGChildren();
1053
1054         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
1055         {
1056                 SG_Node* childnode = (*childit);
1057                 KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
1058                 if (clientgameobj != NULL) // This is a GameObject
1059                         clientgameobj->SetOccluder(v, false);
1060                 
1061                 // if the childobj is NULL then this may be an inverse parent link
1062                 // so a non recursive search should still look down this node.
1063                 setOccluder_recursive(childnode, v);
1064         }
1065 }
1066
1067 void
1068 KX_GameObject::SetOccluder(
1069         bool v,
1070         bool recursive
1071         )
1072 {
1073         if (GetSGNode()) {
1074                 m_bOccluder = v;
1075                 if (recursive)
1076                         setOccluder_recursive(GetSGNode(), v);
1077         }
1078 }
1079
1080 static void setDebug_recursive(SG_Node *node, bool debug)
1081 {
1082         NodeList& children = node->GetSGChildren();
1083         KX_Scene *scene = KX_GetActiveScene();
1084
1085         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit) {
1086                 SG_Node *childnode = (*childit);
1087                 KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
1088                 if (clientgameobj != NULL) {
1089                         if (debug) {
1090                                 if (!scene->ObjectInDebugList(clientgameobj))
1091                                         scene->AddObjectDebugProperties(clientgameobj);
1092                         }
1093                         else
1094                                 scene->RemoveObjectDebugProperties(clientgameobj);
1095                 }
1096
1097                 /* if the childobj is NULL then this may be an inverse parent link
1098                  * so a non recursive search should still look down this node. */
1099                 setDebug_recursive(childnode, debug);
1100         }
1101 }
1102
1103 void KX_GameObject::SetUseDebugProperties( bool debug, bool recursive )
1104 {
1105         KX_Scene *scene = KX_GetActiveScene();
1106
1107         if (debug) {
1108                 if (!scene->ObjectInDebugList(this))
1109                         scene->AddObjectDebugProperties(this);
1110         }
1111         else
1112                 scene->RemoveObjectDebugProperties(this);
1113
1114         if (recursive)
1115                 setDebug_recursive(GetSGNode(), debug);
1116 }
1117
1118 void
1119 KX_GameObject::SetLayer(
1120         int l
1121         )
1122 {
1123         m_layer = l;
1124 }
1125
1126 int
1127 KX_GameObject::GetLayer(
1128         void
1129         )
1130 {
1131         return m_layer;
1132 }
1133
1134 void KX_GameObject::addLinearVelocity(const MT_Vector3& lin_vel,bool local)
1135 {
1136         if (m_pPhysicsController)
1137         {
1138                 MT_Vector3 lv = local ? NodeGetWorldOrientation() * lin_vel : lin_vel;
1139                 m_pPhysicsController->SetLinearVelocity(lv + m_pPhysicsController->GetLinearVelocity(), 0);
1140         }
1141 }
1142
1143
1144
1145 void KX_GameObject::setLinearVelocity(const MT_Vector3& lin_vel,bool local)
1146 {
1147         if (m_pPhysicsController)
1148                 m_pPhysicsController->SetLinearVelocity(lin_vel,local);
1149 }
1150
1151
1152
1153 void KX_GameObject::setAngularVelocity(const MT_Vector3& ang_vel,bool local)
1154 {
1155         if (m_pPhysicsController)
1156                 m_pPhysicsController->SetAngularVelocity(ang_vel,local);
1157 }
1158
1159
1160 void KX_GameObject::ResolveCombinedVelocities(
1161         const MT_Vector3 & lin_vel,
1162         const MT_Vector3 & ang_vel,
1163         bool lin_vel_local,
1164         bool ang_vel_local
1165 ) {
1166         if (m_pPhysicsController)
1167         {
1168
1169                 MT_Vector3 lv = lin_vel_local ? NodeGetWorldOrientation() * lin_vel : lin_vel;
1170                 MT_Vector3 av = ang_vel_local ? NodeGetWorldOrientation() * ang_vel : ang_vel;
1171                 m_pPhysicsController->ResolveCombinedVelocities(
1172                         lv.x(),lv.y(),lv.z(),av.x(),av.y(),av.z());
1173         }
1174 }
1175
1176
1177 void KX_GameObject::SetObjectColor(const MT_Vector4& rgbavec)
1178 {
1179         m_bUseObjectColor = true;
1180         m_objectColor = rgbavec;
1181 }
1182
1183 const MT_Vector4& KX_GameObject::GetObjectColor()
1184 {
1185         return m_objectColor;
1186 }
1187
1188 void KX_GameObject::AlignAxisToVect(const MT_Vector3& dir, int axis, float fac)
1189 {
1190         MT_Matrix3x3 orimat;
1191         MT_Vector3 vect,ori,z,x,y;
1192         MT_Scalar len;
1193
1194         // check on valid node in case a python controller holds a reference to a deleted object
1195         if (!GetSGNode())
1196                 return;
1197
1198         vect = dir;
1199         len = vect.length();
1200         if (MT_fuzzyZero(len))
1201         {
1202                 cout << "alignAxisToVect() Error: Null vector!\n";
1203                 return;
1204         }
1205         
1206         if (fac <= 0.0f) {
1207                 return;
1208         }
1209         
1210         // normalize
1211         vect /= len;
1212         orimat = GetSGNode()->GetWorldOrientation();
1213         switch (axis)
1214         {
1215                 case 0: //x axis
1216                         ori.setValue(orimat[0][2], orimat[1][2], orimat[2][2]); //pivot axis
1217                         if (MT_abs(vect.dot(ori)) > 1.0-3.0*MT_EPSILON) //is the vector parallel to the pivot?
1218                                 ori.setValue(orimat[0][1], orimat[1][1], orimat[2][1]); //change the pivot!
1219                         if (fac == 1.0f) {
1220                                 x = vect;
1221                         } else {
1222                                 x = (vect * fac) + ((orimat * MT_Vector3(1.0, 0.0, 0.0)) * (1.0f - fac));
1223                                 len = x.length();
1224                                 if (MT_fuzzyZero(len)) x = vect;
1225                                 else x /= len;
1226                         }
1227                         y = ori.cross(x);
1228                         z = x.cross(y);
1229                         break;
1230                 case 1: //y axis
1231                         ori.setValue(orimat[0][0], orimat[1][0], orimat[2][0]);
1232                         if (MT_abs(vect.dot(ori)) > 1.0-3.0*MT_EPSILON)
1233                                 ori.setValue(orimat[0][2], orimat[1][2], orimat[2][2]);
1234                         if (fac == 1.0f) {
1235                                 y = vect;
1236                         } else {
1237                                 y = (vect * fac) + ((orimat * MT_Vector3(0.0, 1.0, 0.0)) * (1.0f - fac));
1238                                 len = y.length();
1239                                 if (MT_fuzzyZero(len)) y = vect;
1240                                 else y /= len;
1241                         }
1242                         z = ori.cross(y);
1243                         x = y.cross(z);
1244                         break;
1245                 case 2: //z axis
1246                         ori.setValue(orimat[0][1], orimat[1][1], orimat[2][1]);
1247                         if (MT_abs(vect.dot(ori)) > 1.0-3.0*MT_EPSILON)
1248                                 ori.setValue(orimat[0][0], orimat[1][0], orimat[2][0]);
1249                         if (fac == 1.0f) {
1250                                 z = vect;
1251                         } else {
1252                                 z = (vect * fac) + ((orimat * MT_Vector3(0.0, 0.0, 1.0)) * (1.0f - fac));
1253                                 len = z.length();
1254                                 if (MT_fuzzyZero(len)) z = vect;
1255                                 else z /= len;
1256                         }
1257                         x = ori.cross(z);
1258                         y = z.cross(x);
1259                         break;
1260                 default: //wrong input?
1261                         cout << "alignAxisToVect(): Wrong axis '" << axis <<"'\n";
1262                         return;
1263         }
1264         x.normalize(); //normalize the vectors
1265         y.normalize();
1266         z.normalize();
1267         orimat.setValue(        x[0],y[0],z[0],
1268                                                 x[1],y[1],z[1],
1269                                                 x[2],y[2],z[2]);
1270         if (GetSGNode()->GetSGParent() != NULL)
1271         {
1272                 // the object is a child, adapt its local orientation so that 
1273                 // the global orientation is aligned as we want.
1274                 MT_Matrix3x3 invori = GetSGNode()->GetSGParent()->GetWorldOrientation().inverse();
1275                 NodeSetLocalOrientation(invori*orimat);
1276         }
1277         else
1278                 NodeSetLocalOrientation(orimat);
1279 }
1280
1281 MT_Scalar KX_GameObject::GetMass()
1282 {
1283         if (m_pPhysicsController)
1284         {
1285                 return m_pPhysicsController->GetMass();
1286         }
1287         return 0.0;
1288 }
1289
1290 MT_Vector3 KX_GameObject::GetLocalInertia()
1291 {
1292         MT_Vector3 local_inertia(0.0,0.0,0.0);
1293         if (m_pPhysicsController)
1294         {
1295                 local_inertia = m_pPhysicsController->GetLocalInertia();
1296         }
1297         return local_inertia;
1298 }
1299
1300 MT_Vector3 KX_GameObject::GetLinearVelocity(bool local)
1301 {
1302         MT_Vector3 velocity(0.0,0.0,0.0), locvel;
1303         MT_Matrix3x3 ori;
1304         if (m_pPhysicsController)
1305         {
1306                 velocity = m_pPhysicsController->GetLinearVelocity();
1307                 
1308                 if (local)
1309                 {
1310                         ori = GetSGNode()->GetWorldOrientation();
1311                         
1312                         locvel = velocity * ori;
1313                         return locvel;
1314                 }
1315         }
1316         return velocity;
1317 }
1318
1319 MT_Vector3 KX_GameObject::GetAngularVelocity(bool local)
1320 {
1321         MT_Vector3 velocity(0.0,0.0,0.0), locvel;
1322         MT_Matrix3x3 ori;
1323         if (m_pPhysicsController)
1324         {
1325                 velocity = m_pPhysicsController->GetAngularVelocity();
1326                 
1327                 if (local)
1328                 {
1329                         ori = GetSGNode()->GetWorldOrientation();
1330                         
1331                         locvel = velocity * ori;
1332                         return locvel;
1333                 }
1334         }
1335         return velocity;
1336 }
1337
1338 MT_Vector3 KX_GameObject::GetVelocity(const MT_Point3& point)
1339 {
1340         if (m_pPhysicsController)
1341         {
1342                 return m_pPhysicsController->GetVelocity(point);
1343         }
1344         return MT_Vector3(0.0,0.0,0.0);
1345 }
1346
1347 // scenegraph node stuff
1348
1349 void KX_GameObject::NodeSetLocalPosition(const MT_Point3& trans)
1350 {
1351         // check on valid node in case a python controller holds a reference to a deleted object
1352         if (!GetSGNode())
1353                 return;
1354
1355         if (m_pPhysicsController && !GetSGNode()->GetSGParent())
1356         {
1357                 // don't update physic controller if the object is a child:
1358                 // 1) the transformation will not be right
1359                 // 2) in this case, the physic controller is necessarily a static object
1360                 //    that is updated from the normal kinematic synchronization
1361                 m_pPhysicsController->SetPosition(trans);
1362         }
1363
1364         GetSGNode()->SetLocalPosition(trans);
1365
1366 }
1367
1368
1369
1370 void KX_GameObject::NodeSetLocalOrientation(const MT_Matrix3x3& rot)
1371 {
1372         // check on valid node in case a python controller holds a reference to a deleted object
1373         if (!GetSGNode())
1374                 return;
1375
1376         if (m_pPhysicsController && !GetSGNode()->GetSGParent())
1377         {
1378                 // see note above
1379                 m_pPhysicsController->SetOrientation(rot);
1380         }
1381         GetSGNode()->SetLocalOrientation(rot);
1382 }
1383
1384 void KX_GameObject::NodeSetGlobalOrientation(const MT_Matrix3x3& rot)
1385 {
1386         // check on valid node in case a python controller holds a reference to a deleted object
1387         if (!GetSGNode())
1388                 return;
1389
1390         if (GetSGNode()->GetSGParent())
1391                 GetSGNode()->SetLocalOrientation(GetSGNode()->GetSGParent()->GetWorldOrientation().inverse()*rot);
1392         else
1393                 NodeSetLocalOrientation(rot);
1394 }
1395
1396 void KX_GameObject::NodeSetLocalScale(const MT_Vector3& scale)
1397 {
1398         // check on valid node in case a python controller holds a reference to a deleted object
1399         if (!GetSGNode())
1400                 return;
1401
1402         if (m_pPhysicsController && !GetSGNode()->GetSGParent())
1403         {
1404                 // see note above
1405                 m_pPhysicsController->SetScaling(scale);
1406         }
1407         GetSGNode()->SetLocalScale(scale);
1408 }
1409
1410
1411
1412 void KX_GameObject::NodeSetRelativeScale(const MT_Vector3& scale)
1413 {
1414         if (GetSGNode())
1415         {
1416                 GetSGNode()->RelativeScale(scale);
1417                 if (m_pPhysicsController && (!GetSGNode()->GetSGParent()))
1418                 {
1419                         // see note above
1420                         // we can use the local scale: it's the same thing for a root object 
1421                         // and the world scale is not yet updated
1422                         MT_Vector3 newscale = GetSGNode()->GetLocalScale();
1423                         m_pPhysicsController->SetScaling(newscale);
1424                 }
1425         }
1426 }
1427
1428 void KX_GameObject::NodeSetWorldScale(const MT_Vector3& scale)
1429 {
1430         if (!GetSGNode())
1431                 return;
1432         SG_Node* parent = GetSGNode()->GetSGParent();
1433         if (parent != NULL)
1434         {
1435                 // Make sure the objects have some scale
1436                 MT_Vector3 p_scale = parent->GetWorldScaling();
1437                 if (fabs(p_scale[0]) < (MT_Scalar)FLT_EPSILON ||
1438                         fabs(p_scale[1]) < (MT_Scalar)FLT_EPSILON ||
1439                         fabs(p_scale[2]) < (MT_Scalar)FLT_EPSILON)
1440                 { 
1441                         return; 
1442                 }
1443
1444                 p_scale[0] = 1/p_scale[0];
1445                 p_scale[1] = 1/p_scale[1];
1446                 p_scale[2] = 1/p_scale[2];
1447
1448                 NodeSetLocalScale(scale * p_scale);
1449         }
1450         else
1451         {
1452                 NodeSetLocalScale(scale);
1453         }
1454 }
1455
1456 void KX_GameObject::NodeSetWorldPosition(const MT_Point3& trans)
1457 {
1458         if (!GetSGNode())
1459                 return;
1460         SG_Node* parent = GetSGNode()->GetSGParent();
1461         if (parent != NULL)
1462         {
1463                 // Make sure the objects have some scale
1464                 MT_Vector3 scale = parent->GetWorldScaling();
1465                 if (fabs(scale[0]) < (MT_Scalar)FLT_EPSILON ||
1466                         fabs(scale[1]) < (MT_Scalar)FLT_EPSILON ||
1467                         fabs(scale[2]) < (MT_Scalar)FLT_EPSILON)
1468                 { 
1469                         return; 
1470                 }
1471                 scale[0] = 1.0/scale[0];
1472                 scale[1] = 1.0/scale[1];
1473                 scale[2] = 1.0/scale[2];
1474                 MT_Matrix3x3 invori = parent->GetWorldOrientation().inverse();
1475                 MT_Vector3 newpos = invori*(trans-parent->GetWorldPosition())*scale;
1476                 NodeSetLocalPosition(MT_Point3(newpos[0],newpos[1],newpos[2]));
1477         }
1478         else
1479         {
1480                 NodeSetLocalPosition(trans);
1481         }
1482 }
1483
1484
1485 void KX_GameObject::NodeUpdateGS(double time)
1486 {
1487         if (GetSGNode())
1488                 GetSGNode()->UpdateWorldData(time);
1489 }
1490
1491
1492
1493 const MT_Matrix3x3& KX_GameObject::NodeGetWorldOrientation() const
1494 {
1495         // check on valid node in case a python controller holds a reference to a deleted object
1496         if (!GetSGNode())
1497                 return dummy_orientation;
1498         return GetSGNode()->GetWorldOrientation();
1499 }
1500
1501 const MT_Matrix3x3& KX_GameObject::NodeGetLocalOrientation() const
1502 {
1503         // check on valid node in case a python controller holds a reference to a deleted object
1504         if (!GetSGNode())
1505                 return dummy_orientation;
1506         return GetSGNode()->GetLocalOrientation();
1507 }
1508
1509 const MT_Vector3& KX_GameObject::NodeGetWorldScaling() const
1510 {
1511         // check on valid node in case a python controller holds a reference to a deleted object
1512         if (!GetSGNode())
1513                 return dummy_scaling;
1514
1515         return GetSGNode()->GetWorldScaling();
1516 }
1517
1518 const MT_Vector3& KX_GameObject::NodeGetLocalScaling() const
1519 {
1520         // check on valid node in case a python controller holds a reference to a deleted object
1521         if (!GetSGNode())
1522                 return dummy_scaling;
1523
1524         return GetSGNode()->GetLocalScale();
1525 }
1526
1527 const MT_Point3& KX_GameObject::NodeGetWorldPosition() const
1528 {
1529         // check on valid node in case a python controller holds a reference to a deleted object
1530         if (GetSGNode())
1531                 return GetSGNode()->GetWorldPosition();
1532         else
1533                 return dummy_point;
1534 }
1535
1536 const MT_Point3& KX_GameObject::NodeGetLocalPosition() const
1537 {
1538         // check on valid node in case a python controller holds a reference to a deleted object
1539         if (GetSGNode())
1540                 return GetSGNode()->GetLocalPosition();
1541         else
1542                 return dummy_point;
1543 }
1544
1545
1546 void KX_GameObject::UnregisterCollisionCallbacks()
1547 {
1548         if (!GetPhysicsController()) {
1549                 printf("Warning, trying to unregister collision callbacks for object without collisions: %s!\n", GetName().ReadPtr());
1550                 return;
1551         }
1552
1553         // Unregister from callbacks
1554         KX_Scene* scene = GetScene();
1555         PHY_IPhysicsEnvironment* pe = scene->GetPhysicsEnvironment();
1556         PHY_IPhysicsController* spc = GetPhysicsController();
1557         // If we are the last to unregister on this physics controller
1558         if (pe->RemoveCollisionCallback(spc)){
1559                 // If we are a sensor object
1560                 if (m_pClient_info->isSensor())
1561                         // Remove sensor body from physics world
1562                         pe->RemoveSensor(spc);
1563         }
1564 }
1565
1566 void KX_GameObject::RegisterCollisionCallbacks()
1567 {
1568         if (!GetPhysicsController()) {
1569                 printf("Warning, trying to register collision callbacks for object without collisions: %s!\n", GetName().ReadPtr());
1570                 return;
1571         }
1572
1573         // Register from callbacks
1574         KX_Scene* scene = GetScene();
1575         PHY_IPhysicsEnvironment* pe = scene->GetPhysicsEnvironment();
1576         PHY_IPhysicsController* spc = GetPhysicsController();
1577         // If we are the first to register on this physics controller
1578         if (pe->RequestCollisionCallback(spc)){
1579                 // If we are a sensor object
1580                 if (m_pClient_info->isSensor())
1581                         // Add sensor body to physics world
1582                         pe->AddSensor(spc);
1583         }
1584 }
1585 void KX_GameObject::RunCollisionCallbacks(KX_GameObject *collider, const MT_Vector3 &point, const MT_Vector3 &normal)
1586 {
1587 #ifdef WITH_PYTHON
1588         if (!m_collisionCallbacks || PyList_GET_SIZE(m_collisionCallbacks) == 0)
1589                 return;
1590
1591         /** Current logic controller is set by each python logic bricks before run,
1592          * but if no python logic brick ran the logic manager can be wrong 
1593          * (if the user use muti scenes) and it will cause problems with function
1594          * ConvertPythonToGameObject which use the current logic manager for object's name.
1595          * Note: the scene is already set in logic frame loop.
1596          */
1597         SCA_ILogicBrick::m_sCurrentLogicManager = GetScene()->GetLogicManager();
1598
1599         PyObject *args[] = {collider->GetProxy(), PyObjectFrom(point), PyObjectFrom(normal)};
1600         RunPythonCallBackList(m_collisionCallbacks, args, 1, ARRAY_SIZE(args));
1601
1602         for (unsigned int i = 0; i < ARRAY_SIZE(args); ++i) {
1603                 Py_DECREF(args[i]);
1604         }
1605 #endif
1606 }
1607
1608 /* Suspend/ resume: for the dynamic behavior, there is a simple
1609  * method. For the residual motion, there is not. I wonder what the
1610  * correct solution is for Sumo. Remove from the motion-update tree?
1611  *
1612  * So far, only switch the physics and logic.
1613  * */
1614
1615 void KX_GameObject::Resume(void)
1616 {
1617         if (m_suspended) {
1618                 SCA_IObject::Resume();
1619                 if (GetPhysicsController())
1620                         GetPhysicsController()->RestoreDynamics();
1621
1622                 m_suspended = false;
1623         }
1624 }
1625
1626 void KX_GameObject::Suspend()
1627 {
1628         if ((!m_ignore_activity_culling) && (!m_suspended)) {
1629                 SCA_IObject::Suspend();
1630                 if (GetPhysicsController())
1631                         GetPhysicsController()->SuspendDynamics();
1632                 m_suspended = true;
1633         }
1634 }
1635
1636 static void walk_children(SG_Node* node, CListValue* list, bool recursive)
1637 {
1638         if (!node)
1639                 return;
1640         NodeList& children = node->GetSGChildren();
1641
1642         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
1643         {
1644                 SG_Node* childnode = (*childit);
1645                 CValue* childobj = (CValue*)childnode->GetSGClientObject();
1646                 if (childobj != NULL) // This is a GameObject
1647                 {
1648                         // add to the list
1649                         list->Add(childobj->AddRef());
1650                 }
1651                 
1652                 // if the childobj is NULL then this may be an inverse parent link
1653                 // so a non recursive search should still look down this node.
1654                 if (recursive || childobj==NULL) {
1655                         walk_children(childnode, list, recursive);
1656                 }
1657         }
1658 }
1659
1660 CListValue* KX_GameObject::GetChildren()
1661 {
1662         CListValue* list = new CListValue();
1663         walk_children(GetSGNode(), list, 0); /* GetSGNode() is always valid or it would have raised an exception before this */
1664         return list;
1665 }
1666
1667 CListValue* KX_GameObject::GetChildrenRecursive()
1668 {
1669         CListValue* list = new CListValue();
1670         walk_children(GetSGNode(), list, 1);
1671         return list;
1672 }
1673
1674 KX_Scene* KX_GameObject::GetScene()
1675 {
1676         SG_Node* node = this->GetSGNode();
1677     if (node == NULL)
1678         // this happens for object in non active layers, rely on static scene then
1679         return KX_GetActiveScene();
1680     return static_cast<KX_Scene*>(node->GetSGClientInfo());
1681 }
1682
1683 /* ---------------------------------------------------------------------
1684  * Some stuff taken from the header
1685  * --------------------------------------------------------------------- */
1686 void KX_GameObject::Relink(CTR_Map<CTR_HashedPtr, void*> *map_parameter)
1687 {
1688         // we will relink the sensors and actuators that use object references
1689         // if the object is part of the replicated hierarchy, use the new
1690         // object reference instead
1691         SCA_SensorList& sensorlist = GetSensors();
1692         SCA_SensorList::iterator sit;
1693         for (sit=sensorlist.begin(); sit != sensorlist.end(); sit++)
1694         {
1695                 (*sit)->Relink(map_parameter);
1696         }
1697         SCA_ActuatorList& actuatorlist = GetActuators();
1698         SCA_ActuatorList::iterator ait;
1699         for (ait=actuatorlist.begin(); ait != actuatorlist.end(); ait++)
1700         {
1701                 (*ait)->Relink(map_parameter);
1702         }
1703 }
1704
1705 #ifdef USE_MATHUTILS
1706
1707 /* These require an SGNode */
1708 #define MATHUTILS_VEC_CB_POS_LOCAL 1
1709 #define MATHUTILS_VEC_CB_POS_GLOBAL 2
1710 #define MATHUTILS_VEC_CB_SCALE_LOCAL 3
1711 #define MATHUTILS_VEC_CB_SCALE_GLOBAL 4
1712 #define MATHUTILS_VEC_CB_INERTIA_LOCAL 5
1713 #define MATHUTILS_VEC_CB_OBJECT_COLOR 6
1714 #define MATHUTILS_VEC_CB_LINVEL_LOCAL 7
1715 #define MATHUTILS_VEC_CB_LINVEL_GLOBAL 8
1716 #define MATHUTILS_VEC_CB_ANGVEL_LOCAL 9
1717 #define MATHUTILS_VEC_CB_ANGVEL_GLOBAL 10
1718
1719 static unsigned char mathutils_kxgameob_vector_cb_index= -1; /* index for our callbacks */
1720
1721 static int mathutils_kxgameob_generic_check(BaseMathObject *bmo)
1722 {
1723         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1724         if (self == NULL)
1725                 return -1;
1726         
1727         return 0;
1728 }
1729
1730 static int mathutils_kxgameob_vector_get(BaseMathObject *bmo, int subtype)
1731 {
1732         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1733         if (self == NULL)
1734                 return -1;
1735
1736 #define PHYS_ERR(attr) PyErr_SetString(PyExc_AttributeError, "KX_GameObject." attr ", is missing a physics controller")
1737
1738         switch (subtype) {
1739                 case MATHUTILS_VEC_CB_POS_LOCAL:
1740                         self->NodeGetLocalPosition().getValue(bmo->data);
1741                         break;
1742                 case MATHUTILS_VEC_CB_POS_GLOBAL:
1743                         self->NodeGetWorldPosition().getValue(bmo->data);
1744                         break;
1745                 case MATHUTILS_VEC_CB_SCALE_LOCAL:
1746                         self->NodeGetLocalScaling().getValue(bmo->data);
1747                         break;
1748                 case MATHUTILS_VEC_CB_SCALE_GLOBAL:
1749                         self->NodeGetWorldScaling().getValue(bmo->data);
1750                         break;
1751                 case MATHUTILS_VEC_CB_INERTIA_LOCAL:
1752                         if (!self->GetPhysicsController()) return PHYS_ERR("localInertia"), -1;
1753                         self->GetPhysicsController()->GetLocalInertia().getValue(bmo->data);
1754                         break;
1755                 case MATHUTILS_VEC_CB_OBJECT_COLOR:
1756                         self->GetObjectColor().getValue(bmo->data);
1757                         break;
1758                 case MATHUTILS_VEC_CB_LINVEL_LOCAL:
1759                         if (!self->GetPhysicsController()) return PHYS_ERR("localLinearVelocity"), -1;
1760                         self->GetLinearVelocity(true).getValue(bmo->data);
1761                         break;
1762                 case MATHUTILS_VEC_CB_LINVEL_GLOBAL:
1763                         if (!self->GetPhysicsController()) return PHYS_ERR("worldLinearVelocity"), -1;
1764                         self->GetLinearVelocity(false).getValue(bmo->data);
1765                         break;
1766                 case MATHUTILS_VEC_CB_ANGVEL_LOCAL:
1767                         if (!self->GetPhysicsController()) return PHYS_ERR("localLinearVelocity"), -1;
1768                         self->GetAngularVelocity(true).getValue(bmo->data);
1769                         break;
1770                 case MATHUTILS_VEC_CB_ANGVEL_GLOBAL:
1771                         if (!self->GetPhysicsController()) return PHYS_ERR("worldLinearVelocity"), -1;
1772                         self->GetAngularVelocity(false).getValue(bmo->data);
1773                         break;
1774                         
1775         }
1776         
1777 #undef PHYS_ERR
1778         
1779         return 0;
1780 }
1781
1782 static int mathutils_kxgameob_vector_set(BaseMathObject *bmo, int subtype)
1783 {
1784         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1785         if (self == NULL)
1786                 return -1;
1787         
1788         switch (subtype) {
1789                 case MATHUTILS_VEC_CB_POS_LOCAL:
1790                         self->NodeSetLocalPosition(MT_Point3(bmo->data));
1791                         self->NodeUpdateGS(0.f);
1792                         break;
1793                 case MATHUTILS_VEC_CB_POS_GLOBAL:
1794                         self->NodeSetWorldPosition(MT_Point3(bmo->data));
1795                         self->NodeUpdateGS(0.f);
1796                         break;
1797                 case MATHUTILS_VEC_CB_SCALE_LOCAL:
1798                         self->NodeSetLocalScale(MT_Point3(bmo->data));
1799                         self->NodeUpdateGS(0.f);
1800                         break;
1801                 case MATHUTILS_VEC_CB_SCALE_GLOBAL:
1802                         PyErr_SetString(PyExc_AttributeError, "KX_GameObject.worldScale is read-only");
1803                         return -1;
1804                 case MATHUTILS_VEC_CB_INERTIA_LOCAL:
1805                         /* read only */
1806                         break;
1807                 case MATHUTILS_VEC_CB_OBJECT_COLOR:
1808                         self->SetObjectColor(MT_Vector4(bmo->data));
1809                         break;
1810                 case MATHUTILS_VEC_CB_LINVEL_LOCAL:
1811                         self->setLinearVelocity(MT_Point3(bmo->data),true);
1812                         break;
1813                 case MATHUTILS_VEC_CB_LINVEL_GLOBAL:
1814                         self->setLinearVelocity(MT_Point3(bmo->data),false);
1815                         break;
1816                 case MATHUTILS_VEC_CB_ANGVEL_LOCAL:
1817                         self->setAngularVelocity(MT_Point3(bmo->data),true);
1818                         break;
1819                 case MATHUTILS_VEC_CB_ANGVEL_GLOBAL:
1820                         self->setAngularVelocity(MT_Point3(bmo->data),false);
1821                         break;
1822         }
1823         
1824         return 0;
1825 }
1826
1827 static int mathutils_kxgameob_vector_get_index(BaseMathObject *bmo, int subtype, int index)
1828 {
1829         /* lazy, avoid repeteing the case statement */
1830         if (mathutils_kxgameob_vector_get(bmo, subtype) == -1)
1831                 return -1;
1832         return 0;
1833 }
1834
1835 static int mathutils_kxgameob_vector_set_index(BaseMathObject *bmo, int subtype, int index)
1836 {
1837         float f= bmo->data[index];
1838         
1839         /* lazy, avoid repeteing the case statement */
1840         if (mathutils_kxgameob_vector_get(bmo, subtype) == -1)
1841                 return -1;
1842         
1843         bmo->data[index] = f;
1844         return mathutils_kxgameob_vector_set(bmo, subtype);
1845 }
1846
1847 static Mathutils_Callback mathutils_kxgameob_vector_cb = {
1848         mathutils_kxgameob_generic_check,
1849         mathutils_kxgameob_vector_get,
1850         mathutils_kxgameob_vector_set,
1851         mathutils_kxgameob_vector_get_index,
1852         mathutils_kxgameob_vector_set_index
1853 };
1854
1855 /* Matrix */
1856 #define MATHUTILS_MAT_CB_ORI_LOCAL 1
1857 #define MATHUTILS_MAT_CB_ORI_GLOBAL 2
1858
1859 static unsigned char mathutils_kxgameob_matrix_cb_index= -1; /* index for our callbacks */
1860
1861 static int mathutils_kxgameob_matrix_get(BaseMathObject *bmo, int subtype)
1862 {
1863         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1864         if (self == NULL)
1865                 return -1;
1866
1867         switch (subtype) {
1868                 case MATHUTILS_MAT_CB_ORI_LOCAL:
1869                         self->NodeGetLocalOrientation().getValue3x3(bmo->data);
1870                         break;
1871                 case MATHUTILS_MAT_CB_ORI_GLOBAL:
1872                         self->NodeGetWorldOrientation().getValue3x3(bmo->data);
1873                         break;
1874         }
1875         
1876         return 0;
1877 }
1878
1879
1880 static int mathutils_kxgameob_matrix_set(BaseMathObject *bmo, int subtype)
1881 {
1882         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1883         if (self == NULL)
1884                 return -1;
1885         
1886         MT_Matrix3x3 mat3x3;
1887         switch (subtype) {
1888                 case MATHUTILS_MAT_CB_ORI_LOCAL:
1889                         mat3x3.setValue3x3(bmo->data);
1890                         self->NodeSetLocalOrientation(mat3x3);
1891                         self->NodeUpdateGS(0.f);
1892                         break;
1893                 case MATHUTILS_MAT_CB_ORI_GLOBAL:
1894                         mat3x3.setValue3x3(bmo->data);
1895                         self->NodeSetLocalOrientation(mat3x3);
1896                         self->NodeUpdateGS(0.f);
1897                         break;
1898         }
1899         
1900         return 0;
1901 }
1902
1903 static Mathutils_Callback mathutils_kxgameob_matrix_cb = {
1904         mathutils_kxgameob_generic_check,
1905         mathutils_kxgameob_matrix_get,
1906         mathutils_kxgameob_matrix_set,
1907         NULL,
1908         NULL
1909 };
1910
1911
1912 void KX_GameObject_Mathutils_Callback_Init(void)
1913 {
1914         // register mathutils callbacks, ok to run more than once.
1915         mathutils_kxgameob_vector_cb_index= Mathutils_RegisterCallback(&mathutils_kxgameob_vector_cb);
1916         mathutils_kxgameob_matrix_cb_index= Mathutils_RegisterCallback(&mathutils_kxgameob_matrix_cb);
1917 }
1918
1919 #endif // USE_MATHUTILS
1920
1921 #ifdef WITH_PYTHON
1922 /* ------- python stuff ---------------------------------------------------*/
1923 PyMethodDef KX_GameObject::Methods[] = {
1924         {"applyForce", (PyCFunction)    KX_GameObject::sPyApplyForce, METH_VARARGS},
1925         {"applyTorque", (PyCFunction)   KX_GameObject::sPyApplyTorque, METH_VARARGS},
1926         {"applyRotation", (PyCFunction) KX_GameObject::sPyApplyRotation, METH_VARARGS},
1927         {"applyMovement", (PyCFunction) KX_GameObject::sPyApplyMovement, METH_VARARGS},
1928         {"getLinearVelocity", (PyCFunction) KX_GameObject::sPyGetLinearVelocity, METH_VARARGS},
1929         {"setLinearVelocity", (PyCFunction) KX_GameObject::sPySetLinearVelocity, METH_VARARGS},
1930         {"getAngularVelocity", (PyCFunction) KX_GameObject::sPyGetAngularVelocity, METH_VARARGS},
1931         {"setAngularVelocity", (PyCFunction) KX_GameObject::sPySetAngularVelocity, METH_VARARGS},
1932         {"getVelocity", (PyCFunction) KX_GameObject::sPyGetVelocity, METH_VARARGS},
1933         {"setDamping", (PyCFunction) KX_GameObject::sPySetDamping, METH_VARARGS},
1934         {"getReactionForce", (PyCFunction) KX_GameObject::sPyGetReactionForce, METH_NOARGS},
1935         {"alignAxisToVect",(PyCFunction) KX_GameObject::sPyAlignAxisToVect, METH_VARARGS},
1936         {"getAxisVect",(PyCFunction) KX_GameObject::sPyGetAxisVect, METH_O},
1937         {"suspendDynamics", (PyCFunction)KX_GameObject::sPySuspendDynamics, METH_VARARGS},
1938         {"restoreDynamics", (PyCFunction)KX_GameObject::sPyRestoreDynamics,METH_NOARGS},
1939         {"enableRigidBody", (PyCFunction)KX_GameObject::sPyEnableRigidBody,METH_NOARGS},
1940         {"disableRigidBody", (PyCFunction)KX_GameObject::sPyDisableRigidBody,METH_NOARGS},
1941         {"applyImpulse", (PyCFunction) KX_GameObject::sPyApplyImpulse, METH_VARARGS},
1942         {"setCollisionMargin", (PyCFunction) KX_GameObject::sPySetCollisionMargin, METH_O},
1943         {"setParent", (PyCFunction)KX_GameObject::sPySetParent,METH_VARARGS},
1944         {"setVisible",(PyCFunction) KX_GameObject::sPySetVisible, METH_VARARGS},
1945         {"setOcclusion",(PyCFunction) KX_GameObject::sPySetOcclusion, METH_VARARGS},
1946         {"removeParent", (PyCFunction)KX_GameObject::sPyRemoveParent,METH_NOARGS},
1947
1948
1949         {"getPhysicsId", (PyCFunction)KX_GameObject::sPyGetPhysicsId,METH_NOARGS},
1950         {"getPropertyNames", (PyCFunction)KX_GameObject::sPyGetPropertyNames,METH_NOARGS},
1951         {"replaceMesh",(PyCFunction) KX_GameObject::sPyReplaceMesh, METH_VARARGS},
1952         {"endObject",(PyCFunction) KX_GameObject::sPyEndObject, METH_NOARGS},
1953         {"reinstancePhysicsMesh", (PyCFunction)KX_GameObject::sPyReinstancePhysicsMesh,METH_VARARGS},
1954         
1955         KX_PYMETHODTABLE(KX_GameObject, rayCastTo),
1956         KX_PYMETHODTABLE(KX_GameObject, rayCast),
1957         KX_PYMETHODTABLE_O(KX_GameObject, getDistanceTo),
1958         KX_PYMETHODTABLE_O(KX_GameObject, getVectTo),
1959         KX_PYMETHODTABLE(KX_GameObject, sendMessage),
1960         KX_PYMETHODTABLE(KX_GameObject, addDebugProperty),
1961
1962         KX_PYMETHODTABLE_KEYWORDS(KX_GameObject, playAction),
1963         KX_PYMETHODTABLE(KX_GameObject, stopAction),
1964         KX_PYMETHODTABLE(KX_GameObject, getActionFrame),
1965         KX_PYMETHODTABLE(KX_GameObject, getActionName),
1966         KX_PYMETHODTABLE(KX_GameObject, setActionFrame),
1967         KX_PYMETHODTABLE(KX_GameObject, isPlayingAction),
1968         
1969         // dict style access for props
1970         {"get",(PyCFunction) KX_GameObject::sPyget, METH_VARARGS},
1971         
1972         {NULL,NULL} //Sentinel
1973 };
1974
1975 PyAttributeDef KX_GameObject::Attributes[] = {
1976         KX_PYATTRIBUTE_INT_RO("currentLodLevel", KX_GameObject, m_currentLodLevel),
1977         KX_PYATTRIBUTE_RO_FUNCTION("name",              KX_GameObject, pyattr_get_name),
1978         KX_PYATTRIBUTE_RO_FUNCTION("parent",    KX_GameObject, pyattr_get_parent),
1979         KX_PYATTRIBUTE_RO_FUNCTION("groupMembers",      KX_GameObject, pyattr_get_group_members),
1980         KX_PYATTRIBUTE_RO_FUNCTION("groupObject",       KX_GameObject, pyattr_get_group_object),
1981         KX_PYATTRIBUTE_RO_FUNCTION("scene",             KX_GameObject, pyattr_get_scene),
1982         KX_PYATTRIBUTE_RO_FUNCTION("life",              KX_GameObject, pyattr_get_life),
1983         KX_PYATTRIBUTE_RW_FUNCTION("mass",              KX_GameObject, pyattr_get_mass,         pyattr_set_mass),
1984         KX_PYATTRIBUTE_RO_FUNCTION("isSuspendDynamics",         KX_GameObject, pyattr_get_is_suspend_dynamics),
1985         KX_PYATTRIBUTE_RW_FUNCTION("linVelocityMin",            KX_GameObject, pyattr_get_lin_vel_min, pyattr_set_lin_vel_min),
1986         KX_PYATTRIBUTE_RW_FUNCTION("linVelocityMax",            KX_GameObject, pyattr_get_lin_vel_max, pyattr_set_lin_vel_max),
1987         KX_PYATTRIBUTE_RW_FUNCTION("angularVelocityMin", KX_GameObject, pyattr_get_ang_vel_min, pyattr_set_ang_vel_min),
1988         KX_PYATTRIBUTE_RW_FUNCTION("angularVelocityMax", KX_GameObject, pyattr_get_ang_vel_max, pyattr_set_ang_vel_max),
1989         KX_PYATTRIBUTE_RW_FUNCTION("visible",   KX_GameObject, pyattr_get_visible,      pyattr_set_visible),
1990         KX_PYATTRIBUTE_RW_FUNCTION("record_animation",  KX_GameObject, pyattr_get_record_animation,     pyattr_set_record_animation),
1991         KX_PYATTRIBUTE_BOOL_RW    ("occlusion", KX_GameObject, m_bOccluder),
1992         KX_PYATTRIBUTE_RW_FUNCTION("position",  KX_GameObject, pyattr_get_worldPosition,        pyattr_set_localPosition),
1993         KX_PYATTRIBUTE_RO_FUNCTION("localInertia",      KX_GameObject, pyattr_get_localInertia),
1994         KX_PYATTRIBUTE_RW_FUNCTION("orientation",KX_GameObject,pyattr_get_worldOrientation,pyattr_set_localOrientation),
1995         KX_PYATTRIBUTE_RW_FUNCTION("scaling",   KX_GameObject, pyattr_get_worldScaling, pyattr_set_localScaling),
1996         KX_PYATTRIBUTE_RW_FUNCTION("timeOffset",KX_GameObject, pyattr_get_timeOffset,pyattr_set_timeOffset),
1997         KX_PYATTRIBUTE_RW_FUNCTION("collisionCallbacks",                KX_GameObject, pyattr_get_collisionCallbacks,   pyattr_set_collisionCallbacks),
1998         KX_PYATTRIBUTE_RW_FUNCTION("collisionGroup",                    KX_GameObject, pyattr_get_collisionGroup, pyattr_set_collisionGroup),
1999         KX_PYATTRIBUTE_RW_FUNCTION("collisionMask",                             KX_GameObject, pyattr_get_collisionMask, pyattr_set_collisionMask),
2000         KX_PYATTRIBUTE_RW_FUNCTION("state",             KX_GameObject, pyattr_get_state,        pyattr_set_state),
2001         KX_PYATTRIBUTE_RO_FUNCTION("meshes",    KX_GameObject, pyattr_get_meshes),
2002         KX_PYATTRIBUTE_RW_FUNCTION("localOrientation",KX_GameObject,pyattr_get_localOrientation,pyattr_set_localOrientation),
2003         KX_PYATTRIBUTE_RW_FUNCTION("worldOrientation",KX_GameObject,pyattr_get_worldOrientation,pyattr_set_worldOrientation),
2004         KX_PYATTRIBUTE_RW_FUNCTION("localPosition",     KX_GameObject, pyattr_get_localPosition,        pyattr_set_localPosition),
2005         KX_PYATTRIBUTE_RW_FUNCTION("worldPosition",     KX_GameObject, pyattr_get_worldPosition,    pyattr_set_worldPosition),
2006         KX_PYATTRIBUTE_RW_FUNCTION("localScale",        KX_GameObject, pyattr_get_localScaling, pyattr_set_localScaling),
2007         KX_PYATTRIBUTE_RW_FUNCTION("worldScale",        KX_GameObject, pyattr_get_worldScaling, pyattr_set_worldScaling),
2008         KX_PYATTRIBUTE_RW_FUNCTION("localTransform",            KX_GameObject, pyattr_get_localTransform, pyattr_set_localTransform),
2009         KX_PYATTRIBUTE_RW_FUNCTION("worldTransform",            KX_GameObject, pyattr_get_worldTransform, pyattr_set_worldTransform),
2010         KX_PYATTRIBUTE_RW_FUNCTION("linearVelocity", KX_GameObject, pyattr_get_localLinearVelocity, pyattr_set_worldLinearVelocity),
2011         KX_PYATTRIBUTE_RW_FUNCTION("localLinearVelocity", KX_GameObject, pyattr_get_localLinearVelocity, pyattr_set_localLinearVelocity),
2012         KX_PYATTRIBUTE_RW_FUNCTION("worldLinearVelocity", KX_GameObject, pyattr_get_worldLinearVelocity, pyattr_set_worldLinearVelocity),
2013         KX_PYATTRIBUTE_RW_FUNCTION("angularVelocity", KX_GameObject, pyattr_get_localAngularVelocity, pyattr_set_worldAngularVelocity),
2014         KX_PYATTRIBUTE_RW_FUNCTION("localAngularVelocity", KX_GameObject, pyattr_get_localAngularVelocity, pyattr_set_localAngularVelocity),
2015         KX_PYATTRIBUTE_RW_FUNCTION("worldAngularVelocity", KX_GameObject, pyattr_get_worldAngularVelocity, pyattr_set_worldAngularVelocity),
2016         KX_PYATTRIBUTE_RW_FUNCTION("linearDamping", KX_GameObject, pyattr_get_linearDamping, pyattr_set_linearDamping),
2017         KX_PYATTRIBUTE_RW_FUNCTION("angularDamping", KX_GameObject, pyattr_get_angularDamping, pyattr_set_angularDamping),
2018         KX_PYATTRIBUTE_RO_FUNCTION("children",  KX_GameObject, pyattr_get_children),
2019         KX_PYATTRIBUTE_RO_FUNCTION("childrenRecursive", KX_GameObject, pyattr_get_children_recursive),
2020         KX_PYATTRIBUTE_RO_FUNCTION("attrDict",  KX_GameObject, pyattr_get_attrDict),
2021         KX_PYATTRIBUTE_RW_FUNCTION("color", KX_GameObject, pyattr_get_obcolor, pyattr_set_obcolor),
2022         KX_PYATTRIBUTE_RW_FUNCTION("debug",     KX_GameObject, pyattr_get_debug, pyattr_set_debug),
2023         KX_PYATTRIBUTE_RW_FUNCTION("debugRecursive",    KX_GameObject, pyattr_get_debugRecursive, pyattr_set_debugRecursive),
2024         
2025         /* experimental, don't rely on these yet */
2026         KX_PYATTRIBUTE_RO_FUNCTION("sensors",           KX_GameObject, pyattr_get_sensors),
2027         KX_PYATTRIBUTE_RO_FUNCTION("controllers",       KX_GameObject, pyattr_get_controllers),
2028         KX_PYATTRIBUTE_RO_FUNCTION("actuators",         KX_GameObject, pyattr_get_actuators),
2029         {NULL} //Sentinel
2030 };
2031
2032 PyObject *KX_GameObject::PyReplaceMesh(PyObject *args)
2033 {
2034         KX_Scene *scene = KX_GetActiveScene();
2035         
2036         PyObject *value;
2037         int use_gfx= 1, use_phys= 0;
2038         RAS_MeshObject *new_mesh;
2039         
2040         if (!PyArg_ParseTuple(args,"O|ii:replaceMesh", &value, &use_gfx, &use_phys))
2041                 return NULL;
2042         
2043         if (!ConvertPythonToMesh(value, &new_mesh, false, "gameOb.replaceMesh(value): KX_GameObject"))
2044                 return NULL;
2045         
2046         scene->ReplaceMesh(this, new_mesh, (bool)use_gfx, (bool)use_phys);
2047         Py_RETURN_NONE;
2048 }
2049
2050 PyObject *KX_GameObject::PyEndObject()
2051 {
2052         KX_Scene* scene = GetScene();
2053         
2054         scene->DelayedRemoveObject(this);
2055         
2056         Py_RETURN_NONE;
2057
2058 }
2059
2060 PyObject *KX_GameObject::PyReinstancePhysicsMesh(PyObject *args)
2061 {
2062         KX_GameObject *gameobj= NULL;
2063         RAS_MeshObject *mesh= NULL;
2064         
2065         PyObject *gameobj_py= NULL;
2066         PyObject *mesh_py= NULL;
2067
2068         if (    !PyArg_ParseTuple(args,"|OO:reinstancePhysicsMesh",&gameobj_py, &mesh_py) ||
2069                         (gameobj_py && !ConvertPythonToGameObject(gameobj_py, &gameobj, true, "gameOb.reinstancePhysicsMesh(obj, mesh): KX_GameObject")) || 
2070                         (mesh_py && !ConvertPythonToMesh(mesh_py, &mesh, true, "gameOb.reinstancePhysicsMesh(obj, mesh): KX_GameObject"))
2071                 ) {
2072                 return NULL;
2073         }
2074
2075         /* gameobj and mesh can be NULL */
2076         if (GetPhysicsController() && GetPhysicsController()->ReinstancePhysicsShape(gameobj, mesh))
2077                 Py_RETURN_TRUE;
2078
2079         Py_RETURN_FALSE;
2080 }
2081
2082 static PyObject *Map_GetItem(PyObject *self_v, PyObject *item)
2083 {
2084         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
2085         const char *attr_str= _PyUnicode_AsString(item);
2086         CValue* resultattr;
2087         PyObject *pyconvert;
2088         
2089         if (self == NULL) {
2090                 PyErr_SetString(PyExc_SystemError, "val = gameOb[key]: KX_GameObject, " BGE_PROXY_ERROR_MSG);
2091                 return NULL;
2092         }
2093         
2094         /* first see if the attributes a string and try get the cvalue attribute */
2095         if (attr_str && (resultattr=self->GetProperty(attr_str))) {
2096                 pyconvert = resultattr->ConvertValueToPython();
2097                 return pyconvert ? pyconvert:resultattr->GetProxy();
2098         }
2099         /* no CValue attribute, try get the python only m_attr_dict attribute */
2100         else if (self->m_attr_dict && (pyconvert=PyDict_GetItem(self->m_attr_dict, item))) {
2101                 
2102                 if (attr_str)
2103                         PyErr_Clear();
2104                 Py_INCREF(pyconvert);
2105                 return pyconvert;
2106         }
2107         else {
2108                 if (attr_str)   PyErr_Format(PyExc_KeyError, "value = gameOb[key]: KX_GameObject, key \"%s\" does not exist", attr_str);
2109                 else                    PyErr_SetString(PyExc_KeyError, "value = gameOb[key]: KX_GameObject, key does not exist");
2110                 return NULL;
2111         }
2112                 
2113 }
2114
2115
2116 static int Map_SetItem(PyObject *self_v, PyObject *key, PyObject *val)
2117 {
2118         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
2119         const char *attr_str= _PyUnicode_AsString(key);
2120         if (attr_str==NULL)
2121                 PyErr_Clear();
2122         
2123         if (self == NULL) {
2124                 PyErr_SetString(PyExc_SystemError, "gameOb[key] = value: KX_GameObject, " BGE_PROXY_ERROR_MSG);
2125                 return -1;
2126         }
2127         
2128         if (val==NULL) { /* del ob["key"] */
2129                 int del= 0;
2130                 
2131                 /* try remove both just in case */
2132                 if (attr_str)
2133                         del |= (self->RemoveProperty(attr_str)==true) ? 1:0;
2134                 
2135                 if (self->m_attr_dict)
2136                         del |= (PyDict_DelItem(self->m_attr_dict, key)==0) ? 1:0;
2137                 
2138                 if (del==0) {
2139                         if (attr_str)   PyErr_Format(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key \"%s\" could not be set", attr_str);
2140                         else                    PyErr_SetString(PyExc_KeyError, "del gameOb[key]: KX_GameObject, key could not be deleted");
2141                         return -1;
2142                 }
2143                 else if (self->m_attr_dict) {
2144                         PyErr_Clear(); /* PyDict_DelItem sets an error when it fails */
2145                 }
2146         }
2147         else { /* ob["key"] = value */
2148                 bool set = false;
2149                 
2150                 /* as CValue */
2151                 if (attr_str && PyObject_TypeCheck(val, &PyObjectPlus::Type)==0) /* don't allow GameObjects for eg to be assigned to CValue props */
2152                 {
2153                         CValue *vallie = self->ConvertPythonToValue(val, false, "gameOb[key] = value: ");
2154                         
2155                         if (vallie) {
2156                                 CValue* oldprop = self->GetProperty(attr_str);
2157                                 
2158                                 if (oldprop)
2159                                         oldprop->SetValue(vallie);
2160                                 else
2161                                         self->SetProperty(attr_str, vallie);
2162                                 
2163                                 vallie->Release();
2164                                 set = true;
2165                                 
2166                                 /* try remove dict value to avoid double ups */
2167                                 if (self->m_attr_dict) {
2168                                         if (PyDict_DelItem(self->m_attr_dict, key) != 0)
2169                                                 PyErr_Clear();
2170                                 }
2171                         }
2172                         else if (PyErr_Occurred()) {
2173                                 return -1;
2174                         }
2175                 }
2176                 
2177                 if (set == false) {
2178                         if (self->m_attr_dict==NULL) /* lazy init */
2179                                 self->m_attr_dict= PyDict_New();
2180                         
2181                         
2182                         if (PyDict_SetItem(self->m_attr_dict, key, val)==0)
2183                         {
2184                                 if (attr_str)
2185                                         self->RemoveProperty(attr_str); /* overwrite the CValue if it exists */
2186                                 set = true;
2187                         }
2188                         else {
2189                                 if (attr_str)   PyErr_Format(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key \"%s\" not be added to internal dictionary", attr_str);
2190                                 else                    PyErr_SetString(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key not be added to internal dictionary");
2191                         }
2192                 }
2193                 
2194                 if (set == false) {
2195                         return -1; /* pythons error value */
2196                 }
2197                 
2198         }
2199         
2200         return 0; /* success */
2201 }
2202
2203 static int Seq_Contains(PyObject *self_v, PyObject *value)
2204 {
2205         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
2206         
2207         if (self == NULL) {
2208                 PyErr_SetString(PyExc_SystemError, "val in gameOb: KX_GameObject, " BGE_PROXY_ERROR_MSG);
2209                 return -1;
2210         }
2211         
2212         if (PyUnicode_Check(value) && self->GetProperty(_PyUnicode_AsString(value)))
2213                 return 1;
2214         
2215         if (self->m_attr_dict && PyDict_GetItem(self->m_attr_dict, value))
2216                 return 1;
2217         
2218         return 0;
2219 }
2220
2221
2222 PyMappingMethods KX_GameObject::Mapping = {
2223         (lenfunc)NULL                                   ,                       /*inquiry mp_length */
2224         (binaryfunc)Map_GetItem,                /*binaryfunc mp_subscript */
2225         (objobjargproc)Map_SetItem,     /*objobjargproc mp_ass_subscript */
2226 };
2227
2228 PySequenceMethods KX_GameObject::Sequence = {
2229         NULL,           /* Cant set the len otherwise it can evaluate as false */
2230         NULL,           /* sq_concat */
2231         NULL,           /* sq_repeat */
2232         NULL,           /* sq_item */
2233         NULL,           /* sq_slice */
2234         NULL,           /* sq_ass_item */
2235         NULL,           /* sq_ass_slice */
2236         (objobjproc)Seq_Contains,       /* sq_contains */
2237         (binaryfunc) NULL, /* sq_inplace_concat */
2238         (ssizeargfunc) NULL, /* sq_inplace_repeat */
2239 };
2240
2241 PyTypeObject KX_GameObject::Type = {
2242         PyVarObject_HEAD_INIT(NULL, 0)
2243         "KX_GameObject",
2244         sizeof(PyObjectPlus_Proxy),
2245         0,
2246         py_base_dealloc,
2247         0,
2248         0,
2249         0,
2250         0,
2251         py_base_repr,
2252         0,
2253         &Sequence,
2254         &Mapping,
2255         0,0,0,
2256         NULL,
2257         NULL,
2258         0,
2259         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
2260         0,0,0,0,0,0,0,
2261         Methods,
2262         0,
2263         0,
2264         &SCA_IObject::Type,
2265         0,0,0,0,0,0,
2266         py_base_new
2267 };
2268
2269 PyObject *KX_GameObject::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2270 {
2271         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2272         return PyUnicode_From_STR_String(self->GetName());
2273 }
2274
2275 PyObject *KX_GameObject::pyattr_get_parent(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2276 {
2277         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2278         KX_GameObject* parent = self->GetParent();
2279         if (parent) {
2280                 return parent->GetProxy();
2281         }
2282         Py_RETURN_NONE;
2283 }
2284
2285 PyObject *KX_GameObject::pyattr_get_group_members(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2286 {
2287         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2288         CListValue* instances = self->GetInstanceObjects();
2289         if (instances) {
2290                 return instances->GetProxy();
2291         }
2292         Py_RETURN_NONE;
2293 }
2294
2295 PyObject* KX_GameObject::pyattr_get_collisionCallbacks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2296 {
2297         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2298
2299         // Only objects with a physics controller should have collision callbacks
2300         if (!self->GetPhysicsController()) {
2301                 PyErr_SetString(PyExc_AttributeError, "KX_GameObject.collisionCallbacks: attribute only available for objects with collisions enabled");
2302                 return NULL;
2303         }
2304
2305         // Return the existing callbacks
2306         if (self->m_collisionCallbacks == NULL)
2307         {
2308                 self->m_collisionCallbacks = PyList_New(0);
2309                 // Subscribe to collision update from KX_TouchManager
2310                 self->RegisterCollisionCallbacks();
2311         }
2312         Py_INCREF(self->m_collisionCallbacks);
2313         return self->m_collisionCallbacks;
2314 }
2315
2316 int KX_GameObject::pyattr_set_collisionCallbacks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2317 {
2318         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2319
2320         // Only objects with a physics controller should have collision callbacks
2321         if (!self->GetPhysicsController()) {
2322                 PyErr_SetString(PyExc_AttributeError, "KX_GameObject.collisionCallbacks: attribute only available for objects with collisions enabled");
2323                 return PY_SET_ATTR_FAIL;
2324         }
2325
2326         if (!PyList_CheckExact(value))
2327         {
2328                 PyErr_SetString(PyExc_ValueError, "Expected a list");
2329                 return PY_SET_ATTR_FAIL;
2330         }
2331
2332         if (self->m_collisionCallbacks == NULL) {
2333                 self->RegisterCollisionCallbacks();
2334         } else {
2335                 Py_DECREF(self->m_collisionCallbacks);
2336         }
2337
2338         Py_INCREF(value);
2339
2340
2341         self->m_collisionCallbacks = value;
2342
2343         return PY_SET_ATTR_SUCCESS;
2344 }
2345
2346 PyObject *KX_GameObject::pyattr_get_collisionGroup(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2347 {
2348         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2349         return PyLong_FromLong(self->GetUserCollisionGroup());
2350 }
2351
2352 int KX_GameObject::pyattr_set_collisionGroup(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2353 {
2354         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2355         int val = PyLong_AsLong(value);
2356
2357         if (val == -1 && PyErr_Occurred()) {
2358                 PyErr_SetString(PyExc_TypeError, "gameOb.collisionGroup = int: KX_GameObject, expected an int bit field");
2359                 return PY_SET_ATTR_FAIL;
2360         }
2361
2362         if (val < 0 || val > USHRT_MAX) {
2363                 PyErr_Format(PyExc_AttributeError, "gameOb.collisionGroup = int: KX_GameObject, expected a int bit field between 0 and %i", USHRT_MAX);
2364                 return PY_SET_ATTR_FAIL;
2365         }
2366
2367         self->SetUserCollisionGroup(val);
2368         return PY_SET_ATTR_SUCCESS;
2369 }
2370
2371 PyObject *KX_GameObject::pyattr_get_collisionMask(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2372 {
2373         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2374         return PyLong_FromLong(self->GetUserCollisionMask());
2375 }
2376
2377 int KX_GameObject::pyattr_set_collisionMask(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2378 {
2379         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2380         int val = PyLong_AsLong(value);
2381
2382         if (val == -1 && PyErr_Occurred()) {
2383                 PyErr_SetString(PyExc_TypeError, "gameOb.collisionMask = int: KX_GameObject, expected an int bit field");
2384                 return PY_SET_ATTR_FAIL;
2385         }
2386
2387         if (val < 0 || val > USHRT_MAX) {
2388                 PyErr_Format(PyExc_AttributeError, "gameOb.collisionMask = int: KX_GameObject, expected a int bit field between 0 and %i", USHRT_MAX);
2389                 return PY_SET_ATTR_FAIL;
2390         }
2391
2392         self->SetUserCollisionMask(val);
2393         return PY_SET_ATTR_SUCCESS;
2394 }
2395
2396 PyObject* KX_GameObject::pyattr_get_scene(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2397 {
2398         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
2399         KX_Scene *scene = self->GetScene();
2400         if (scene) {
2401                 return scene->GetProxy();
2402         }
2403         Py_RETURN_NONE;
2404 }
2405
2406 PyObject *KX_GameObject::pyattr_get_group_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2407 {
2408         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2409         KX_GameObject* pivot = self->GetDupliGroupObject();
2410         if (pivot) {
2411                 return pivot->GetProxy();
2412         }
2413         Py_RETURN_NONE;
2414 }
2415
2416 PyObject *KX_GameObject::pyattr_get_life(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2417 {
2418         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2419
2420         CValue *life = self->GetProperty("::timebomb");
2421         if (life)
2422                 // this convert the timebomb seconds to frames, hard coded 50.0 (assuming 50fps)
2423                 // value hardcoded in KX_Scene::AddReplicaObject()
2424                 return PyFloat_FromDouble(life->GetNumber() * 50.0);
2425         else
2426                 Py_RETURN_NONE;
2427 }
2428
2429 PyObject *KX_GameObject::pyattr_get_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2430 {
2431         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2432         PHY_IPhysicsController *spc = self->GetPhysicsController();
2433         return PyFloat_FromDouble(spc ? spc->GetMass() : 0.0);
2434 }
2435
2436 int KX_GameObject::pyattr_set_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2437 {
2438         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2439         PHY_IPhysicsController *spc = self->GetPhysicsController();
2440         MT_Scalar val = PyFloat_AsDouble(value);
2441         if (val < 0.0) { /* also accounts for non float */
2442                 PyErr_SetString(PyExc_AttributeError, "gameOb.mass = float: KX_GameObject, expected a float zero or above");
2443                 return PY_SET_ATTR_FAIL;
2444         }
2445
2446         if (spc)
2447                 spc->SetMass(val);
2448
2449         return PY_SET_ATTR_SUCCESS;
2450 }
2451
2452 PyObject *KX_GameObject::pyattr_get_is_suspend_dynamics(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2453 {
2454         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2455
2456         // Only objects with a physics controller can be suspended
2457         if (!self->GetPhysicsController()) {
2458                 PyErr_SetString(PyExc_AttributeError, "This object has not Physics Controller");
2459                 return NULL;
2460         }
2461
2462         return PyBool_FromLong(self->IsDynamicsSuspended());
2463 }
2464
2465 PyObject *KX_GameObject::pyattr_get_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2466 {
2467         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2468         PHY_IPhysicsController *spc = self->GetPhysicsController();
2469         return PyFloat_FromDouble(spc ? spc->GetLinVelocityMin() : 0.0f);
2470 }
2471
2472 int KX_GameObject::pyattr_set_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2473 {
2474         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2475         PHY_IPhysicsController *spc = self->GetPhysicsController();
2476         MT_Scalar val = PyFloat_AsDouble(value);
2477         if (val < 0.0) { /* also accounts for non float */
2478                 PyErr_SetString(PyExc_AttributeError, "gameOb.linVelocityMin = float: KX_GameObject, expected a float zero or above");
2479                 return PY_SET_ATTR_FAIL;
2480         }
2481
2482         if (spc)
2483                 spc->SetLinVelocityMin(val);
2484
2485         return PY_SET_ATTR_SUCCESS;
2486 }
2487
2488 PyObject *KX_GameObject::pyattr_get_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2489 {
2490         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2491         PHY_IPhysicsController *spc = self->GetPhysicsController();
2492         return PyFloat_FromDouble(spc ? spc->GetLinVelocityMax() : 0.0f);
2493 }
2494
2495 int KX_GameObject::pyattr_set_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2496 {
2497         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2498         PHY_IPhysicsController *spc = self->GetPhysicsController();
2499         MT_Scalar val = PyFloat_AsDouble(value);
2500         if (val < 0.0) { /* also accounts for non float */
2501                 PyErr_SetString(PyExc_AttributeError, "gameOb.linVelocityMax = float: KX_GameObject, expected a float zero or above");
2502                 return PY_SET_ATTR_FAIL;
2503         }
2504
2505         if (spc)
2506                 spc->SetLinVelocityMax(val);
2507
2508         return PY_SET_ATTR_SUCCESS;
2509 }
2510
2511 PyObject *KX_GameObject::pyattr_get_ang_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2512 {
2513         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
2514         PHY_IPhysicsController *spc = self->GetPhysicsController();
2515         return PyFloat_FromDouble(spc ? spc->GetAngularVelocityMin() : 0.0f);
2516 }
2517
2518 int KX_GameObject::pyattr_set_ang_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2519 {
2520         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
2521         PHY_IPhysicsController *spc = self->GetPhysicsController();
2522         MT_Scalar val = PyFloat_AsDouble(value);
2523         if (val < 0.0f) { /* also accounts for non float */
2524                 PyErr_SetString(PyExc_AttributeError,
2525                                 "gameOb.angularVelocityMin = float: KX_GameObject, expected a nonnegative float");
2526                 return PY_SET_ATTR_FAIL;
2527         }
2528
2529         if (spc)
2530                 spc->SetAngularVelocityMin(val);
2531
2532         return PY_SET_ATTR_SUCCESS;
2533 }
2534
2535 PyObject *KX_GameObject::pyattr_get_ang_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2536 {
2537         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
2538         PHY_IPhysicsController *spc = self->GetPhysicsController();
2539         return PyFloat_FromDouble(spc ? spc->GetAngularVelocityMax() : 0.0f);
2540 }
2541
2542 int KX_GameObject::pyattr_set_ang_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2543 {
2544         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
2545         PHY_IPhysicsController *spc = self->GetPhysicsController();
2546         MT_Scalar val = PyFloat_AsDouble(value);
2547         if (val < 0.0f) { /* also accounts for non float */
2548                 PyErr_SetString(PyExc_AttributeError,
2549                                 "gameOb.angularVelocityMax = float: KX_GameObject, expected a nonnegative float");
2550                 return PY_SET_ATTR_FAIL;
2551         }
2552
2553         if (spc)
2554                 spc->SetAngularVelocityMax(val);
2555
2556         return PY_SET_ATTR_SUCCESS;
2557 }
2558
2559
2560 PyObject *KX_GameObject::pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2561 {
2562         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2563         return PyBool_FromLong(self->GetVisible());
2564 }
2565
2566 int KX_GameObject::pyattr_set_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2567 {
2568         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2569         int param = PyObject_IsTrue( value );
2570         if (param == -1) {
2571                 PyErr_SetString(PyExc_AttributeError, "gameOb.visible = bool: KX_GameObject, expected True or False");
2572                 return PY_SET_ATTR_FAIL;
2573         }
2574
2575         self->SetVisible(param, false);
2576         self->UpdateBuckets(false);
2577         return PY_SET_ATTR_SUCCESS;
2578 }
2579
2580 PyObject *KX_GameObject::pyattr_get_record_animation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2581 {
2582         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2583         return PyBool_FromLong(self->IsRecordAnimation());
2584 }
2585
2586 int KX_GameObject::pyattr_set_record_animation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2587 {
2588         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2589         int param = PyObject_IsTrue(value);
2590         if (param == -1) {
2591                 PyErr_SetString(PyExc_AttributeError, "gameOb.record_animation = bool: KX_GameObject, expected boolean");
2592                 return PY_SET_ATTR_FAIL;
2593         }
2594
2595         self->SetRecordAnimation(param);
2596
2597         return PY_SET_ATTR_SUCCESS;
2598 }
2599
2600
2601
2602 PyObject *KX_GameObject::pyattr_get_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2603 {
2604 #ifdef USE_MATHUTILS
2605         return Vector_CreatePyObject_cb(
2606                 BGE_PROXY_FROM_REF_BORROW(self_v), 3,
2607                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_POS_GLOBAL);
2608 #else
2609         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2610         return PyObjectFrom(self->NodeGetWorldPosition());
2611 #endif
2612 }
2613
2614 int KX_GameObject::pyattr_set_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2615 {
2616         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2617         MT_Point3 pos;
2618         if (!PyVecTo(value, pos))
2619                 return PY_SET_ATTR_FAIL;
2620         
2621         self->NodeSetWorldPosition(pos);
2622         self->NodeUpdateGS(0.f);
2623         return PY_SET_ATTR_SUCCESS;
2624 }
2625
2626 PyObject *KX_GameObject::pyattr_get_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2627 {
2628 #ifdef USE_MATHUTILS
2629         return Vector_CreatePyObject_cb(
2630                 BGE_PROXY_FROM_REF_BORROW(self_v), 3,
2631                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_POS_LOCAL);
2632 #else
2633         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2634         return PyObjectFrom(self->NodeGetLocalPosition());
2635 #endif
2636 }
2637
2638 int KX_GameObject::pyattr_set_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2639 {
2640         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2641         MT_Point3 pos;
2642         if (!PyVecTo(value, pos))
2643                 return PY_SET_ATTR_FAIL;
2644         
2645         self->NodeSetLocalPosition(pos);
2646         self->NodeUpdateGS(0.f);
2647         return PY_SET_ATTR_SUCCESS;
2648 }
2649
2650 PyObject *KX_GameObject::pyattr_get_localInertia(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2651 {
2652 #ifdef USE_MATHUTILS
2653         return Vector_CreatePyObject_cb(
2654                 BGE_PROXY_FROM_REF_BORROW(self_v), 3,
2655                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_INERTIA_LOCAL);
2656 #else
2657         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2658         if (self->GetPhysicsController1())
2659                 return PyObjectFrom(self->GetPhysicsController1()->GetLocalInertia());
2660         return Py_BuildValue("fff", 0.0f, 0.0f, 0.0f);
2661 #endif
2662 }
2663
2664 PyObject *KX_GameObject::pyattr_get_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2665 {
2666 #ifdef USE_MATHUTILS
2667         return Matrix_CreatePyObject_cb(
2668                 BGE_PROXY_FROM_REF_BORROW(self_v), 3, 3,
2669                 mathutils_kxgameob_matrix_cb_index, MATHUTILS_MAT_CB_ORI_GLOBAL);
2670 #else
2671         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2672         return PyObjectFrom(self->NodeGetWorldOrientation());
2673 #endif
2674 }
2675
2676 int KX_GameObject::pyattr_set_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2677 {
2678         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2679         
2680         /* if value is not a sequence PyOrientationTo makes an error */
2681         MT_Matrix3x3 rot;
2682         if (!PyOrientationTo(value, rot, "gameOb.worldOrientation = sequence: KX_GameObject, "))
2683                 return PY_SET_ATTR_FAIL;
2684
2685         self->NodeSetGlobalOrientation(rot);
2686         
2687         self->NodeUpdateGS(0.f);
2688         return PY_SET_ATTR_SUCCESS;
2689 }
2690
2691 PyObject *KX_GameObject::pyattr_get_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2692 {
2693 #ifdef USE_MATHUTILS
2694         return Matrix_CreatePyObject_cb(
2695                 BGE_PROXY_FROM_REF_BORROW(self_v), 3, 3,
2696                 mathutils_kxgameob_matrix_cb_index, MATHUTILS_MAT_CB_ORI_LOCAL);
2697 #else
2698         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2699         return PyObjectFrom(self->NodeGetLocalOrientation());
2700 #endif
2701 }
2702
2703 int KX_GameObject::pyattr_set_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2704 {
2705         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2706         
2707         /* if value is not a sequence PyOrientationTo makes an error */
2708         MT_Matrix3x3 rot;
2709         if (!PyOrientationTo(value, rot, "gameOb.localOrientation = sequence: KX_GameObject, "))
2710                 return PY_SET_ATTR_FAIL;
2711
2712         self->NodeSetLocalOrientation(rot);
2713         self->NodeUpdateGS(0.f);
2714         return PY_SET_ATTR_SUCCESS;
2715 }
2716
2717 PyObject *KX_GameObject::pyattr_get_worldScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2718 {
2719 #ifdef USE_MATHUTILS
2720         return Vector_CreatePyObject_cb(
2721                 BGE_PROXY_FROM_REF_BORROW(self_v), 3,
2722                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_SCALE_GLOBAL);
2723 #else
2724         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2725         return PyObjectFrom(self->NodeGetWorldScaling());
2726 #endif
2727 }
2728
2729 int KX_GameObject::pyattr_set_worldScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2730 {
2731         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2732         MT_Vector3 scale;
2733         if (!PyVecTo(value, scale))
2734                 return PY_SET_ATTR_FAIL;
2735
2736         self->NodeSetWorldScale(scale);
2737         self->NodeUpdateGS(0.f);
2738         return PY_SET_ATTR_SUCCESS;
2739 }
2740
2741 PyObject *KX_GameObject::pyattr_get_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2742 {
2743 #ifdef USE_MATHUTILS
2744         return Vector_CreatePyObject_cb(
2745                 BGE_PROXY_FROM_REF_BORROW(self_v), 3,
2746                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_SCALE_LOCAL);
2747 #else
2748         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2749         return PyObjectFrom(self->NodeGetLocalScaling());
2750 #endif
2751 }
2752
2753 int KX_GameObject::pyattr_set_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2754 {
2755         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2756         MT_Vector3 scale;
2757         if (!PyVecTo(value, scale))
2758                 return PY_SET_ATTR_FAIL;
2759
2760         self->NodeSetLocalScale(scale);
2761         self->NodeUpdateGS(0.f);
2762         return PY_SET_ATTR_SUCCESS;
2763 }
2764
2765 PyObject *KX_GameObject::pyattr_get_localTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2766 {
2767         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2768
2769         double mat[16];
2770
2771         MT_Transform trans;
2772         
2773         trans.setOrigin(self->GetSGNode()->GetLocalPosition());
2774         trans.setBasis(self->GetSGNode()->GetLocalOrientation());
2775         
2776         MT_Vector3 scaling = self->GetSGNode()->GetLocalScale();
2777         trans.scale(scaling[0], scaling[1], scaling[2]);
2778
2779         trans.getValue(mat);
2780
2781         return PyObjectFrom(MT_Matrix4x4(mat));
2782 }
2783
2784 int KX_GameObject::pyattr_set_localTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2785 {
2786         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2787         MT_Matrix4x4 temp;
2788         if (!PyMatTo(value, temp))
2789                 return PY_SET_ATTR_FAIL;
2790
2791         float transform[4][4];
2792         float loc[3], size[3];
2793         float rot[3][3];
2794         MT_Matrix3x3 orientation;
2795
2796         temp.getValue(*transform);
2797         mat4_to_loc_rot_size(loc, rot, size, transform);
2798
2799         self->NodeSetLocalPosition(MT_Point3(loc));
2800
2801         //MT_Matrix3x3's constructor expects a 4x4 matrix
2802         orientation = MT_Matrix3x3();
2803         orientation.setValue3x3(*rot);
2804         self->NodeSetLocalOrientation(orientation);
2805
2806         self->NodeSetLocalScale(MT_Vector3(size));
2807
2808         return PY_SET_ATTR_SUCCESS;
2809 }
2810
2811 PyObject *KX_GameObject::pyattr_get_worldTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2812 {
2813         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2814
2815         return PyObjectFrom(MT_Matrix4x4(self->GetOpenGLMatrix()));
2816 }
2817
2818 int KX_GameObject::pyattr_set_worldTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2819 {
2820         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2821         MT_Matrix4x4 temp;
2822         if (!PyMatTo(value, temp))
2823                 return PY_SET_ATTR_FAIL;
2824
2825         float transform[4][4];
2826         float loc[3], size[3];
2827         float rot[3][3];
2828         MT_Matrix3x3 orientation;
2829
2830         temp.getValue(*transform);
2831         mat4_to_loc_rot_size(loc, rot, size, transform);
2832
2833         self->NodeSetWorldPosition(MT_Point3(loc));
2834
2835         //MT_Matrix3x3's constructor expects a 4x4 matrix
2836         orientation = MT_Matrix3x3();
2837         orientation.setValue3x3(*rot);
2838         self->NodeSetGlobalOrientation(orientation);
2839
2840         self->NodeSetWorldScale(MT_Vector3(size));
2841
2842         return PY_SET_ATTR_SUCCESS;
2843 }
2844
2845 PyObject *KX_GameObject::pyattr_get_worldLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2846 {
2847 #ifdef USE_MATHUTILS
2848         return Vector_CreatePyObject_cb(
2849                 BGE_PROXY_FROM_REF_BORROW(self_v), 3,
2850                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_LINVEL_GLOBAL);
2851 #else
2852         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2853         return PyObjectFrom(GetLinearVelocity(false));
2854 #endif
2855 }
2856
2857 int KX_GameObject::pyattr_set_worldLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2858 {
2859         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2860         MT_Vector3 velocity;
2861         if (!PyVecTo(value, velocity))
2862                 return PY_SET_ATTR_FAIL;
2863
2864         self->setLinearVelocity(velocity, false);
2865
2866         return PY_SET_ATTR_SUCCESS;
2867 }
2868
2869 PyObject *KX_GameObject::pyattr_get_localLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2870 {
2871 #ifdef USE_MATHUTILS
2872         return Vector_CreatePyObject_cb(
2873                 BGE_PROXY_FROM_REF_BORROW(self_v), 3,
2874                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_LINVEL_LOCAL);
2875 #else
2876         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2877         return PyObjectFrom(GetLinearVelocity(true));
2878 #endif
2879 }
2880
2881 int KX_GameObject::pyattr_set_localLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2882 {
2883         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2884         MT_Vector3 velocity;
2885         if (!PyVecTo(value, velocity))
2886                 return PY_SET_ATTR_FAIL;
2887
2888         self->setLinearVelocity(velocity, true);
2889
2890         return PY_SET_ATTR_SUCCESS;
2891 }
2892
2893 PyObject *KX_GameObject::pyattr_get_worldAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2894 {
2895 #ifdef USE_MATHUTILS
2896         return Vector_CreatePyObject_cb(
2897                 BGE_PROXY_FROM_REF_BORROW(self_v), 3,
2898                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_ANGVEL_GLOBAL);
2899 #else
2900         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2901         return PyObjectFrom(GetAngularVelocity(false));
2902 #endif
2903 }
2904
2905 int KX_GameObject::pyattr_set_worldAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2906 {
2907         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2908         MT_Vector3 velocity;
2909         if (!PyVecTo(value, velocity))
2910                 return PY_SET_ATTR_FAIL;
2911
2912         self->setAngularVelocity(velocity, false);
2913
2914         return PY_SET_ATTR_SUCCESS;
2915 }
2916
2917 PyObject *KX_GameObject::pyattr_get_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2918 {
2919 #ifdef USE_MATHUTILS
2920         return Vector_CreatePyObject_cb(
2921                 BGE_PROXY_FROM_REF_BORROW(self_v), 3,
2922                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_ANGVEL_LOCAL);
2923 #else
2924         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2925         return PyObjectFrom(GetAngularVelocity(true));
2926 #endif
2927 }
2928
2929 int KX_GameObject::pyattr_set_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2930 {
2931         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2932         MT_Vector3 velocity;
2933         if (!PyVecTo(value, velocity))
2934                 return PY_SET_ATTR_FAIL;
2935
2936         self->setAngularVelocity(velocity, true);
2937
2938         return PY_SET_ATTR_SUCCESS;
2939 }
2940
2941 PyObject *KX_GameObject::pyattr_get_linearDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2942 {
2943         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2944         return PyFloat_FromDouble(self->getLinearDamping());
2945 }
2946
2947 int KX_GameObject::pyattr_set_linearDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2948 {
2949         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2950         float val = PyFloat_AsDouble(value);
2951         self->setLinearDamping(val);
2952         return PY_SET_ATTR_SUCCESS;
2953 }
2954
2955 PyObject *KX_GameObject::pyattr_get_angularDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2956 {
2957         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2958         return PyFloat_FromDouble(self->getAngularDamping());
2959 }
2960
2961 int KX_GameObject::pyattr_set_angularDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2962 {
2963         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2964         float val = PyFloat_AsDouble(value);
2965         self->setAngularDamping(val);
2966         return PY_SET_ATTR_SUCCESS;
2967 }
2968
2969
2970 PyObject *KX_GameObject::pyattr_get_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2971 {
2972         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2973         SG_Node* sg_parent;
2974         if (self->GetSGNode() && (sg_parent = self->GetSGNode()->GetSGParent()) != NULL && sg_parent->IsSlowParent()) {
2975                 return PyFloat_FromDouble(static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->GetTimeOffset());
2976         } else {
2977                 return PyFloat_FromDouble(0.0);
2978         }
2979 }
2980
2981 int KX_GameObject::pyattr_set_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2982 {
2983         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2984         if (self->GetSGNode()) {
2985                 MT_Scalar val = PyFloat_AsDouble(value);
2986                 SG_Node *sg_parent= self->GetSGNode()->GetSGParent();
2987                 if (val < 0.0) { /* also accounts for non float */
2988                         PyErr_SetString(PyExc_AttributeError, "gameOb.timeOffset = float: KX_GameObject, expected a float zero or above");
2989                         return PY_SET_ATTR_FAIL;
2990                 }
2991                 if (sg_parent && sg_parent->IsSlowParent())
2992                         static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->SetTimeOffset(val);
2993         }
2994         return PY_SET_ATTR_SUCCESS;
2995 }
2996
2997 PyObject *KX_GameObject::pyattr_get_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2998 {
2999         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
3000         int state = 0;
3001         state |= self->GetState();
3002         return PyLong_FromLong(state);
3003 }
3004
3005 int KX_GameObject::pyattr_set_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
3006 {
3007         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
3008         int state_i = PyLong_AsLong(value);
3009         unsigned int state = 0;
3010         
3011         if (state_i == -1 && PyErr_Occurred()) {
3012                 PyErr_SetString(PyExc_TypeError, "gameOb.state = int: KX_GameObject, expected an int bit field");
3013                 return PY_SET_ATTR_FAIL;
3014         }
3015         
3016         state |= state_i;
3017         if ((state & ((1<<30)-1)) == 0) {
3018                 PyErr_SetString(PyExc_AttributeError, "gameOb.state = int: KX_GameObject, state bitfield was not between 0 and 30 (1<<0 and 1<<29)");
3019                 return PY_SET_ATTR_FAIL;
3020         }
3021         self->SetState(state);
3022         return PY_SET_ATTR_SUCCESS;
3023 }
3024
3025 PyObject *KX_GameObject::pyattr_get_meshes(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3026 {
3027         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
3028         PyObject *meshes= PyList_New(self->m_meshes.size());
3029         int i;
3030         
3031         for (i=0; i < (int)self->m_meshes.size(); i++)
3032         {
3033                 KX_MeshProxy* meshproxy = new KX_MeshProxy(self->m_meshes[i]);
3034                 PyList_SET_ITEM(meshes, i, meshproxy->NewProxy(true));
3035         }
3036         
3037         return meshes;
3038 }
3039
3040 PyObject *KX_GameObject::pyattr_get_obcolor(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3041 {
3042 #ifdef USE_MATHUTILS
3043         return Vector_CreatePyObject_cb(
3044                 BGE_PROXY_FROM_REF_BORROW(self_v), 4,
3045                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_OBJECT_COLOR);
3046 #else
3047         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
3048         return PyObjectFrom(self->GetObjectColor());
3049 #endif
3050 }
3051
3052 int KX_GameObject::pyattr_set_obcolor(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
3053 {
3054         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
3055         MT_Vector4 obcolor;
3056         if (!PyVecTo(value, obcolor))
3057                 return PY_SET_ATTR_FAIL;
3058
3059         self->SetObjectColor(obcolor);
3060         return PY_SET_ATTR_SUCCESS;
3061 }
3062
3063 /* These are experimental! */
3064 PyObject *KX_GameObject::pyattr_get_sensors(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3065 {
3066         return KX_PythonSeq_CreatePyObject((static_cast<KX_GameObject*>(self_v))->m_proxy, KX_PYGENSEQ_OB_TYPE_SENSORS);
3067 }
3068
3069 PyObject *KX_GameObject::pyattr_get_controllers(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3070 {
3071         return KX_PythonSeq_CreatePyObject((static_cast<KX_GameObject*>(self_v))->m_proxy, KX_PYGENSEQ_OB_TYPE_CONTROLLERS);
3072 }
3073
3074 PyObject *KX_GameObject::pyattr_get_actuators(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3075 {
3076         return KX_PythonSeq_CreatePyObject((static_cast<KX_GameObject*>(self_v))->m_proxy, KX_PYGENSEQ_OB_TYPE_ACTUATORS);
3077 }
3078 /* End experimental */
3079
3080 PyObject *KX_GameObject::pyattr_get_children(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3081 {
3082         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
3083         return self->GetChildren()->NewProxy(true);
3084 }
3085
3086 PyObject *KX_GameObject::pyattr_get_children_recursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3087 {
3088         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
3089         return self->GetChildrenRecursive()->NewProxy(true);
3090 }
3091
3092 PyObject *KX_GameObject::pyattr_get_attrDict(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3093 {
3094         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
3095         
3096         if (self->m_attr_dict==NULL)
3097                 self->m_attr_dict= PyDict_New();
3098         
3099         Py_INCREF(self->m_attr_dict);
3100         return self->m_attr_dict;
3101 }
3102
3103 PyObject *KX_GameObject::pyattr_get_debug(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3104 {
3105         KX_Scene *scene = KX_GetActiveScene();
3106         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
3107
3108         return PyBool_FromLong(scene->ObjectInDebugList(self));
3109 }
3110
3111 int KX_GameObject::pyattr_set_debug(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
3112 {
3113         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
3114         int param = PyObject_IsTrue(value);
3115
3116         if (param == -1) {
3117                 PyErr_SetString(PyExc_AttributeError, "gameOb.debug = bool: KX_GameObject, expected True or False");
3118                 return PY_SET_ATTR_FAIL;
3119         }
3120
3121         self->SetUseDebugProperties(param, false);
3122
3123         return PY_SET_ATTR_SUCCESS;
3124 }
3125
3126 PyObject *KX_GameObject::pyattr_get_debugRecursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3127 {
3128         KX_Scene *scene = KX_GetActiveScene();
3129         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
3130
3131         return PyBool_FromLong(scene->ObjectInDebugList(self));
3132 }
3133
3134 int KX_GameObject::pyattr_set_debugRecursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
3135 {
3136         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
3137         int param = PyObject_IsTrue(value);
3138
3139         if (param == -1) {
3140                 PyErr_SetString(PyExc_AttributeError, "gameOb.debugRecursive = bool: KX_GameObject, expected True or False");
3141                 return PY_SET_ATTR_FAIL;
3142         }
3143
3144         self->SetUseDebugProperties(param, true);
3145
3146         return PY_SET_ATTR_SUCCESS;
3147 }
3148
3149 PyObject *KX_GameObject::PyApplyForce(PyObject *args)
3150 {
3151         int local = 0;
3152         PyObject *pyvect;
3153
3154         if (PyArg_ParseTuple(args, "O|i:applyForce", &pyvect, &local)) {
3155                 MT_Vector3 force;
3156                 if (PyVecTo(pyvect, force)) {
3157                         ApplyForce(force, (local!=0));
3158                         Py_RETURN_NONE;
3159                 }
3160         }
3161         return NULL;
3162 }
3163
3164 PyObject *KX_GameObject::PyApplyTorque(PyObject *args)
3165 {
3166         int local = 0;
3167         PyObject *pyvect;
3168
3169         if (PyArg_ParseTuple(args, "O|i:applyTorque", &pyvect, &local)) {
3170                 MT_Vector3 torque;
3171                 if (PyVecTo(pyvect, torque)) {
3172                         ApplyTorque(torque, (local!=0));
3173                         Py_RETURN_NONE;
3174                 }
3175         }
3176         return NULL;
3177 }
3178
3179 PyObject *KX_GameObject::PyApplyRotation(PyObject *args)
3180 {
3181         int local = 0;
3182         PyObject *pyvect;
3183
3184         if (PyArg_ParseTuple(args, "O|i:applyRotation", &pyvect, &local)) {
3185                 MT_Vector3 rotation;
3186                 if (PyVecTo(pyvect, rotation)) {
3187                         ApplyRotation(rotation, (local!=0));
3188                         Py_RETURN_NONE;
3189                 }
3190         }
3191         return NULL;
3192 }
3193
3194 PyObject *KX_GameObject::PyApplyMovement(PyObject *args)
3195 {
3196         int local = 0;
3197         PyObject *pyvect;
3198
3199         if (PyArg_ParseTuple(args, "O|i:applyMovement", &pyvect, &local)) {
3200                 MT_Vector3 movement;
3201                 if (PyVecTo(pyvect, movement)) {
3202                         ApplyMovement(movement, (local!=0));
3203                         Py_RETURN_NONE;
3204                 }
3205         }
3206         return NULL;
3207 }
3208
3209 PyObject *KX_GameObject::PyGetLinearVelocity(PyObject *args)
3210 {
3211         // only can get the velocity if we have a physics object connected to us...
3212         int local = 0;
3213         if (PyArg_ParseTuple(args,"|i:getLinearVelocity",&local))
3214         {
3215                 return PyObjectFrom(GetLinearVelocity((local!=0)));
3216         }
3217         else
3218         {
3219                 return NULL;
3220         }
3221 }
3222
3223 PyObject *KX_GameObject::PySetLinearVelocity(PyObject *args)
3224 {
3225         int local = 0;
3226         PyObject *pyvect;
3227         
3228         if (PyArg_ParseTuple(args,"O|i:setLinearVelocity",&pyvect,&local)) {
3229                 MT_Vector3 velocity;
3230                 if (PyVecTo(pyvect, velocity)) {
3231                         setLinearVelocity(velocity, (local!=0));
3232                         Py_RETURN_NONE;
3233                 }
3234         }
3235         return NULL;
3236 }
3237
3238 PyObject *KX_GameObject::PyGetAngularVelocity(PyObject *args)
3239 {
3240         // only can get the velocity if we have a physics object connected to us...
3241         int local = 0;
3242         if (PyArg_ParseTuple(args,"|i:getAngularVelocity",&local))
3243         {
3244                 return PyObjectFrom(GetAngularVelocity((local!=0)));
3245         }
3246         else
3247         {
3248                 return NULL;
3249         }
3250 }
3251
3252 PyObject *KX_GameObject::PySetAngularVelocity(PyObject *args)
3253 {
3254         int local = 0;
3255         PyObject *pyvect;
3256         
3257         if (PyArg_ParseTuple(args,"O|i:setAngularVelocity",&pyvect,&local)) {
3258                 MT_Vector3 velocity;
3259                 if (PyVecTo(pyvect, velocity)) {
3260                         setAngularVelocity(velocity, (local!=0));
3261                         Py_RETURN_NONE;
3262                 }
3263         }
3264         return NULL;
3265 }
3266
3267 PyObject *KX_GameObject::PySetDamping(PyObject *args)
3268 {
3269         float linear;
3270         float angular;
3271
3272         if (!PyArg_ParseTuple(args,"ff|i:setDamping", &linear, &angular))
3273                 return NULL;
3274
3275         setDamping(linear, angular);
3276         Py_RETURN_NONE;
3277 }
3278
3279 PyObject *KX_GameObject::PySetVisible(PyObject *args)
3280 {
3281         int visible, recursive = 0;
3282         if (!PyArg_ParseTuple(args,"i|i:setVisible",&visible, &recursive))
3283                 return NULL;
3284         
3285         SetVisible(visible ? true:false, recursive ? true:false);
3286         UpdateBuckets(recursive ? true:false);
3287         Py_RETURN_NONE;
3288         
3289 }
3290
3291 PyObject *KX_GameObject::PySetOcclusion(PyObject *args)
3292 {
3293         int occlusion, recursive = 0;
3294         if (!PyArg_ParseTuple(args,"i|i:setOcclusion",&occlusion, &recursive))
3295                 return NULL;
3296         
3297         SetOccluder(occlusion ? true:false, recursive ? true:false);
3298         Py_RETURN_NONE;
3299 }
3300
3301 PyObject *KX_GameObject::PyGetVelocity(PyObject *args)
3302 {
3303         // only can get the velocity if we have a physics object connected to us...
3304         MT_Point3 point(0.0,0.0,0.0);
3305         PyObject *pypos = NULL;
3306         
3307         if (!PyArg_ParseTuple(args, "|O:getVelocity", &pypos) || (pypos && !PyVecTo(pypos, point)))
3308                 return NULL;
3309
3310         return PyObjectFrom(GetVelocity(point));
3311 }
3312
3313 PyObject *KX_GameObject::PyGetReactionForce()
3314 {
3315         // only can get the velocity if we have a physics object connected to us...
3316         
3317         // XXX - Currently not working with bullet intergration, see KX_BulletPhysicsController.cpp's getReactionForce
3318 #if 0
3319         if (GetPhysicsController1())
3320                 return PyObjectFrom(GetPhysicsController1()->getReactionForce());
3321         return PyObjectFrom(dummy_point);
3322 #endif
3323         
3324         return Py_BuildValue("fff", 0.0, 0.0, 0.0);
3325         
3326 }
3327
3328
3329
3330 PyObject *KX_GameObject::PyEnableRigidBody()
3331 {
3332         if (GetPhysicsController())
3333                 GetPhysicsController()->SetRigidBody(true);
3334
3335         Py_RETURN_NONE;
3336 }
3337
3338
3339
3340 PyObject *KX_GameObject::PyDisableRigidBody()
3341 {
3342         if (GetPhysicsController())
3343                 GetPhysicsController()->SetRigidBody(false);
3344
3345         Py_RETURN_NONE;
3346 }
3347
3348
3349 PyObject *KX_GameObject::PySetParent(PyObject *args)
3350 {
3351         KX_Scene *scene = KX_GetActiveScene();
3352         PyObject *pyobj;
3353         KX_GameObject *obj;
3354         int addToCompound=1, ghost=1;
3355         
3356         if (!PyArg_ParseTuple(args,"O|ii:setParent", &pyobj, &addToCompound, &ghost)) {
3357                 return NULL; // Python sets a simple error
3358         }
3359         if (!ConvertPythonToGameObject(pyobj, &obj, true, "gameOb.setParent(obj): KX_GameObject"))
3360                 return NULL;
3361         if (obj)
3362                 this->SetParent(scene, obj, addToCompound, ghost);
3363         Py_RETURN_NONE;
3364 }
3365
3366 PyObject *KX_GameObject::PyRemoveParent()
3367 {
3368         KX_Scene *scene = KX_GetActiveScene();
3369         
3370         this->RemoveParent(scene);
3371         Py_RETURN_NONE;
3372 }
3373
3374
3375 PyObject *KX_GameObject::PySetCollisionMargin(PyObject *value)
3376 {
3377         float collisionMargin = PyFloat_AsDouble(value);
3378         
3379         if (collisionMargin==-1 && PyErr_Occurred()) {
3380                 PyErr_SetString(PyExc_TypeError, "expected a float");
3381                 return NULL;
3382         }
3383         
3384         if (m_pPhysicsController)
3385         {
3386                 m_pPhysicsController->SetMargin(collisionMargin);
3387                 Py_RETURN_NONE;
3388         }
3389         PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller");
3390         return NULL;
3391 }
3392
3393
3394
3395 PyObject *KX_GameObject::PyApplyImpulse(PyObject *args)
3396 {
3397         PyObject *pyattach;
3398         PyObject *pyimpulse;
3399         int local = 0;
3400         
3401         if (!m_pPhysicsController)      {
3402                 PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller");
3403                 return NULL;
3404         }
3405         
3406         if (PyArg_ParseTuple(args, "OO|i:applyImpulse", &pyattach, &pyimpulse, &local))
3407         {
3408                 MT_Point3  attach;
3409                 MT_Vector3 impulse;
3410                 if (PyVecTo(pyattach, attach) && PyVecTo(pyimpulse, impulse))
3411                 {
3412                         m_pPhysicsController->ApplyImpulse(attach, impulse, (local!=0));
3413                         Py_RETURN_NONE;
3414                 }
3415
3416         }
3417         
3418         return NULL;
3419 }
3420
3421
3422