Fix warnings reported by MSVC
[blender.git] / source / gameengine / Ketsji / KX_GameObject.cpp
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  * Game object wrapper
27  */
28
29 /** \file gameengine/Ketsji/KX_GameObject.cpp
30  *  \ingroup ketsji
31  */
32
33 #ifdef _MSC_VER
34   /* This warning tells us about truncation of __long__ stl-generated names.
35    * It can occasionally cause DevStudio to have internal compiler warnings. */
36 #  pragma warning( disable:4786 )
37 #endif
38
39 #include "RAS_IPolygonMaterial.h"
40 #include "KX_BlenderMaterial.h"
41 #include "KX_GameObject.h"
42 #include "KX_Camera.h" // only for their ::Type
43 #include "KX_Light.h"  // only for their ::Type
44 #include "KX_FontObject.h"  // only for their ::Type
45 #include "RAS_MeshObject.h"
46 #include "KX_NavMeshObject.h"
47 #include "KX_MeshProxy.h"
48 #include "KX_PolyProxy.h"
49 #include <stdio.h> // printf
50 #include "SG_Controller.h"
51 #include "PHY_IGraphicController.h"
52 #include "SG_Node.h"
53 #include "KX_ClientObjectInfo.h"
54 #include "RAS_BucketManager.h"
55 #include "KX_RayCast.h"
56 #include "KX_PythonInit.h"
57 #include "KX_PyMath.h"
58 #include "SCA_IActuator.h"
59 #include "SCA_ISensor.h"
60 #include "SCA_IController.h"
61 #include "NG_NetworkScene.h" //Needed for sendMessage()
62 #include "KX_ObstacleSimulation.h"
63 #include "KX_Scene.h"
64
65 #include "BKE_object.h"
66
67 #include "BL_ActionManager.h"
68 #include "BL_Action.h"
69
70 #include "EXP_PyObjectPlus.h" /* python stuff */
71 #include "EXP_ListWrapper.h"
72 #include "BLI_utildefines.h"
73
74 #ifdef WITH_PYTHON
75 #  include "EXP_PythonCallBack.h"
76 #  include "python_utildefines.h"
77 #endif
78
79 // This file defines relationships between parents and children
80 // in the game engine.
81
82 #include "KX_SG_NodeRelationships.h"
83
84 #include "BLI_math.h"
85
86 static MT_Point3 dummy_point= MT_Point3(0.0f, 0.0f, 0.0f);
87 static MT_Vector3 dummy_scaling = MT_Vector3(1.0f, 1.0f, 1.0f);
88 static MT_Matrix3x3 dummy_orientation = MT_Matrix3x3(1.0f, 0.0f, 0.0f,
89                                                      0.0f, 1.0f, 0.0f,
90                                                      0.0f, 0.0f, 1.0f);
91
92 KX_GameObject::KX_GameObject(
93         void* sgReplicationInfo,
94         SG_Callbacks callbacks)
95     : SCA_IObject(),
96       m_bDyna(false),
97       m_layer(0),
98       m_currentLodLevel(0),
99       m_previousLodLevel(0),
100       m_pBlenderObject(NULL),
101       m_pBlenderGroupObject(NULL),
102       m_bUseObjectColor(false),
103       m_bIsNegativeScaling(false),
104       m_objectColor(1.0f, 1.0f, 1.0f, 1.0f),
105       m_bVisible(true),
106       m_bCulled(true),
107       m_bOccluder(false),
108       m_pPhysicsController(NULL),
109       m_pGraphicController(NULL),
110       m_pObstacleSimulation(NULL),
111       m_pInstanceObjects(NULL),
112       m_pDupliGroupObject(NULL),
113       m_actionManager(NULL),
114       m_bRecordAnimation(false),
115       m_isDeformable(false)
116
117 #ifdef WITH_PYTHON
118     , m_attr_dict(NULL),
119     m_collisionCallbacks(NULL)
120 #endif
121 {
122         m_ignore_activity_culling = false;
123         m_pClient_info = new KX_ClientObjectInfo(this, KX_ClientObjectInfo::ACTOR);
124         m_pSGNode = new SG_Node(this,sgReplicationInfo,callbacks);
125
126         // define the relationship between this node and it's parent.
127         
128         KX_NormalParentRelation * parent_relation = 
129                 KX_NormalParentRelation::New();
130         m_pSGNode->SetParentRelation(parent_relation);
131 };
132
133
134
135 KX_GameObject::~KX_GameObject()
136 {
137 #ifdef WITH_PYTHON
138         if (m_attr_dict) {
139                 PyDict_Clear(m_attr_dict); /* in case of circular refs or other weird cases */
140                 /* Py_CLEAR: Py_DECREF's and NULL's */
141                 Py_CLEAR(m_attr_dict);
142         }
143         // Unregister collision callbacks
144         // Do this before we start freeing physics information like m_pClient_info
145         if (m_collisionCallbacks){
146                 UnregisterCollisionCallbacks();
147                 Py_CLEAR(m_collisionCallbacks);
148         }
149 #endif // WITH_PYTHON
150
151         RemoveMeshes();
152
153         // is this delete somewhere ?
154         //if (m_sumoObj)
155         //      delete m_sumoObj;
156         delete m_pClient_info;
157         //if (m_pSGNode)
158         //      delete m_pSGNode;
159         if (m_pSGNode)
160         {
161                 // must go through controllers and make sure they will not use us anymore
162                 // This is important for KX_BulletPhysicsControllers that unregister themselves
163                 // from the object when they are deleted.
164                 SGControllerList::iterator contit;
165                 SGControllerList& controllers = m_pSGNode->GetSGControllerList();
166                 for (contit = controllers.begin();contit!=controllers.end();++contit)
167                 {
168                         (*contit)->ClearObject();
169                 }
170                 m_pSGNode->SetSGClientObject(NULL);
171
172                 /* m_pSGNode is freed in KX_Scene::RemoveNodeDestructObject */
173         }
174         if (m_pGraphicController)
175         {
176                 delete m_pGraphicController;
177         }
178
179         if (m_pPhysicsController)
180         {
181                 delete m_pPhysicsController;
182         }
183
184         if (m_pObstacleSimulation)
185         {
186                 m_pObstacleSimulation->DestroyObstacleForObj(this);
187         }
188
189         if (m_actionManager)
190         {
191                 delete m_actionManager;
192         }
193
194         if (m_pDupliGroupObject)
195         {
196                 m_pDupliGroupObject->Release();
197         }
198
199         if (m_pInstanceObjects)
200         {
201                 m_pInstanceObjects->Release();
202         }
203 }
204
205 KX_GameObject* KX_GameObject::GetClientObject(KX_ClientObjectInfo *info)
206 {
207         if (!info)
208                 return NULL;
209         return info->m_gameobject;
210 }
211
212 CValue* KX_GameObject:: Calc(VALUE_OPERATOR op, CValue *val) 
213 {
214         return NULL;
215 }
216
217
218
219 CValue* KX_GameObject::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val)
220 {
221         return NULL;
222 }
223
224
225
226 const STR_String & KX_GameObject::GetText()
227 {
228         return m_text;
229 }
230
231
232
233 double KX_GameObject::GetNumber()
234 {
235         return 0;
236 }
237
238
239
240 STR_String& KX_GameObject::GetName()
241 {
242         return m_name;
243 }
244
245
246 /* Set the name of the value */
247 void KX_GameObject::SetName(const char *name)
248 {
249         m_name = name;
250 }
251
252 PHY_IPhysicsController* KX_GameObject::GetPhysicsController()
253 {
254         return m_pPhysicsController;
255 }
256
257 KX_GameObject* KX_GameObject::GetDupliGroupObject()
258
259         return m_pDupliGroupObject;
260 }
261
262 CListValue* KX_GameObject::GetInstanceObjects()
263
264         return m_pInstanceObjects;
265 }
266
267 void KX_GameObject::AddInstanceObjects(KX_GameObject* obj)
268 {
269         if (!m_pInstanceObjects)
270                 m_pInstanceObjects = new CListValue();
271
272         obj->AddRef();
273         m_pInstanceObjects->Add(obj);
274 }
275
276 void KX_GameObject::RemoveInstanceObject(KX_GameObject* obj)
277 {
278         assert(m_pInstanceObjects);
279         m_pInstanceObjects->RemoveValue(obj);
280         obj->Release();
281 }
282
283 void KX_GameObject::RemoveDupliGroupObject()
284 {
285         if (m_pDupliGroupObject) {
286                 m_pDupliGroupObject->Release();
287                 m_pDupliGroupObject = NULL;
288         }
289 }
290
291 void KX_GameObject::SetDupliGroupObject(KX_GameObject* obj)
292 {
293         obj->AddRef();
294         m_pDupliGroupObject = obj;
295 }
296
297 void KX_GameObject::AddConstraint(bRigidBodyJointConstraint *cons)
298 {
299         m_constraints.push_back(cons);
300 }
301
302 std::vector<bRigidBodyJointConstraint*> KX_GameObject::GetConstraints()
303 {
304         return m_constraints;
305 }
306
307 void KX_GameObject::ClearConstraints()
308 {
309         m_constraints.clear();
310 }
311
312 KX_GameObject* KX_GameObject::GetParent()
313 {
314         KX_GameObject* result = NULL;
315         SG_Node* node = m_pSGNode;
316         
317         while (node && !result)
318         {
319                 node = node->GetSGParent();
320                 if (node)
321                         result = (KX_GameObject*)node->GetSGClientObject();
322         }
323
324         return result;
325         
326 }
327
328 void KX_GameObject::SetParent(KX_Scene *scene, KX_GameObject* obj, bool addToCompound, bool ghost)
329 {
330         // check on valid node in case a python controller holds a reference to a deleted object
331         if (obj && 
332                 GetSGNode() &&                  // object is not zombi
333                 obj->GetSGNode() &&             // object is not zombi
334                 GetSGNode()->GetSGParent() != obj->GetSGNode() &&       // not already parented to same object
335                 !GetSGNode()->IsAncessor(obj->GetSGNode()) &&           // no parenting loop
336                 this != obj)                                                                            // not the object itself
337         {
338                 // Make sure the objects have some scale
339                 MT_Vector3 scale1 = NodeGetWorldScaling();
340                 MT_Vector3 scale2 = obj->NodeGetWorldScaling();
341                 if (fabs(scale2[0]) < (MT_Scalar)FLT_EPSILON ||
342                         fabs(scale2[1]) < (MT_Scalar)FLT_EPSILON ||
343                         fabs(scale2[2]) < (MT_Scalar)FLT_EPSILON ||
344                         fabs(scale1[0]) < (MT_Scalar)FLT_EPSILON ||
345                         fabs(scale1[1]) < (MT_Scalar)FLT_EPSILON ||
346                         fabs(scale1[2]) < (MT_Scalar)FLT_EPSILON) { return; }
347
348                 // Remove us from our old parent and set our new parent
349                 RemoveParent(scene);
350                 obj->GetSGNode()->AddChild(GetSGNode());
351
352                 if (m_pPhysicsController)
353                 {
354                         m_pPhysicsController->SuspendDynamics(ghost);
355                 }
356                 // Set us to our new scale, position, and orientation
357                 scale2[0] = 1.0f/scale2[0];
358                 scale2[1] = 1.0f/scale2[1];
359                 scale2[2] = 1.0f/scale2[2];
360                 scale1 = scale1 * scale2;
361                 MT_Matrix3x3 invori = obj->NodeGetWorldOrientation().inverse();
362                 MT_Vector3 newpos = invori*(NodeGetWorldPosition()-obj->NodeGetWorldPosition())*scale2;
363
364                 NodeSetLocalScale(scale1);
365                 NodeSetLocalPosition(MT_Point3(newpos[0],newpos[1],newpos[2]));
366                 NodeSetLocalOrientation(invori*NodeGetWorldOrientation());
367                 NodeUpdateGS(0.f);
368                 // object will now be a child, it must be removed from the parent list
369                 CListValue* rootlist = scene->GetRootParentList();
370                 if (rootlist->RemoveValue(this))
371                         // the object was in parent list, decrement ref count as it's now removed
372                         Release();
373                 // if the new parent is a compound object, add this object shape to the compound shape.
374                 // step 0: verify this object has physical controller
375                 if (m_pPhysicsController && addToCompound)
376                 {
377                         // step 1: find the top parent (not necessarily obj)
378                         KX_GameObject* rootobj = (KX_GameObject*)obj->GetSGNode()->GetRootSGParent()->GetSGClientObject();
379                         // step 2: verify it has a physical controller and compound shape
380                         if (rootobj != NULL && 
381                                 rootobj->m_pPhysicsController != NULL &&
382                                 rootobj->m_pPhysicsController->IsCompound())
383                         {
384                                 rootobj->m_pPhysicsController->AddCompoundChild(m_pPhysicsController);
385                         }
386                 }
387                 // graphically, the object hasn't change place, no need to update m_pGraphicController
388         }
389 }
390
391 void KX_GameObject::RemoveParent(KX_Scene *scene)
392 {
393         // check on valid node in case a python controller holds a reference to a deleted object
394         if (GetSGNode() && GetSGNode()->GetSGParent())
395         {
396                 // get the root object to remove us from compound object if needed
397                 KX_GameObject* rootobj = (KX_GameObject*)GetSGNode()->GetRootSGParent()->GetSGClientObject();
398                 // Set us to the right spot 
399                 GetSGNode()->SetLocalScale(GetSGNode()->GetWorldScaling());
400                 GetSGNode()->SetLocalOrientation(GetSGNode()->GetWorldOrientation());
401                 GetSGNode()->SetLocalPosition(GetSGNode()->GetWorldPosition());
402
403                 // Remove us from our parent
404                 GetSGNode()->DisconnectFromParent();
405                 NodeUpdateGS(0.f);
406                 // the object is now a root object, add it to the parentlist
407                 CListValue* rootlist = scene->GetRootParentList();
408                 if (!rootlist->SearchValue(this))
409                         // object was not in root list, add it now and increment ref count
410                         rootlist->Add(AddRef());
411                 if (m_pPhysicsController)
412                 {
413                         // in case this controller was added as a child shape to the parent
414                         if (rootobj != NULL && 
415                                 rootobj->m_pPhysicsController != NULL &&
416                                 rootobj->m_pPhysicsController->IsCompound())
417                         {
418                                 rootobj->m_pPhysicsController->RemoveCompoundChild(m_pPhysicsController);
419                         }
420                         m_pPhysicsController->RestoreDynamics();
421                         if (m_pPhysicsController->IsDynamic() && (rootobj != NULL && rootobj->m_pPhysicsController))
422                         {
423                                 // dynamic object should remember the velocity they had while being parented
424                                 MT_Point3 childPoint = GetSGNode()->GetWorldPosition();
425                                 MT_Point3 rootPoint = rootobj->GetSGNode()->GetWorldPosition();
426                                 MT_Point3 relPoint;
427                                 relPoint = (childPoint-rootPoint);
428                                 MT_Vector3 linVel = rootobj->m_pPhysicsController->GetVelocity(relPoint);
429                                 MT_Vector3 angVel = rootobj->m_pPhysicsController->GetAngularVelocity();
430                                 m_pPhysicsController->SetLinearVelocity(linVel, false);
431                                 m_pPhysicsController->SetAngularVelocity(angVel, false);
432                         }
433                 }
434                 // graphically, the object hasn't change place, no need to update m_pGraphicController
435         }
436 }
437
438 BL_ActionManager* KX_GameObject::GetActionManager()
439 {
440         // We only want to create an action manager if we need it
441         if (!m_actionManager)
442         {
443                 GetScene()->AddAnimatedObject(this);
444                 m_actionManager = new BL_ActionManager(this);
445         }
446         return m_actionManager;
447 }
448
449 bool KX_GameObject::PlayAction(const char* name,
450                                                                 float start,
451                                                                 float end,
452                                                                 short layer,
453                                                                 short priority,
454                                                                 float blendin,
455                                                                 short play_mode,
456                                                                 float layer_weight,
457                                                                 short ipo_flags,
458                                                                 float playback_speed,
459                                                                 short blend_mode)
460 {
461         return GetActionManager()->PlayAction(name, start, end, layer, priority, blendin, play_mode, layer_weight, ipo_flags, playback_speed, blend_mode);
462 }
463
464 void KX_GameObject::StopAction(short layer)
465 {
466         GetActionManager()->StopAction(layer);
467 }
468
469 void KX_GameObject::RemoveTaggedActions()
470 {
471         GetActionManager()->RemoveTaggedActions();
472 }
473
474 bool KX_GameObject::IsActionDone(short layer)
475 {
476         return GetActionManager()->IsActionDone(layer);
477 }
478
479 void KX_GameObject::UpdateActionManager(float curtime)
480 {
481         GetActionManager()->Update(curtime);
482 }
483
484 float KX_GameObject::GetActionFrame(short layer)
485 {
486         return GetActionManager()->GetActionFrame(layer);
487 }
488
489 const char *KX_GameObject::GetActionName(short layer)
490 {
491         return GetActionManager()->GetActionName(layer);
492 }
493
494 void KX_GameObject::SetActionFrame(short layer, float frame)
495 {
496         GetActionManager()->SetActionFrame(layer, frame);
497 }
498
499 bAction *KX_GameObject::GetCurrentAction(short layer)
500 {
501         return GetActionManager()->GetCurrentAction(layer);
502 }
503
504 void KX_GameObject::SetPlayMode(short layer, short mode)
505 {
506         GetActionManager()->SetPlayMode(layer, mode);
507 }
508
509 void KX_GameObject::SetTimes(short layer, float start, float end)
510 {
511         GetActionManager()->SetTimes(layer, start, end);
512 }
513
514 void KX_GameObject::ProcessReplica()
515 {
516         SCA_IObject::ProcessReplica();
517
518         m_pGraphicController = NULL;
519         m_pPhysicsController = NULL;
520         m_pSGNode = NULL;
521
522         /* Dupli group and instance list are set later in replication.
523          * See KX_Scene::DupliGroupRecurse. */
524         m_pDupliGroupObject = NULL;
525         m_pInstanceObjects = NULL;
526         m_pClient_info = new KX_ClientObjectInfo(*m_pClient_info);
527         m_pClient_info->m_gameobject = this;
528         m_actionManager = NULL;
529         m_state = 0;
530
531         KX_Scene* scene = KX_GetActiveScene();
532         KX_ObstacleSimulation* obssimulation = scene->GetObstacleSimulation();
533         struct Object* blenderobject = GetBlenderObject();
534         if (obssimulation && (blenderobject->gameflag & OB_HASOBSTACLE))
535         {
536                 obssimulation->AddObstacleForObj(this);
537         }
538
539 #ifdef WITH_PYTHON
540         if (m_attr_dict)
541                 m_attr_dict= PyDict_Copy(m_attr_dict);
542 #endif
543                 
544 }
545
546 static void setGraphicController_recursive(SG_Node* node)
547 {
548         NodeList& children = node->GetSGChildren();
549
550         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
551         {
552                 SG_Node* childnode = (*childit);
553                 KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
554                 if (clientgameobj != NULL) // This is a GameObject
555                         clientgameobj->ActivateGraphicController(false);
556                 
557                 // if the childobj is NULL then this may be an inverse parent link
558                 // so a non recursive search should still look down this node.
559                 setGraphicController_recursive(childnode);
560         }
561 }
562
563
564 void KX_GameObject::ActivateGraphicController(bool recurse)
565 {
566         if (m_pGraphicController)
567         {
568                 m_pGraphicController->Activate(m_bVisible);
569         }
570         if (recurse)
571         {
572                 setGraphicController_recursive(GetSGNode());
573         }
574 }
575
576 void KX_GameObject::SetUserCollisionGroup(unsigned short group)
577 {
578         m_userCollisionGroup = group;
579         if (m_pPhysicsController)
580                 m_pPhysicsController->RefreshCollisions();
581 }
582 void KX_GameObject::SetUserCollisionMask(unsigned short mask)
583 {
584         m_userCollisionMask = mask;
585         if (m_pPhysicsController)
586                 m_pPhysicsController->RefreshCollisions();
587 }
588
589 unsigned short KX_GameObject::GetUserCollisionGroup()
590 {
591         return m_userCollisionGroup;
592 }
593 unsigned short KX_GameObject::GetUserCollisionMask()
594 {
595         return m_userCollisionMask;
596 }
597
598 bool KX_GameObject::CheckCollision(KX_GameObject* other)
599 {
600         return this->m_userCollisionGroup & other->m_userCollisionMask;
601 }
602
603 CValue* KX_GameObject::GetReplica()
604 {
605         KX_GameObject* replica = new KX_GameObject(*this);
606
607         // this will copy properties and so on...
608         replica->ProcessReplica();
609
610         return replica;
611 }
612
613 bool KX_GameObject::IsDynamicsSuspended() const
614 {
615         if (m_pPhysicsController)
616                 return m_pPhysicsController->IsSuspended();
617         return false;
618 }
619
620 float KX_GameObject::getLinearDamping() const
621 {
622         if (m_pPhysicsController)
623                 return m_pPhysicsController->GetLinearDamping();
624         return 0;
625 }
626
627 float KX_GameObject::getAngularDamping() const
628 {
629         if (m_pPhysicsController)
630                 return m_pPhysicsController->GetAngularDamping();
631         return 0;
632 }
633
634 void KX_GameObject::setLinearDamping(float damping)
635 {
636         if (m_pPhysicsController)
637                 m_pPhysicsController->SetLinearDamping(damping);
638 }
639
640
641 void KX_GameObject::setAngularDamping(float damping)
642 {
643         if (m_pPhysicsController)
644                 m_pPhysicsController->SetAngularDamping(damping);
645 }
646
647
648 void KX_GameObject::setDamping(float linear, float angular)
649 {
650         if (m_pPhysicsController)
651                 m_pPhysicsController->SetDamping(linear, angular);
652 }
653
654
655 void KX_GameObject::ApplyForce(const MT_Vector3& force,bool local)
656 {
657         if (m_pPhysicsController)
658                 m_pPhysicsController->ApplyForce(force,local);
659 }
660
661
662
663 void KX_GameObject::ApplyTorque(const MT_Vector3& torque,bool local)
664 {
665         if (m_pPhysicsController)
666                 m_pPhysicsController->ApplyTorque(torque,local);
667 }
668
669
670
671 void KX_GameObject::ApplyMovement(const MT_Vector3& dloc,bool local)
672 {
673         if (GetSGNode()) 
674         {
675                 if (m_pPhysicsController) // (IsDynamic())
676                 {
677                         m_pPhysicsController->RelativeTranslate(dloc,local);
678                 }
679                 GetSGNode()->RelativeTranslate(dloc,GetSGNode()->GetSGParent(),local);
680         }
681 }
682
683
684
685 void KX_GameObject::ApplyRotation(const MT_Vector3& drot,bool local)
686 {
687         MT_Matrix3x3 rotmat(drot);
688         
689         if (GetSGNode()) {
690                 GetSGNode()->RelativeRotate(rotmat,local);
691
692                 if (m_pPhysicsController) { // (IsDynamic())
693                         m_pPhysicsController->RelativeRotate(rotmat,local);
694                 }
695         }
696 }
697
698
699
700 /**
701  * GetOpenGL Matrix, returns an OpenGL 'compatible' matrix
702  */
703 float *KX_GameObject::GetOpenGLMatrix()
704 {
705         // todo: optimize and only update if necessary
706         float *fl = m_OpenGL_4x4Matrix.getPointer();
707         if (GetSGNode()) {
708                 MT_Transform trans;
709         
710                 trans.setOrigin(GetSGNode()->GetWorldPosition());
711                 trans.setBasis(GetSGNode()->GetWorldOrientation());
712         
713                 MT_Vector3 scaling = GetSGNode()->GetWorldScaling();
714                 m_bIsNegativeScaling = ((scaling[0] < 0.0f) ^ (scaling[1] < 0.0f) ^ (scaling[2] < 0.0f)) ? true : false;
715                 trans.scale(scaling[0], scaling[1], scaling[2]);
716                 trans.getValue(fl);
717                 GetSGNode()->ClearDirty();
718         }
719         return fl;
720 }
721
722 void KX_GameObject::UpdateBlenderObjectMatrix(Object* blendobj)
723 {
724         if (!blendobj)
725                 blendobj = m_pBlenderObject;
726         if (blendobj) {
727                 const MT_Matrix3x3& rot = NodeGetWorldOrientation();
728                 const MT_Vector3& scale = NodeGetWorldScaling();
729                 const MT_Vector3& pos = NodeGetWorldPosition();
730                 rot.getValue(blendobj->obmat[0]);
731                 pos.getValue(blendobj->obmat[3]);
732                 mul_v3_fl(blendobj->obmat[0], scale[0]);
733                 mul_v3_fl(blendobj->obmat[1], scale[1]);
734                 mul_v3_fl(blendobj->obmat[2], scale[2]);
735         }
736 }
737
738 void KX_GameObject::AddMeshUser()
739 {
740         for (size_t i=0;i<m_meshes.size();i++)
741         {
742                 m_meshes[i]->AddMeshUser(this, &m_meshSlots, GetDeformer());
743         }
744         // set the part of the mesh slot that never change
745         float *fl = GetOpenGLMatrixPtr()->getPointer();
746
747         SG_QList::iterator<RAS_MeshSlot> mit(m_meshSlots);
748 //      RAS_MeshSlot* ms;
749         for (mit.begin(); !mit.end(); ++mit)
750         {
751                 (*mit)->m_OpenGLMatrix = fl;
752         }
753         UpdateBuckets(false);
754 }
755
756 static void UpdateBuckets_recursive(SG_Node* node)
757 {
758         NodeList& children = node->GetSGChildren();
759
760         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
761         {
762                 SG_Node* childnode = (*childit);
763                 KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
764                 if (clientgameobj != NULL) // This is a GameObject
765                         clientgameobj->UpdateBuckets(0);
766                 
767                 // if the childobj is NULL then this may be an inverse parent link
768                 // so a non recursive search should still look down this node.
769                 UpdateBuckets_recursive(childnode);
770         }
771 }
772
773 void KX_GameObject::UpdateBuckets( bool recursive )
774 {
775         if (GetSGNode()) {
776                 RAS_MeshSlot *ms;
777
778                 if (GetSGNode()->IsDirty())
779                         GetOpenGLMatrix();
780
781                 SG_QList::iterator<RAS_MeshSlot> mit(m_meshSlots);
782                 for (mit.begin(); !mit.end(); ++mit)
783                 {
784                         ms = *mit;
785                         ms->m_bObjectColor = m_bUseObjectColor;
786                         ms->m_RGBAcolor = m_objectColor;
787                         ms->m_bVisible = m_bVisible;
788                         ms->m_bCulled = m_bCulled || !m_bVisible;
789                         if (!ms->m_bCulled) 
790                                 ms->m_bucket->ActivateMesh(ms);
791                         
792                         /* split if necessary */
793 #ifdef USE_SPLIT
794                         ms->Split();
795 #endif
796                 }
797         
798                 if (recursive) {
799                         UpdateBuckets_recursive(GetSGNode());
800                 }
801         }
802 }
803
804 void KX_GameObject::RemoveMeshes()
805 {
806         for (size_t i=0;i<m_meshes.size();i++)
807                 m_meshes[i]->RemoveFromBuckets(this);
808
809         //note: meshes can be shared, and are deleted by KX_BlenderSceneConverter
810
811         m_meshes.clear();
812 }
813
814 void KX_GameObject::AddLodMesh(RAS_MeshObject* mesh)
815 {
816         m_lodmeshes.push_back(mesh);
817 }
818
819
820 static float calcHysteresis(KX_Scene *kxscene, LodLevel *lod)
821 {
822         float hystvariance = 0.0f;
823
824         if (!kxscene->IsActivedLodHysteresis())
825                 return hystvariance;
826                         
827         short hysteresis = 0;
828         // if exists, LoD level hysteresis will override scene hysteresis
829         if (lod->next->flags & OB_LOD_USE_HYST)
830                 hysteresis = lod->next->obhysteresis;
831         else
832                 hysteresis = kxscene->GetLodHysteresisValue();
833
834         return hystvariance = MT_abs(lod->next->distance - lod->distance) * hysteresis / 100;
835 }
836
837 void KX_GameObject::UpdateLod(MT_Vector3 &cam_pos)
838 {
839         // Handle dupligroups
840         if (m_pInstanceObjects) {
841                 KX_GameObject *instob;
842                 int count = m_pInstanceObjects->GetCount();
843                 for (int i = 0; i < count; i++) {
844                         instob = (KX_GameObject*)m_pInstanceObjects->GetValue(i);
845                         instob->UpdateLod(cam_pos);
846                 }
847         }
848
849         if (m_lodmeshes.empty())
850                 return;
851
852         MT_Vector3 delta = NodeGetWorldPosition() - cam_pos;
853         float distance2 = delta.length2();
854
855         int level = 0;
856         float hystvariance = 0.0f;
857         Object *bob = GetBlenderObject();
858         LodLevel *lod = (LodLevel *)bob->lodlevels.first;
859         KX_Scene *kxscene = GetScene();
860
861         for (; lod; lod = lod->next, level++) {
862                 if (!lod->source || lod->source->type != OB_MESH)
863                         level--;
864
865                 if (!lod->next)
866                         break;
867
868                 if (level == m_previousLodLevel || level == (m_previousLodLevel + 1)) {
869                         hystvariance = calcHysteresis(kxscene, lod);
870                         float newdistance = lod->next->distance + hystvariance;
871                         if (newdistance * newdistance > distance2)
872                                 break;
873                 }
874                 else if (level == (m_previousLodLevel - 1)) {
875                         hystvariance = calcHysteresis(kxscene, lod);
876                         float newdistance = lod->next->distance - hystvariance;
877                         if (newdistance * newdistance > distance2)
878                                 break;
879                 }
880         }
881
882         RAS_MeshObject *mesh = m_lodmeshes[level];
883         m_currentLodLevel = level;
884         if (mesh != m_meshes[0]) {
885                 m_previousLodLevel = level;
886                 GetScene()->ReplaceMesh(this, mesh, true, false);
887         }
888 }
889
890 void KX_GameObject::UpdateTransform()
891 {
892         // HACK: saves function call for dynamic object, they are handled differently
893         if (m_pPhysicsController && !m_pPhysicsController->IsDynamic())
894                 m_pPhysicsController->SetTransform();
895         if (m_pGraphicController)
896                 // update the culling tree
897                 m_pGraphicController->SetGraphicTransform();
898
899 }
900
901 void KX_GameObject::UpdateTransformFunc(SG_IObject* node, void* gameobj, void* scene)
902 {
903         ((KX_GameObject*)gameobj)->UpdateTransform();
904 }
905
906 void KX_GameObject::SynchronizeTransform()
907 {
908         // only used for sensor object, do full synchronization as bullet doesn't do it
909         if (m_pPhysicsController)
910                 m_pPhysicsController->SetTransform();
911         if (m_pGraphicController)
912                 m_pGraphicController->SetGraphicTransform();
913 }
914
915 void KX_GameObject::SynchronizeTransformFunc(SG_IObject* node, void* gameobj, void* scene)
916 {
917         ((KX_GameObject*)gameobj)->SynchronizeTransform();
918 }
919
920
921 void KX_GameObject::SetDebugColor(unsigned int bgra)
922 {
923         for (size_t i=0;i<m_meshes.size();i++)
924                 m_meshes[i]->DebugColor(bgra);
925 }
926
927
928
929 void KX_GameObject::ResetDebugColor()
930 {
931         SetDebugColor(0xff000000);
932 }
933
934 void KX_GameObject::InitIPO(bool ipo_as_force,
935                             bool ipo_add,
936                             bool ipo_local)
937 {
938         SGControllerList::iterator it = GetSGNode()->GetSGControllerList().begin();
939
940         while (it != GetSGNode()->GetSGControllerList().end()) {
941                 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_RESET, true);
942                 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_AS_FORCE, ipo_as_force);
943                 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_ADD, ipo_add);
944                 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_LOCAL, ipo_local);
945                 it++;
946         }
947
948
949 void KX_GameObject::UpdateIPO(float curframetime,
950                                                           bool recurse) 
951 {
952         /* This function shouldn't call BL_Action::Update, not even indirectly, 
953          * as it will cause deadlock due to the lock in BL_Action::Update. */
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.0f-3.0f*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.0f, 0.0f, 0.0f)) * (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.0f-3.0f*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.0f, 1.0f, 0.0f)) * (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.0f-3.0f*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.0f, 0.0f, 1.0f)) * (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.0f;
1288 }
1289
1290 MT_Vector3 KX_GameObject::GetLocalInertia()
1291 {
1292         MT_Vector3 local_inertia(0.0f,0.0f,0.0f);
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.0f,0.0f,0.0f), 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.0f,0.0f,0.0f), 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.0f,0.0f,0.0f);
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.0f/scale[0];
1472                 scale[1] = 1.0f/scale[1];
1473                 scale[2] = 1.0f/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                 // Child objects must be static, so we block changing to dynamic
1620                 if (GetPhysicsController() && !GetParent())
1621                         GetPhysicsController()->RestoreDynamics();
1622
1623                 m_suspended = false;
1624         }
1625 }
1626
1627 void KX_GameObject::Suspend()
1628 {
1629         if ((!m_ignore_activity_culling) && (!m_suspended)) {
1630                 SCA_IObject::Suspend();
1631                 if (GetPhysicsController())
1632                         GetPhysicsController()->SuspendDynamics();
1633                 m_suspended = true;
1634         }
1635 }
1636
1637 static void walk_children(SG_Node* node, CListValue* list, bool recursive)
1638 {
1639         if (!node)
1640                 return;
1641         NodeList& children = node->GetSGChildren();
1642
1643         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
1644         {
1645                 SG_Node* childnode = (*childit);
1646                 CValue* childobj = (CValue*)childnode->GetSGClientObject();
1647                 if (childobj != NULL) // This is a GameObject
1648                 {
1649                         // add to the list
1650                         list->Add(childobj->AddRef());
1651                 }
1652                 
1653                 // if the childobj is NULL then this may be an inverse parent link
1654                 // so a non recursive search should still look down this node.
1655                 if (recursive || childobj==NULL) {
1656                         walk_children(childnode, list, recursive);
1657                 }
1658         }
1659 }
1660
1661 CListValue* KX_GameObject::GetChildren()
1662 {
1663         CListValue* list = new CListValue();
1664         walk_children(GetSGNode(), list, 0); /* GetSGNode() is always valid or it would have raised an exception before this */
1665         return list;
1666 }
1667
1668 CListValue* KX_GameObject::GetChildrenRecursive()
1669 {
1670         CListValue* list = new CListValue();
1671         walk_children(GetSGNode(), list, 1);
1672         return list;
1673 }
1674
1675 KX_Scene* KX_GameObject::GetScene()
1676 {
1677         SG_Node* node = this->GetSGNode();
1678         if (node == NULL) {
1679                 // this happens for object in non active layers, rely on static scene then
1680                 return KX_GetActiveScene();
1681         }
1682         return static_cast<KX_Scene*>(node->GetSGClientInfo());
1683 }
1684
1685 /* ---------------------------------------------------------------------
1686  * Some stuff taken from the header
1687  * --------------------------------------------------------------------- */
1688 void KX_GameObject::Relink(CTR_Map<CTR_HashedPtr, void*> *map_parameter)
1689 {
1690         // we will relink the sensors and actuators that use object references
1691         // if the object is part of the replicated hierarchy, use the new
1692         // object reference instead
1693         SCA_SensorList& sensorlist = GetSensors();
1694         SCA_SensorList::iterator sit;
1695         for (sit=sensorlist.begin(); sit != sensorlist.end(); sit++)
1696         {
1697                 (*sit)->Relink(map_parameter);
1698         }
1699         SCA_ActuatorList& actuatorlist = GetActuators();
1700         SCA_ActuatorList::iterator ait;
1701         for (ait=actuatorlist.begin(); ait != actuatorlist.end(); ait++)
1702         {
1703                 (*ait)->Relink(map_parameter);
1704         }
1705 }
1706
1707 #ifdef USE_MATHUTILS
1708
1709 /* These require an SGNode */
1710 #define MATHUTILS_VEC_CB_POS_LOCAL 1
1711 #define MATHUTILS_VEC_CB_POS_GLOBAL 2
1712 #define MATHUTILS_VEC_CB_SCALE_LOCAL 3
1713 #define MATHUTILS_VEC_CB_SCALE_GLOBAL 4
1714 #define MATHUTILS_VEC_CB_INERTIA_LOCAL 5
1715 #define MATHUTILS_VEC_CB_OBJECT_COLOR 6
1716 #define MATHUTILS_VEC_CB_LINVEL_LOCAL 7
1717 #define MATHUTILS_VEC_CB_LINVEL_GLOBAL 8
1718 #define MATHUTILS_VEC_CB_ANGVEL_LOCAL 9
1719 #define MATHUTILS_VEC_CB_ANGVEL_GLOBAL 10
1720
1721 static unsigned char mathutils_kxgameob_vector_cb_index= -1; /* index for our callbacks */
1722
1723 static int mathutils_kxgameob_generic_check(BaseMathObject *bmo)
1724 {
1725         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1726         if (self == NULL)
1727                 return -1;
1728         
1729         return 0;
1730 }
1731
1732 static int mathutils_kxgameob_vector_get(BaseMathObject *bmo, int subtype)
1733 {
1734         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1735         if (self == NULL)
1736                 return -1;
1737
1738 #define PHYS_ERR(attr) PyErr_SetString(PyExc_AttributeError, "KX_GameObject." attr ", is missing a physics controller")
1739
1740         switch (subtype) {
1741                 case MATHUTILS_VEC_CB_POS_LOCAL:
1742                         self->NodeGetLocalPosition().getValue(bmo->data);
1743                         break;
1744                 case MATHUTILS_VEC_CB_POS_GLOBAL:
1745                         self->NodeGetWorldPosition().getValue(bmo->data);
1746                         break;
1747                 case MATHUTILS_VEC_CB_SCALE_LOCAL:
1748                         self->NodeGetLocalScaling().getValue(bmo->data);
1749                         break;
1750                 case MATHUTILS_VEC_CB_SCALE_GLOBAL:
1751                         self->NodeGetWorldScaling().getValue(bmo->data);
1752                         break;
1753                 case MATHUTILS_VEC_CB_INERTIA_LOCAL:
1754                         if (!self->GetPhysicsController()) return PHYS_ERR("localInertia"), -1;
1755                         self->GetPhysicsController()->GetLocalInertia().getValue(bmo->data);
1756                         break;
1757                 case MATHUTILS_VEC_CB_OBJECT_COLOR:
1758                         self->GetObjectColor().getValue(bmo->data);
1759                         break;
1760                 case MATHUTILS_VEC_CB_LINVEL_LOCAL:
1761                         if (!self->GetPhysicsController()) return PHYS_ERR("localLinearVelocity"), -1;
1762                         self->GetLinearVelocity(true).getValue(bmo->data);
1763                         break;
1764                 case MATHUTILS_VEC_CB_LINVEL_GLOBAL:
1765                         if (!self->GetPhysicsController()) return PHYS_ERR("worldLinearVelocity"), -1;
1766                         self->GetLinearVelocity(false).getValue(bmo->data);
1767                         break;
1768                 case MATHUTILS_VEC_CB_ANGVEL_LOCAL:
1769                         if (!self->GetPhysicsController()) return PHYS_ERR("localLinearVelocity"), -1;
1770                         self->GetAngularVelocity(true).getValue(bmo->data);
1771                         break;
1772                 case MATHUTILS_VEC_CB_ANGVEL_GLOBAL:
1773                         if (!self->GetPhysicsController()) return PHYS_ERR("worldLinearVelocity"), -1;
1774                         self->GetAngularVelocity(false).getValue(bmo->data);
1775                         break;
1776                         
1777         }
1778         
1779 #undef PHYS_ERR
1780         
1781         return 0;
1782 }
1783
1784 static int mathutils_kxgameob_vector_set(BaseMathObject *bmo, int subtype)
1785 {
1786         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1787         if (self == NULL)
1788                 return -1;
1789         
1790         switch (subtype) {
1791                 case MATHUTILS_VEC_CB_POS_LOCAL:
1792                         self->NodeSetLocalPosition(MT_Point3(bmo->data));
1793                         self->NodeUpdateGS(0.f);
1794                         break;
1795                 case MATHUTILS_VEC_CB_POS_GLOBAL:
1796                         self->NodeSetWorldPosition(MT_Point3(bmo->data));
1797                         self->NodeUpdateGS(0.f);
1798                         break;
1799                 case MATHUTILS_VEC_CB_SCALE_LOCAL:
1800                         self->NodeSetLocalScale(MT_Point3(bmo->data));
1801                         self->NodeUpdateGS(0.f);
1802                         break;
1803                 case MATHUTILS_VEC_CB_SCALE_GLOBAL:
1804                         PyErr_SetString(PyExc_AttributeError, "KX_GameObject.worldScale is read-only");
1805                         return -1;
1806                 case MATHUTILS_VEC_CB_INERTIA_LOCAL:
1807                         /* read only */
1808                         break;
1809                 case MATHUTILS_VEC_CB_OBJECT_COLOR:
1810                         self->SetObjectColor(MT_Vector4(bmo->data));
1811                         break;
1812                 case MATHUTILS_VEC_CB_LINVEL_LOCAL:
1813                         self->setLinearVelocity(MT_Point3(bmo->data),true);
1814                         break;
1815                 case MATHUTILS_VEC_CB_LINVEL_GLOBAL:
1816                         self->setLinearVelocity(MT_Point3(bmo->data),false);
1817                         break;
1818                 case MATHUTILS_VEC_CB_ANGVEL_LOCAL:
1819                         self->setAngularVelocity(MT_Point3(bmo->data),true);
1820                         break;
1821                 case MATHUTILS_VEC_CB_ANGVEL_GLOBAL:
1822                         self->setAngularVelocity(MT_Point3(bmo->data),false);
1823                         break;
1824         }
1825         
1826         return 0;
1827 }
1828
1829 static int mathutils_kxgameob_vector_get_index(BaseMathObject *bmo, int subtype, int index)
1830 {
1831         /* lazy, avoid repeteing the case statement */
1832         if (mathutils_kxgameob_vector_get(bmo, subtype) == -1)
1833                 return -1;
1834         return 0;
1835 }
1836
1837 static int mathutils_kxgameob_vector_set_index(BaseMathObject *bmo, int subtype, int index)
1838 {
1839         float f= bmo->data[index];
1840         
1841         /* lazy, avoid repeteing the case statement */
1842         if (mathutils_kxgameob_vector_get(bmo, subtype) == -1)
1843                 return -1;
1844         
1845         bmo->data[index] = f;
1846         return mathutils_kxgameob_vector_set(bmo, subtype);
1847 }
1848
1849 static Mathutils_Callback mathutils_kxgameob_vector_cb = {
1850         mathutils_kxgameob_generic_check,
1851         mathutils_kxgameob_vector_get,
1852         mathutils_kxgameob_vector_set,
1853         mathutils_kxgameob_vector_get_index,
1854         mathutils_kxgameob_vector_set_index
1855 };
1856
1857 /* Matrix */
1858 #define MATHUTILS_MAT_CB_ORI_LOCAL 1
1859 #define MATHUTILS_MAT_CB_ORI_GLOBAL 2
1860
1861 static unsigned char mathutils_kxgameob_matrix_cb_index= -1; /* index for our callbacks */
1862
1863 static int mathutils_kxgameob_matrix_get(BaseMathObject *bmo, int subtype)
1864 {
1865         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1866         if (self == NULL)
1867                 return -1;
1868
1869         switch (subtype) {
1870                 case MATHUTILS_MAT_CB_ORI_LOCAL:
1871                         self->NodeGetLocalOrientation().getValue3x3(bmo->data);
1872                         break;
1873                 case MATHUTILS_MAT_CB_ORI_GLOBAL:
1874                         self->NodeGetWorldOrientation().getValue3x3(bmo->data);
1875                         break;
1876         }
1877         
1878         return 0;
1879 }
1880
1881
1882 static int mathutils_kxgameob_matrix_set(BaseMathObject *bmo, int subtype)
1883 {
1884         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1885         if (self == NULL)
1886                 return -1;
1887         
1888         MT_Matrix3x3 mat3x3;
1889         switch (subtype) {
1890                 case MATHUTILS_MAT_CB_ORI_LOCAL:
1891                         mat3x3.setValue3x3(bmo->data);
1892                         self->NodeSetLocalOrientation(mat3x3);
1893                         self->NodeUpdateGS(0.f);
1894                         break;
1895                 case MATHUTILS_MAT_CB_ORI_GLOBAL:
1896                         mat3x3.setValue3x3(bmo->data);
1897                         self->NodeSetLocalOrientation(mat3x3);
1898                         self->NodeUpdateGS(0.f);
1899                         break;
1900         }
1901         
1902         return 0;
1903 }
1904
1905 static Mathutils_Callback mathutils_kxgameob_matrix_cb = {
1906         mathutils_kxgameob_generic_check,
1907         mathutils_kxgameob_matrix_get,
1908         mathutils_kxgameob_matrix_set,
1909         NULL,
1910         NULL
1911 };
1912
1913
1914 void KX_GameObject_Mathutils_Callback_Init(void)
1915 {
1916         // register mathutils callbacks, ok to run more than once.
1917         mathutils_kxgameob_vector_cb_index= Mathutils_RegisterCallback(&mathutils_kxgameob_vector_cb);
1918         mathutils_kxgameob_matrix_cb_index= Mathutils_RegisterCallback(&mathutils_kxgameob_matrix_cb);
1919 }
1920
1921 #endif // USE_MATHUTILS
1922
1923 #ifdef WITH_PYTHON
1924 /* ------- python stuff ---------------------------------------------------*/
1925 PyMethodDef KX_GameObject::Methods[] = {
1926         {"applyForce", (PyCFunction)    KX_GameObject::sPyApplyForce, METH_VARARGS},
1927         {"applyTorque", (PyCFunction)   KX_GameObject::sPyApplyTorque, METH_VARARGS},
1928         {"applyRotation", (PyCFunction) KX_GameObject::sPyApplyRotation, METH_VARARGS},
1929         {"applyMovement", (PyCFunction) KX_GameObject::sPyApplyMovement, METH_VARARGS},
1930         {"getLinearVelocity", (PyCFunction) KX_GameObject::sPyGetLinearVelocity, METH_VARARGS},
1931         {"setLinearVelocity", (PyCFunction) KX_GameObject::sPySetLinearVelocity, METH_VARARGS},
1932         {"getAngularVelocity", (PyCFunction) KX_GameObject::sPyGetAngularVelocity, METH_VARARGS},
1933         {"setAngularVelocity", (PyCFunction) KX_GameObject::sPySetAngularVelocity, METH_VARARGS},
1934         {"getVelocity", (PyCFunction) KX_GameObject::sPyGetVelocity, METH_VARARGS},
1935         {"setDamping", (PyCFunction) KX_GameObject::sPySetDamping, METH_VARARGS},
1936         {"getReactionForce", (PyCFunction) KX_GameObject::sPyGetReactionForce, METH_NOARGS},
1937         {"alignAxisToVect",(PyCFunction) KX_GameObject::sPyAlignAxisToVect, METH_VARARGS},
1938         {"getAxisVect",(PyCFunction) KX_GameObject::sPyGetAxisVect, METH_O},
1939         {"suspendDynamics", (PyCFunction)KX_GameObject::sPySuspendDynamics, METH_VARARGS},
1940         {"restoreDynamics", (PyCFunction)KX_GameObject::sPyRestoreDynamics,METH_NOARGS},
1941         {"enableRigidBody", (PyCFunction)KX_GameObject::sPyEnableRigidBody,METH_NOARGS},
1942         {"disableRigidBody", (PyCFunction)KX_GameObject::sPyDisableRigidBody,METH_NOARGS},
1943         {"applyImpulse", (PyCFunction) KX_GameObject::sPyApplyImpulse, METH_VARARGS},
1944         {"setCollisionMargin", (PyCFunction) KX_GameObject::sPySetCollisionMargin, METH_O},
1945         {"setParent", (PyCFunction)KX_GameObject::sPySetParent,METH_VARARGS},
1946         {"setVisible",(PyCFunction) KX_GameObject::sPySetVisible, METH_VARARGS},
1947         {"setOcclusion",(PyCFunction) KX_GameObject::sPySetOcclusion, METH_VARARGS},
1948         {"removeParent", (PyCFunction)KX_GameObject::sPyRemoveParent,METH_NOARGS},
1949
1950
1951         {"getPhysicsId", (PyCFunction)KX_GameObject::sPyGetPhysicsId,METH_NOARGS},
1952         {"getPropertyNames", (PyCFunction)KX_GameObject::sPyGetPropertyNames,METH_NOARGS},
1953         {"replaceMesh",(PyCFunction) KX_GameObject::sPyReplaceMesh, METH_VARARGS},
1954         {"endObject",(PyCFunction) KX_GameObject::sPyEndObject, METH_NOARGS},
1955         {"reinstancePhysicsMesh", (PyCFunction)KX_GameObject::sPyReinstancePhysicsMesh,METH_VARARGS},
1956         
1957         KX_PYMETHODTABLE(KX_GameObject, rayCastTo),
1958         KX_PYMETHODTABLE(KX_GameObject, rayCast),
1959         KX_PYMETHODTABLE_O(KX_GameObject, getDistanceTo),
1960         KX_PYMETHODTABLE_O(KX_GameObject, getVectTo),
1961         KX_PYMETHODTABLE(KX_GameObject, sendMessage),
1962         KX_PYMETHODTABLE(KX_GameObject, addDebugProperty),
1963
1964         KX_PYMETHODTABLE_KEYWORDS(KX_GameObject, playAction),
1965         KX_PYMETHODTABLE(KX_GameObject, stopAction),
1966         KX_PYMETHODTABLE(KX_GameObject, getActionFrame),
1967         KX_PYMETHODTABLE(KX_GameObject, getActionName),
1968         KX_PYMETHODTABLE(KX_GameObject, setActionFrame),
1969         KX_PYMETHODTABLE(KX_GameObject, isPlayingAction),
1970         
1971         // dict style access for props
1972         {"get",(PyCFunction) KX_GameObject::sPyget, METH_VARARGS},
1973         
1974         {NULL,NULL} //Sentinel
1975 };
1976
1977 PyAttributeDef KX_GameObject::Attributes[] = {
1978         KX_PYATTRIBUTE_INT_RO("currentLodLevel", KX_GameObject, m_currentLodLevel),
1979         KX_PYATTRIBUTE_RO_FUNCTION("name",              KX_GameObject, pyattr_get_name),
1980         KX_PYATTRIBUTE_RO_FUNCTION("parent",    KX_GameObject, pyattr_get_parent),
1981         KX_PYATTRIBUTE_RO_FUNCTION("groupMembers",      KX_GameObject, pyattr_get_group_members),
1982         KX_PYATTRIBUTE_RO_FUNCTION("groupObject",       KX_GameObject, pyattr_get_group_object),
1983         KX_PYATTRIBUTE_RO_FUNCTION("scene",             KX_GameObject, pyattr_get_scene),
1984         KX_PYATTRIBUTE_RO_FUNCTION("life",              KX_GameObject, pyattr_get_life),
1985         KX_PYATTRIBUTE_RW_FUNCTION("mass",              KX_GameObject, pyattr_get_mass,         pyattr_set_mass),
1986         KX_PYATTRIBUTE_RO_FUNCTION("isSuspendDynamics",         KX_GameObject, pyattr_get_is_suspend_dynamics),
1987         KX_PYATTRIBUTE_RW_FUNCTION("linVelocityMin",            KX_GameObject, pyattr_get_lin_vel_min, pyattr_set_lin_vel_min),
1988         KX_PYATTRIBUTE_RW_FUNCTION("linVelocityMax",            KX_GameObject, pyattr_get_lin_vel_max, pyattr_set_lin_vel_max),
1989         KX_PYATTRIBUTE_RW_FUNCTION("angularVelocityMin", KX_GameObject, pyattr_get_ang_vel_min, pyattr_set_ang_vel_min),
1990         KX_PYATTRIBUTE_RW_FUNCTION("angularVelocityMax", KX_GameObject, pyattr_get_ang_vel_max, pyattr_set_ang_vel_max),
1991         KX_PYATTRIBUTE_RW_FUNCTION("visible",   KX_GameObject, pyattr_get_visible,      pyattr_set_visible),
1992         KX_PYATTRIBUTE_RW_FUNCTION("record_animation",  KX_GameObject, pyattr_get_record_animation,     pyattr_set_record_animation),
1993         KX_PYATTRIBUTE_BOOL_RW    ("occlusion", KX_GameObject, m_bOccluder),
1994         KX_PYATTRIBUTE_RW_FUNCTION("position",  KX_GameObject, pyattr_get_worldPosition,        pyattr_set_localPosition),
1995         KX_PYATTRIBUTE_RO_FUNCTION("localInertia",      KX_GameObject, pyattr_get_localInertia),
1996         KX_PYATTRIBUTE_RW_FUNCTION("orientation",KX_GameObject,pyattr_get_worldOrientation,pyattr_set_localOrientation),
1997         KX_PYATTRIBUTE_RW_FUNCTION("scaling",   KX_GameObject, pyattr_get_worldScaling, pyattr_set_localScaling),
1998         KX_PYATTRIBUTE_RW_FUNCTION("timeOffset",KX_GameObject, pyattr_get_timeOffset,pyattr_set_timeOffset),
1999         KX_PYATTRIBUTE_RW_FUNCTION("collisionCallbacks",                KX_GameObject, pyattr_get_collisionCallbacks,   pyattr_set_collisionCallbacks),
2000         KX_PYATTRIBUTE_RW_FUNCTION("collisionGroup",                    KX_GameObject, pyattr_get_collisionGroup, pyattr_set_collisionGroup),
2001         KX_PYATTRIBUTE_RW_FUNCTION("collisionMask",                             KX_GameObject, pyattr_get_collisionMask, pyattr_set_collisionMask),
2002         KX_PYATTRIBUTE_RW_FUNCTION("state",             KX_GameObject, pyattr_get_state,        pyattr_set_state),
2003         KX_PYATTRIBUTE_RO_FUNCTION("meshes",    KX_GameObject, pyattr_get_meshes),
2004         KX_PYATTRIBUTE_RW_FUNCTION("localOrientation",KX_GameObject,pyattr_get_localOrientation,pyattr_set_localOrientation),
2005         KX_PYATTRIBUTE_RW_FUNCTION("worldOrientation",KX_GameObject,pyattr_get_worldOrientation,pyattr_set_worldOrientation),
2006         KX_PYATTRIBUTE_RW_FUNCTION("localPosition",     KX_GameObject, pyattr_get_localPosition,        pyattr_set_localPosition),
2007         KX_PYATTRIBUTE_RW_FUNCTION("worldPosition",     KX_GameObject, pyattr_get_worldPosition,    pyattr_set_worldPosition),
2008         KX_PYATTRIBUTE_RW_FUNCTION("localScale",        KX_GameObject, pyattr_get_localScaling, pyattr_set_localScaling),
2009         KX_PYATTRIBUTE_RW_FUNCTION("worldScale",        KX_GameObject, pyattr_get_worldScaling, pyattr_set_worldScaling),
2010         KX_PYATTRIBUTE_RW_FUNCTION("localTransform",            KX_GameObject, pyattr_get_localTransform, pyattr_set_localTransform),
2011         KX_PYATTRIBUTE_RW_FUNCTION("worldTransform",            KX_GameObject, pyattr_get_worldTransform, pyattr_set_worldTransform),
2012         KX_PYATTRIBUTE_RW_FUNCTION("linearVelocity", KX_GameObject, pyattr_get_localLinearVelocity, pyattr_set_worldLinearVelocity),
2013         KX_PYATTRIBUTE_RW_FUNCTION("localLinearVelocity", KX_GameObject, pyattr_get_localLinearVelocity, pyattr_set_localLinearVelocity),
2014         KX_PYATTRIBUTE_RW_FUNCTION("worldLinearVelocity", KX_GameObject, pyattr_get_worldLinearVelocity, pyattr_set_worldLinearVelocity),
2015         KX_PYATTRIBUTE_RW_FUNCTION("angularVelocity", KX_GameObject, pyattr_get_localAngularVelocity, pyattr_set_worldAngularVelocity),
2016         KX_PYATTRIBUTE_RW_FUNCTION("localAngularVelocity", KX_GameObject, pyattr_get_localAngularVelocity, pyattr_set_localAngularVelocity),
2017         KX_PYATTRIBUTE_RW_FUNCTION("worldAngularVelocity", KX_GameObject, pyattr_get_worldAngularVelocity, pyattr_set_worldAngularVelocity),
2018         KX_PYATTRIBUTE_RW_FUNCTION("linearDamping", KX_GameObject, pyattr_get_linearDamping, pyattr_set_linearDamping),
2019         KX_PYATTRIBUTE_RW_FUNCTION("angularDamping", KX_GameObject, pyattr_get_angularDamping, pyattr_set_angularDamping),
2020         KX_PYATTRIBUTE_RO_FUNCTION("children",  KX_GameObject, pyattr_get_children),
2021         KX_PYATTRIBUTE_RO_FUNCTION("childrenRecursive", KX_GameObject, pyattr_get_children_recursive),
2022         KX_PYATTRIBUTE_RO_FUNCTION("attrDict",  KX_GameObject, pyattr_get_attrDict),
2023         KX_PYATTRIBUTE_RW_FUNCTION("color", KX_GameObject, pyattr_get_obcolor, pyattr_set_obcolor),
2024         KX_PYATTRIBUTE_RW_FUNCTION("debug",     KX_GameObject, pyattr_get_debug, pyattr_set_debug),
2025         KX_PYATTRIBUTE_RW_FUNCTION("debugRecursive",    KX_GameObject, pyattr_get_debugRecursive, pyattr_set_debugRecursive),
2026         
2027         /* experimental, don't rely on these yet */
2028         KX_PYATTRIBUTE_RO_FUNCTION("sensors",           KX_GameObject, pyattr_get_sensors),
2029         KX_PYATTRIBUTE_RO_FUNCTION("controllers",       KX_GameObject, pyattr_get_controllers),
2030         KX_PYATTRIBUTE_RO_FUNCTION("actuators",         KX_GameObject, pyattr_get_actuators),
2031         {NULL} //Sentinel
2032 };
2033
2034 PyObject *KX_GameObject::PyReplaceMesh(PyObject *args)
2035 {
2036         KX_Scene *scene = KX_GetActiveScene();
2037         
2038         PyObject *value;
2039         int use_gfx= 1, use_phys= 0;
2040         RAS_MeshObject *new_mesh;
2041         
2042         if (!PyArg_ParseTuple(args,"O|ii:replaceMesh", &value, &use_gfx, &use_phys))
2043                 return NULL;
2044         
2045         if (!ConvertPythonToMesh(value, &new_mesh, false, "gameOb.replaceMesh(value): KX_GameObject"))
2046                 return NULL;
2047         
2048         scene->ReplaceMesh(this, new_mesh, (bool)use_gfx, (bool)use_phys);
2049         Py_RETURN_NONE;
2050 }
2051
2052 PyObject *KX_GameObject::PyEndObject()
2053 {
2054         KX_Scene* scene = GetScene();
2055         
2056         scene->DelayedRemoveObject(this);
2057         
2058         Py_RETURN_NONE;
2059
2060 }
2061
2062 PyObject *KX_GameObject::PyReinstancePhysicsMesh(PyObject *args)
2063 {
2064         KX_GameObject *gameobj= NULL;
2065         RAS_MeshObject *mesh= NULL;
2066         
2067         PyObject *gameobj_py= NULL;
2068         PyObject *mesh_py= NULL;
2069
2070         if (    !PyArg_ParseTuple(args,"|OO:reinstancePhysicsMesh",&gameobj_py, &mesh_py) ||
2071                         (gameobj_py && !ConvertPythonToGameObject(gameobj_py, &gameobj, true, "gameOb.reinstancePhysicsMesh(obj, mesh): KX_GameObject")) || 
2072                         (mesh_py && !ConvertPythonToMesh(mesh_py, &mesh, true, "gameOb.reinstancePhysicsMesh(obj, mesh): KX_GameObject"))
2073                 ) {
2074                 return NULL;
2075         }
2076
2077         /* gameobj and mesh can be NULL */
2078         if (GetPhysicsController() && GetPhysicsController()->ReinstancePhysicsShape(gameobj, mesh))
2079                 Py_RETURN_TRUE;
2080
2081         Py_RETURN_FALSE;
2082 }
2083
2084 static PyObject *Map_GetItem(PyObject *self_v, PyObject *item)
2085 {
2086         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
2087         const char *attr_str= _PyUnicode_AsString(item);
2088         CValue* resultattr;
2089         PyObject *pyconvert;
2090         
2091         if (self == NULL) {
2092                 PyErr_SetString(PyExc_SystemError, "val = gameOb[key]: KX_GameObject, " BGE_PROXY_ERROR_MSG);
2093                 return NULL;
2094         }
2095         
2096         /* first see if the attributes a string and try get the cvalue attribute */
2097         if (attr_str && (resultattr=self->GetProperty(attr_str))) {
2098                 pyconvert = resultattr->ConvertValueToPython();
2099                 return pyconvert ? pyconvert:resultattr->GetProxy();
2100         }
2101         /* no CValue attribute, try get the python only m_attr_dict attribute */
2102         else if (self->m_attr_dict && (pyconvert=PyDict_GetItem(self->m_attr_dict, item))) {
2103                 
2104                 if (attr_str)
2105                         PyErr_Clear();
2106                 Py_INCREF(pyconvert);
2107                 return pyconvert;
2108         }
2109         else {
2110                 if (attr_str)   PyErr_Format(PyExc_KeyError, "value = gameOb[key]: KX_GameObject, key \"%s\" does not exist", attr_str);
2111                 else                    PyErr_SetString(PyExc_KeyError, "value = gameOb[key]: KX_GameObject, key does not exist");
2112                 return NULL;
2113         }
2114                 
2115 }
2116
2117
2118 static int Map_SetItem(PyObject *self_v, PyObject *key, PyObject *val)
2119 {
2120         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
2121         const char *attr_str= _PyUnicode_AsString(key);
2122         if (attr_str==NULL)
2123                 PyErr_Clear();
2124         
2125         if (self == NULL) {
2126                 PyErr_SetString(PyExc_SystemError, "gameOb[key] = value: KX_GameObject, " BGE_PROXY_ERROR_MSG);
2127                 return -1;
2128         }
2129         
2130         if (val==NULL) { /* del ob["key"] */
2131                 int del= 0;
2132                 
2133                 /* try remove both just in case */
2134                 if (attr_str)
2135                         del |= (self->RemoveProperty(attr_str)==true) ? 1:0;
2136                 
2137                 if (self->m_attr_dict)
2138                         del |= (PyDict_DelItem(self->m_attr_dict, key)==0) ? 1:0;
2139                 
2140                 if (del==0) {
2141                         if (attr_str)   PyErr_Format(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key \"%s\" could not be set", attr_str);
2142                         else                    PyErr_SetString(PyExc_KeyError, "del gameOb[key]: KX_GameObject, key could not be deleted");
2143                         return -1;
2144                 }
2145                 else if (self->m_attr_dict) {
2146                         PyErr_Clear(); /* PyDict_DelItem sets an error when it fails */
2147                 }
2148         }
2149         else { /* ob["key"] = value */
2150                 bool set = false;
2151                 
2152                 /* as CValue */
2153                 if (attr_str && PyObject_TypeCheck(val, &PyObjectPlus::Type)==0) /* don't allow GameObjects for eg to be assigned to CValue props */
2154                 {
2155                         CValue *vallie = self->ConvertPythonToValue(val, false, "gameOb[key] = value: ");
2156                         
2157                         if (vallie) {
2158                                 CValue* oldprop = self->GetProperty(attr_str);
2159                                 
2160                                 if (oldprop)
2161                                         oldprop->SetValue(vallie);
2162                                 else
2163                                         self->SetProperty(attr_str, vallie);
2164                                 
2165                                 vallie->Release();
2166                                 set = true;
2167                                 
2168                                 /* try remove dict value to avoid double ups */
2169                                 if (self->m_attr_dict) {
2170                                         if (PyDict_DelItem(self->m_attr_dict, key) != 0)
2171                                                 PyErr_Clear();
2172                                 }
2173                         }
2174                         else if (PyErr_Occurred()) {
2175                                 return -1;
2176                         }
2177                 }
2178                 
2179                 if (set == false) {
2180                         if (self->m_attr_dict==NULL) /* lazy init */
2181                                 self->m_attr_dict= PyDict_New();
2182                         
2183                         
2184                         if (PyDict_SetItem(self->m_attr_dict, key, val)==0)
2185                         {
2186                                 if (attr_str)
2187                                         self->RemoveProperty(attr_str); /* overwrite the CValue if it exists */
2188                                 set = true;
2189                         }
2190                         else {
2191                                 if (attr_str)   PyErr_Format(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key \"%s\" not be added to internal dictionary", attr_str);
2192                                 else                    PyErr_SetString(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key not be added to internal dictionary");
2193                         }
2194                 }
2195                 
2196                 if (set == false) {
2197                         return -1; /* pythons error value */
2198                 }
2199                 
2200         }
2201         
2202         return 0; /* success */
2203 }
2204
2205 static int Seq_Contains(PyObject *self_v, PyObject *value)
2206 {
2207         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
2208         
2209         if (self == NULL) {
2210                 PyErr_SetString(PyExc_SystemError, "val in gameOb: KX_GameObject, " BGE_PROXY_ERROR_MSG);
2211                 return -1;
2212         }
2213         
2214         if (PyUnicode_Check(value) && self->GetProperty(_PyUnicode_AsString(value)))
2215                 return 1;
2216         
2217         if (self->m_attr_dict && PyDict_GetItem(self->m_attr_dict, value))
2218                 return 1;
2219         
2220         return 0;
2221 }
2222
2223
2224 PyMappingMethods KX_GameObject::Mapping = {
2225         (lenfunc)NULL                                   ,                       /*inquiry mp_length */
2226         (binaryfunc)Map_GetItem,                /*binaryfunc mp_subscript */
2227         (objobjargproc)Map_SetItem,     /*objobjargproc mp_ass_subscript */
2228 };
2229
2230 PySequenceMethods KX_GameObject::Sequence = {
2231         NULL,           /* Cant set the len otherwise it can evaluate as false */
2232         NULL,           /* sq_concat */
2233         NULL,           /* sq_repeat */
2234         NULL,           /* sq_item */
2235         NULL,           /* sq_slice */
2236         NULL,           /* sq_ass_item */
2237         NULL,           /* sq_ass_slice */
2238         (objobjproc)Seq_Contains,       /* sq_contains */
2239         (binaryfunc) NULL, /* sq_inplace_concat */
2240         (ssizeargfunc) NULL, /* sq_inplace_repeat */
2241 };
2242
2243 PyTypeObject KX_GameObject::Type = {
2244         PyVarObject_HEAD_INIT(NULL, 0)
2245         "KX_GameObject",
2246         sizeof(PyObjectPlus_Proxy),
2247         0,
2248         py_base_dealloc,
2249         0,
2250         0,
2251         0,
2252         0,
2253         py_base_repr,
2254         0,
2255         &Sequence,
2256         &Mapping,
2257         0,0,0,
2258         NULL,
2259         NULL,
2260         0,
2261         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
2262         0,0,0,0,0,0,0,
2263         Methods,
2264         0,
2265         0,
2266         &SCA_IObject::Type,
2267         0,0,0,0,0,0,
2268         py_base_new
2269 };
2270
2271 PyObject *KX_GameObject::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2272 {
2273         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2274         return PyUnicode_From_STR_String(self->GetName());
2275 }
2276
2277 PyObject *KX_GameObject::pyattr_get_parent(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2278 {
2279         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2280         KX_GameObject* parent = self->GetParent();
2281         if (parent) {
2282                 return parent->GetProxy();
2283         }
2284         Py_RETURN_NONE;
2285 }
2286
2287 PyObject *KX_GameObject::pyattr_get_group_members(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2288 {
2289         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2290         CListValue* instances = self->GetInstanceObjects();
2291         if (instances) {
2292                 return instances->GetProxy();
2293         }
2294         Py_RETURN_NONE;
2295 }
2296
2297 PyObject* KX_GameObject::pyattr_get_collisionCallbacks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2298 {
2299         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2300
2301         // Only objects with a physics controller should have collision callbacks
2302         if (!self->GetPhysicsController()) {
2303                 PyErr_SetString(PyExc_AttributeError, "KX_GameObject.collisionCallbacks: attribute only available for objects with collisions enabled");
2304                 return NULL;
2305         }
2306
2307         // Return the existing callbacks
2308         if (self->m_collisionCallbacks == NULL)
2309         {
2310                 self->m_collisionCallbacks = PyList_New(0);
2311                 // Subscribe to collision update from KX_TouchManager
2312                 self->RegisterCollisionCallbacks();
2313         }
2314         Py_INCREF(self->m_collisionCallbacks);
2315         return self->m_collisionCallbacks;
2316 }
2317
2318 int KX_GameObject::pyattr_set_collisionCallbacks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2319 {
2320         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2321
2322         // Only objects with a physics controller should have collision callbacks
2323         if (!self->GetPhysicsController()) {
2324                 PyErr_SetString(PyExc_AttributeError, "KX_GameObject.collisionCallbacks: attribute only available for objects with collisions enabled");
2325                 return PY_SET_ATTR_FAIL;
2326         }
2327
2328         if (!PyList_CheckExact(value))
2329         {
2330                 PyErr_SetString(PyExc_ValueError, "Expected a list");
2331                 return PY_SET_ATTR_FAIL;
2332         }
2333
2334         if (self->m_collisionCallbacks == NULL) {
2335                 self->RegisterCollisionCallbacks();
2336         } else {
2337                 Py_DECREF(self->m_collisionCallbacks);
2338         }
2339
2340         Py_INCREF(value);
2341
2342
2343         self->m_collisionCallbacks = value;
2344
2345         return PY_SET_ATTR_SUCCESS;
2346 }
2347
2348 PyObject *KX_GameObject::pyattr_get_collisionGroup(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2349 {
2350         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2351         return PyLong_FromLong(self->GetUserCollisionGroup());
2352 }
2353
2354 int KX_GameObject::pyattr_set_collisionGroup(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2355 {
2356         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2357         int val = PyLong_AsLong(value);
2358
2359         if (val == -1 && PyErr_Occurred()) {
2360                 PyErr_SetString(PyExc_TypeError, "gameOb.collisionGroup = int: KX_GameObject, expected an int bit field");
2361                 return PY_SET_ATTR_FAIL;
2362         }
2363
2364         if (val == 0 || val & ~((1 << OB_MAX_COL_MASKS) - 1)) {
2365                 PyErr_Format(PyExc_AttributeError, "gameOb.collisionGroup = int: KX_GameObject, expected a int bit field, 0 < group < %i", (1 << OB_MAX_COL_MASKS));
2366                 return PY_SET_ATTR_FAIL;
2367         }
2368
2369         self->SetUserCollisionGroup(val);
2370         return PY_SET_ATTR_SUCCESS;
2371 }
2372
2373 PyObject *KX_GameObject::pyattr_get_collisionMask(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2374 {
2375         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2376         return PyLong_FromLong(self->GetUserCollisionMask());
2377 }
2378
2379 int KX_GameObject::pyattr_set_collisionMask(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2380 {
2381         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2382         int val = PyLong_AsLong(value);
2383
2384         if (val == -1 && PyErr_Occurred()) {
2385                 PyErr_SetString(PyExc_TypeError, "gameOb.collisionMask = int: KX_GameObject, expected an int bit field");
2386                 return PY_SET_ATTR_FAIL;
2387         }
2388
2389         if (val == 0 || val & ~((1 << OB_MAX_COL_MASKS) - 1)) {
2390                 PyErr_Format(PyExc_AttributeError, "gameOb.collisionMask = int: KX_GameObject, expected a int bit field, 0 < mask < %i", (1 << OB_MAX_COL_MASKS));
2391                 return PY_SET_ATTR_FAIL;
2392         }
2393
2394         self->SetUserCollisionMask(val);
2395         return PY_SET_ATTR_SUCCESS;
2396 }
2397
2398 PyObject* KX_GameObject::pyattr_get_scene(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2399 {
2400         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
2401         KX_Scene *scene = self->GetScene();
2402         if (scene) {
2403                 return scene->GetProxy();
2404         }
2405         Py_RETURN_NONE;
2406 }
2407
2408 PyObject *KX_GameObject::pyattr_get_group_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2409 {
2410         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2411         KX_GameObject* pivot = self->GetDupliGroupObject();
2412         if (pivot) {
2413                 return pivot->GetProxy();
2414         }
2415         Py_RETURN_NONE;
2416 }
2417
2418 PyObject *KX_GameObject::pyattr_get_life(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2419 {
2420         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2421
2422         CValue *life = self->GetProperty("::timebomb");
2423         if (life)
2424                 // this convert the timebomb seconds to frames, hard coded 50.0f (assuming 50fps)
2425                 // value hardcoded in KX_Scene::AddReplicaObject()
2426                 return PyFloat_FromDouble(life->GetNumber() * 50.0);
2427         else
2428                 Py_RETURN_NONE;
2429 }
2430
2431 PyObject *KX_GameObject::pyattr_get_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2432 {
2433         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2434         PHY_IPhysicsController *spc = self->GetPhysicsController();
2435         return PyFloat_FromDouble(spc ? spc->GetMass() : 0.0f);
2436 }
2437
2438 int KX_GameObject::pyattr_set_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2439 {
2440         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2441         PHY_IPhysicsController *spc = self->GetPhysicsController();
2442         MT_Scalar val = PyFloat_AsDouble(value);
2443         if (val < 0.0f) { /* also accounts for non float */
2444                 PyErr_SetString(PyExc_AttributeError, "gameOb.mass = float: KX_GameObject, expected a float zero or above");
2445                 return PY_SET_ATTR_FAIL;
2446         }
2447
2448         if (spc)
2449                 spc->SetMass(val);
2450
2451         return PY_SET_ATTR_SUCCESS;
2452 }
2453
2454 PyObject *KX_GameObject::pyattr_get_is_suspend_dynamics(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2455 {
2456         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2457
2458         // Only objects with a physics controller can be suspended
2459         if (!self->GetPhysicsController()) {
2460                 PyErr_SetString(PyExc_AttributeError, "This object has not Physics Controller");
2461                 return NULL;
2462         }
2463
2464         return PyBool_FromLong(self->IsDynamicsSuspended());
2465 }
2466
2467 PyObject *KX_GameObject::pyattr_get_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2468 {
2469         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2470         PHY_IPhysicsController *spc = self->GetPhysicsController();
2471         return PyFloat_FromDouble(spc ? spc->GetLinVelocityMin() : 0.0f);
2472 }
2473
2474 int KX_GameObject::pyattr_set_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2475 {
2476         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2477         PHY_IPhysicsController *spc = self->GetPhysicsController();
2478         MT_Scalar val = PyFloat_AsDouble(value);
2479         if (val < 0.0f) { /* also accounts for non float */
2480                 PyErr_SetString(PyExc_AttributeError, "gameOb.linVelocityMin = float: KX_GameObject, expected a float zero or above");
2481                 return PY_SET_ATTR_FAIL;
2482         }
2483
2484         if (spc)
2485                 spc->SetLinVelocityMin(val);
2486
2487         return PY_SET_ATTR_SUCCESS;
2488 }
2489
2490 PyObject *KX_GameObject::pyattr_get_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2491 {
2492         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2493         PHY_IPhysicsController *spc = self->GetPhysicsController();
2494         return PyFloat_FromDouble(spc ? spc->GetLinVelocityMax() : 0.0f);
2495 }
2496
2497 int KX_GameObject::pyattr_set_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2498 {
2499         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2500         PHY_IPhysicsController *spc = self->GetPhysicsController();
2501         MT_Scalar val = PyFloat_AsDouble(value);
2502         if (val < 0.0f) { /* also accounts for non float */
2503                 PyErr_SetString(PyExc_AttributeError, "gameOb.linVelocityMax = float: KX_GameObject, expected a float zero or above");
2504                 return PY_SET_ATTR_FAIL;
2505         }
2506
2507         if (spc)
2508                 spc->SetLinVelocityMax(val);
2509
2510         return PY_SET_ATTR_SUCCESS;
2511 }
2512
2513 PyObject *KX_GameObject::pyattr_get_ang_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2514 {
2515         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
2516         PHY_IPhysicsController *spc = self->GetPhysicsController();
2517         return PyFloat_FromDouble(spc ? spc->GetAngularVelocityMin() : 0.0f);
2518 }
2519
2520 int KX_GameObject::pyattr_set_ang_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2521 {
2522         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
2523         PHY_IPhysicsController *spc = self->GetPhysicsController();
2524         MT_Scalar val = PyFloat_AsDouble(value);
2525         if (val < 0.0f) { /* also accounts for non float */
2526                 PyErr_SetString(PyExc_AttributeError,
2527                                 "gameOb.angularVelocityMin = float: KX_GameObject, expected a nonnegative float");
2528                 return PY_SET_ATTR_FAIL;
2529         }
2530
2531         if (spc)
2532                 spc->SetAngularVelocityMin(val);
2533
2534         return PY_SET_ATTR_SUCCESS;
2535 }
2536
2537 PyObject *KX_GameObject::pyattr_get_ang_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2538 {
2539         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
2540         PHY_IPhysicsController *spc = self->GetPhysicsController();
2541         return PyFloat_FromDouble(spc ? spc->GetAngularVelocityMax() : 0.0f);
2542 }
2543
2544 int KX_GameObject::pyattr_set_ang_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2545 {
2546         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
2547         PHY_IPhysicsController *spc = self->GetPhysicsController();
2548         MT_Scalar val = PyFloat_AsDouble(value);
2549         if (val < 0.0f) { /* also accounts for non float */
2550                 PyErr_SetString(PyExc_AttributeError,
2551                                 "gameOb.angularVelocityMax = float: KX_GameObject, expected a nonnegative float");
2552                 return PY_SET_ATTR_FAIL;
2553         }
2554
2555         if (spc)
2556                 spc->SetAngularVelocityMax(val);
2557
2558         return PY_SET_ATTR_SUCCESS;
2559 }
2560
2561
2562 PyObject *KX_GameObject::pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2563 {
2564         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2565         return PyBool_FromLong(self->GetVisible());
2566 }
2567
2568 int KX_GameObject::pyattr_set_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2569 {
2570         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2571         int param = PyObject_IsTrue( value );
2572         if (param == -1) {
2573                 PyErr_SetString(PyExc_AttributeError, "gameOb.visible = bool: KX_GameObject, expected True or False");
2574                 return PY_SET_ATTR_FAIL;
2575         }
2576
2577         self->SetVisible(param, false);
2578         self->UpdateBuckets(false);
2579         return PY_SET_ATTR_SUCCESS;
2580 }
2581
2582 PyObject *KX_GameObject::pyattr_get_record_animation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2583 {
2584         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2585         return PyBool_FromLong(self->IsRecordAnimation());
2586 }
2587
2588 int KX_GameObject::pyattr_set_record_animation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2589 {
2590         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2591         int param = PyObject_IsTrue(value);
2592         if (param == -1) {
2593                 PyErr_SetString(PyExc_AttributeError, "gameOb.record_animation = bool: KX_GameObject, expected boolean");
2594                 return PY_SET_ATTR_FAIL;
2595         }
2596
2597         self->SetRecordAnimation(param);
2598
2599         return PY_SET_ATTR_SUCCESS;
2600 }
2601
2602
2603
2604 PyObject *KX_GameObject::pyattr_get_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2605 {
2606 #ifdef USE_MATHUTILS
2607         return Vector_CreatePyObject_cb(
2608                 BGE_PROXY_FROM_REF_BORROW(self_v), 3,
2609                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_POS_GLOBAL);
2610 #else
2611         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2612         return PyObjectFrom(self->NodeGetWorldPosition());
2613 #endif
2614 }
2615
2616 int KX_GameObject::pyattr_set_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2617 {
2618         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2619         MT_Point3 pos;
2620         if (!PyVecTo(value, pos))
2621                 return PY_SET_ATTR_FAIL;
2622         
2623         self->NodeSetWorldPosition(pos);
2624         self->NodeUpdateGS(0.f);
2625         return PY_SET_ATTR_SUCCESS;
2626 }
2627
2628 PyObject *KX_GameObject::pyattr_get_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2629 {
2630 #ifdef USE_MATHUTILS
2631         return Vector_CreatePyObject_cb(
2632                 BGE_PROXY_FROM_REF_BORROW(self_v), 3,
2633                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_POS_LOCAL);
2634 #else
2635         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2636         return PyObjectFrom(self->NodeGetLocalPosition());
2637 #endif
2638 }
2639
2640 int KX_GameObject::pyattr_set_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2641 {
2642         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2643         MT_Point3 pos;
2644         if (!PyVecTo(value, pos))
2645                 return PY_SET_ATTR_FAIL;
2646         
2647         self->NodeSetLocalPosition(pos);
2648         self->NodeUpdateGS(0.f);
2649         return PY_SET_ATTR_SUCCESS;
2650 }
2651
2652 PyObject *KX_GameObject::pyattr_get_localInertia(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2653 {
2654 #ifdef USE_MATHUTILS
2655         return Vector_CreatePyObject_cb(
2656                 BGE_PROXY_FROM_REF_BORROW(self_v), 3,
2657                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_INERTIA_LOCAL);
2658 #else
2659         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2660         if (self->GetPhysicsController1())
2661                 return PyObjectFrom(self->GetPhysicsController1()->GetLocalInertia());
2662         return Py_BuildValue("fff", 0.0f, 0.0f, 0.0f);
2663 #endif
2664 }
2665
2666 PyObject *KX_GameObject::pyattr_get_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2667 {
2668 #ifdef USE_MATHUTILS
2669         return Matrix_CreatePyObject_cb(
2670                 BGE_PROXY_FROM_REF_BORROW(self_v), 3, 3,
2671                 mathutils_kxgameob_matrix_cb_index, MATHUTILS_MAT_CB_ORI_GLOBAL);
2672 #else
2673         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2674         return PyObjectFrom(self->NodeGetWorldOrientation());
2675 #endif
2676 }
2677
2678 int KX_GameObject::pyattr_set_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2679 {
2680         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2681         
2682         /* if value is not a sequence PyOrientationTo makes an error */
2683         MT_Matrix3x3 rot;
2684         if (!PyOrientationTo(value, rot, "gameOb.worldOrientation = sequence: KX_GameObject, "))
2685                 return PY_SET_ATTR_FAIL;
2686
2687         self->NodeSetGlobalOrientation(rot);
2688         
2689         self->NodeUpdateGS(0.f);
2690         return PY_SET_ATTR_SUCCESS;
2691 }
2692
2693 PyObject *KX_GameObject::pyattr_get_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2694 {
2695 #ifdef USE_MATHUTILS
2696         return Matrix_CreatePyObject_cb(
2697                 BGE_PROXY_FROM_REF_BORROW(self_v), 3, 3,
2698                 mathutils_kxgameob_matrix_cb_index, MATHUTILS_MAT_CB_ORI_LOCAL);
2699 #else
2700         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2701         return PyObjectFrom(self->NodeGetLocalOrientation());
2702 #endif
2703 }
2704
2705 int KX_GameObject::pyattr_set_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2706 {
2707         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2708         
2709         /* if value is not a sequence PyOrientationTo makes an error */
2710         MT_Matrix3x3 rot;
2711         if (!PyOrientationTo(value, rot, "gameOb.localOrientation = sequence: KX_GameObject, "))
2712                 return PY_SET_ATTR_FAIL;
2713
2714         self->NodeSetLocalOrientation(rot);
2715         self->NodeUpdateGS(0.f);
2716         return PY_SET_ATTR_SUCCESS;
2717 }
2718
2719 PyObject *KX_GameObject::pyattr_get_worldScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2720 {
2721 #ifdef USE_MATHUTILS
2722         return Vector_CreatePyObject_cb(
2723                 BGE_PROXY_FROM_REF_BORROW(self_v), 3,
2724                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_SCALE_GLOBAL);
2725 #else
2726         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2727         return PyObjectFrom(self->NodeGetWorldScaling());
2728 #endif
2729 }
2730
2731 int KX_GameObject::pyattr_set_worldScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2732 {
2733         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2734         MT_Vector3 scale;
2735         if (!PyVecTo(value, scale))
2736                 return PY_SET_ATTR_FAIL;
2737
2738         self->NodeSetWorldScale(scale);
2739         self->NodeUpdateGS(0.f);
2740         return PY_SET_ATTR_SUCCESS;
2741 }
2742
2743 PyObject *KX_GameObject::pyattr_get_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2744 {
2745 #ifdef USE_MATHUTILS
2746         return Vector_CreatePyObject_cb(
2747                 BGE_PROXY_FROM_REF_BORROW(self_v), 3,
2748                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_SCALE_LOCAL);
2749 #else
2750         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2751         return PyObjectFrom(self->NodeGetLocalScaling());
2752 #endif
2753 }
2754
2755 int KX_GameObject::pyattr_set_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2756 {
2757         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2758         MT_Vector3 scale;
2759         if (!PyVecTo(value, scale))
2760                 return PY_SET_ATTR_FAIL;
2761
2762         self->NodeSetLocalScale(scale);
2763         self->NodeUpdateGS(0.f);
2764         return PY_SET_ATTR_SUCCESS;
2765 }
2766
2767 PyObject *KX_GameObject::pyattr_get_localTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2768 {
2769         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2770
2771         float mat[16];
2772
2773         MT_Transform trans;
2774         
2775         trans.setOrigin(self->GetSGNode()->GetLocalPosition());
2776         trans.setBasis(self->GetSGNode()->GetLocalOrientation());
2777         
2778         MT_Vector3 scaling = self->GetSGNode()->GetLocalScale();
2779         trans.scale(scaling[0], scaling[1], scaling[2]);
2780
2781         trans.getValue(mat);
2782
2783         return PyObjectFrom(MT_Matrix4x4(mat));
2784 }
2785
2786 int KX_GameObject::pyattr_set_localTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2787 {
2788         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2789         MT_Matrix4x4 temp;
2790         if (!PyMatTo(value, temp))
2791                 return PY_SET_ATTR_FAIL;
2792
2793         float transform[4][4];
2794         float loc[3], size[3];
2795         float rot[3][3];
2796         MT_Matrix3x3 orientation;
2797
2798         temp.getValue(*transform);
2799         mat4_to_loc_rot_size(loc, rot, size, transform);
2800
2801         self->NodeSetLocalPosition(MT_Point3(loc));
2802
2803         //MT_Matrix3x3's constructor expects a 4x4 matrix
2804         orientation = MT_Matrix3x3();
2805         orientation.setValue3x3(*rot);
2806         self->NodeSetLocalOrientation(orientation);
2807
2808         self->NodeSetLocalScale(MT_Vector3(size));
2809
2810         return PY_SET_ATTR_SUCCESS;
2811 }
2812
2813 PyObject *KX_GameObject::pyattr_get_worldTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2814 {
2815         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2816
2817         return PyObjectFrom(MT_Matrix4x4(self->GetOpenGLMatrix()));
2818 }
2819
2820 int KX_GameObject::pyattr_set_worldTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2821 {
2822         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2823         MT_Matrix4x4 temp;
2824         if (!PyMatTo(value, temp))
2825                 return PY_SET_ATTR_FAIL;
2826
2827         float transform[4][4];
2828         float loc[3], size[3];
2829         float rot[3][3];
2830         MT_Matrix3x3 orientation;
2831
2832         temp.getValue(*transform);
2833         mat4_to_loc_rot_size(loc, rot, size, transform);
2834
2835         self->NodeSetWorldPosition(MT_Point3(loc));
2836
2837         //MT_Matrix3x3's constructor expects a 4x4 matrix
2838         orientation = MT_Matrix3x3();
2839         orientation.setValue3x3(*rot);
2840         self->NodeSetGlobalOrientation(orientation);
2841
2842         self->NodeSetWorldScale(MT_Vector3(size));
2843
2844         return PY_SET_ATTR_SUCCESS;
2845 }
2846
2847 PyObject *KX_GameObject::pyattr_get_worldLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2848 {
2849 #ifdef USE_MATHUTILS
2850         return Vector_CreatePyObject_cb(
2851                 BGE_PROXY_FROM_REF_BORROW(self_v), 3,
2852                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_LINVEL_GLOBAL);
2853 #else
2854         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2855         return PyObjectFrom(GetLinearVelocity(false));
2856 #endif
2857 }
2858
2859 int KX_GameObject::pyattr_set_worldLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2860 {
2861         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2862         MT_Vector3 velocity;
2863         if (!PyVecTo(value, velocity))
2864                 return PY_SET_ATTR_FAIL;
2865
2866         self->setLinearVelocity(velocity, false);
2867
2868         return PY_SET_ATTR_SUCCESS;
2869 }
2870
2871 PyObject *KX_GameObject::pyattr_get_localLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2872 {
2873 #ifdef USE_MATHUTILS
2874         return Vector_CreatePyObject_cb(
2875                 BGE_PROXY_FROM_REF_BORROW(self_v), 3,
2876                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_LINVEL_LOCAL);
2877 #else
2878         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2879         return PyObjectFrom(GetLinearVelocity(true));
2880 #endif
2881 }
2882
2883 int KX_GameObject::pyattr_set_localLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2884 {
2885         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2886         MT_Vector3 velocity;
2887         if (!PyVecTo(value, velocity))
2888                 return PY_SET_ATTR_FAIL;
2889
2890         self->setLinearVelocity(velocity, true);
2891
2892         return PY_SET_ATTR_SUCCESS;
2893 }
2894
2895 PyObject *KX_GameObject::pyattr_get_worldAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2896 {
2897 #ifdef USE_MATHUTILS
2898         return Vector_CreatePyObject_cb(
2899                 BGE_PROXY_FROM_REF_BORROW(self_v), 3,
2900                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_ANGVEL_GLOBAL);
2901 #else
2902         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2903         return PyObjectFrom(GetAngularVelocity(false));
2904 #endif
2905 }
2906
2907 int KX_GameObject::pyattr_set_worldAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2908 {
2909         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2910         MT_Vector3 velocity;
2911         if (!PyVecTo(value, velocity))
2912                 return PY_SET_ATTR_FAIL;
2913
2914         self->setAngularVelocity(velocity, false);
2915
2916         return PY_SET_ATTR_SUCCESS;
2917 }
2918
2919 PyObject *KX_GameObject::pyattr_get_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2920 {
2921 #ifdef USE_MATHUTILS
2922         return Vector_CreatePyObject_cb(
2923                 BGE_PROXY_FROM_REF_BORROW(self_v), 3,
2924                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_ANGVEL_LOCAL);
2925 #else
2926         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2927         return PyObjectFrom(GetAngularVelocity(true));
2928 #endif
2929 }
2930
2931 int KX_GameObject::pyattr_set_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2932 {
2933         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2934         MT_Vector3 velocity;
2935         if (!PyVecTo(value, velocity))
2936                 return PY_SET_ATTR_FAIL;
2937
2938         self->setAngularVelocity(velocity, true);
2939
2940         return PY_SET_ATTR_SUCCESS;
2941 }
2942
2943 PyObject *KX_GameObject::pyattr_get_linearDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2944 {
2945         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2946         return PyFloat_FromDouble(self->getLinearDamping());
2947 }
2948
2949 int KX_GameObject::pyattr_set_linearDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2950 {
2951         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2952         float val = PyFloat_AsDouble(value);
2953         self->setLinearDamping(val);
2954         return PY_SET_ATTR_SUCCESS;
2955 }
2956
2957 PyObject *KX_GameObject::pyattr_get_angularDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2958 {
2959         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2960         return PyFloat_FromDouble(self->getAngularDamping());
2961 }
2962
2963 int KX_GameObject::pyattr_set_angularDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2964 {
2965         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2966         float val = PyFloat_AsDouble(value);
2967         self->setAngularDamping(val);
2968         return PY_SET_ATTR_SUCCESS;
2969 }
2970
2971
2972 PyObject *KX_GameObject::pyattr_get_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2973 {
2974         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2975         SG_Node* sg_parent;
2976         if (self->GetSGNode() && (sg_parent = self->GetSGNode()->GetSGParent()) != NULL && sg_parent->IsSlowParent()) {
2977                 return PyFloat_FromDouble(static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->GetTimeOffset());
2978         } else {
2979                 return PyFloat_FromDouble(0.0f);
2980         }
2981 }
2982
2983 int KX_GameObject::pyattr_set_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2984 {
2985         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2986         if (self->GetSGNode()) {
2987                 MT_Scalar val = PyFloat_AsDouble(value);
2988                 SG_Node *sg_parent= self->GetSGNode()->GetSGParent();
2989                 if (val < 0.0f) { /* also accounts for non float */
2990                         PyErr_SetString(PyExc_AttributeError, "gameOb.timeOffset = float: KX_GameObject, expected a float zero or above");
2991                         return PY_SET_ATTR_FAIL;
2992                 }
2993                 if (sg_parent && sg_parent->IsSlowParent())
2994                         static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->SetTimeOffset(val);
2995         }
2996         return PY_SET_ATTR_SUCCESS;
2997 }
2998
2999 PyObject *KX_GameObject::pyattr_get_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3000 {
3001         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
3002         int state = 0;
3003         state |= self->GetState();
3004         return PyLong_FromLong(state);
3005 }
3006
3007 int KX_GameObject::pyattr_set_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
3008 {
3009         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
3010         int state_i = PyLong_AsLong(value);
3011         unsigned int state = 0;
3012         
3013         if (state_i == -1 && PyErr_Occurred()) {
3014                 PyErr_SetString(PyExc_TypeError, "gameOb.state = int: KX_GameObject, expected an int bit field");
3015                 return PY_SET_ATTR_FAIL;
3016         }
3017         
3018         state |= state_i;
3019         if ((state & ((1<<30)-1)) == 0) {
3020                 PyErr_SetString(PyExc_AttributeError, "gameOb.state = int: KX_GameObject, state bitfield was not between 0 and 30 (1<<0 and 1<<29)");
3021                 return PY_SET_ATTR_FAIL;
3022         }
3023         self->SetState(state);
3024         return PY_SET_ATTR_SUCCESS;
3025 }
3026
3027 PyObject *KX_GameObject::pyattr_get_meshes(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3028 {
3029         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
3030         PyObject *meshes= PyList_New(self->m_meshes.size());
3031         int i;
3032         
3033         for (i=0; i < (int)self->m_meshes.size(); i++)
3034         {
3035                 KX_MeshProxy* meshproxy = new KX_MeshProxy(self->m_meshes[i]);
3036                 PyList_SET_ITEM(meshes, i, meshproxy->NewProxy(true));
3037         }
3038         
3039         return meshes;
3040 }
3041
3042 PyObject *KX_GameObject::pyattr_get_obcolor(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3043 {
3044 #ifdef USE_MATHUTILS
3045         return Vector_CreatePyObject_cb(
3046                 BGE_PROXY_FROM_REF_BORROW(self_v), 4,
3047                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_OBJECT_COLOR);
3048 #else
3049         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
3050         return PyObjectFrom(self->GetObjectColor());
3051 #endif
3052 }
3053
3054 int KX_GameObject::pyattr_set_obcolor(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
3055 {
3056         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
3057         MT_Vector4 obcolor;
3058         if (!PyVecTo(value, obcolor))
3059                 return PY_SET_ATTR_FAIL;
3060
3061         self->SetObjectColor(obcolor);
3062         return PY_SET_ATTR_SUCCESS;
3063 }
3064
3065 static int kx_game_object_get_sensors_size_cb(void *self_v)
3066 {
3067         return ((KX_GameObject *)self_v)->GetSensors().size();
3068 }
3069
3070 static PyObject *kx_game_object_get_sensors_item_cb(void *self_v, int index)
3071 {
3072         return ((KX_GameObject *)self_v)->GetSensors()[index]->GetProxy();
3073 }
3074
3075 static const char *kx_game_object_get_sensors_item_name_cb(void *self_v, int index)
3076 {
3077         return ((KX_GameObject *)self_v)->GetSensors()[index]->GetName().ReadPtr();
3078 }
3079
3080 /* These are experimental! */
3081 PyObject *KX_GameObject::pyattr_get_sensors(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3082 {
3083         return (new CListWrapper(self_v,
3084                                                          ((KX_GameObject *)self_v)->GetProxy(),
3085                                                          NULL,
3086                                                          kx_game_object_get_sensors_size_cb,
3087                                                          kx_game_object_get_sensors_item_cb,
3088                                                          kx_game_object_get_sensors_item_name_cb,
3089                                                          NULL))->NewProxy(true);
3090 }
3091
3092 static int kx_game_object_get_controllers_size_cb(void *self_v)
3093 {
3094         return ((KX_GameObject *)self_v)->GetControllers().size();
3095 }
3096
3097 static PyObject *kx_game_object_get_controllers_item_cb(void *self_v, int index)
3098 {
3099         return ((KX_GameObject *)self_v)->GetControllers()[index]->GetProxy();
3100 }
3101
3102 static const char *kx_game_object_get_controllers_item_name_cb(void *self_v, int index)
3103 {
3104         return ((KX_GameObject *)self_v)->GetControllers()[index]->GetName().ReadPtr();
3105 }
3106
3107 PyObject *KX_GameObject::pyattr_get_controllers(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3108 {
3109         return (new CListWrapper(self_v,
3110                                                          ((KX_GameObject *)self_v)->GetProxy(),
3111                                                          NULL,
3112                                                          kx_game_object_get_controllers_size_cb,
3113                                                          kx_game_object_get_controllers_item_cb,
3114                                                          kx_game_object_get_controllers_item_name_cb,
3115                                                          NULL))->NewProxy(true);
3116 }
3117
3118 static int kx_game_object_get_actuators_size_cb(void *self_v)
3119 {
3120         return ((KX_GameObject *)self_v)->GetActuators().size();
3121 }
3122
3123 static PyObject *kx_game_object_get_actuators_item_cb(void *self_v, int index)
3124 {
3125         return ((KX_GameObject *)self_v)->GetActuators()[index]->GetProxy();
3126 }
3127
3128 static const char *kx_game_object_get_actuators_item_name_cb(void *self_v, int index)
3129 {
3130         return ((KX_GameObject *)self_v)->GetActuators()[index]->GetName().ReadPtr();
3131 }
3132
3133 PyObject *KX_GameObject::pyattr_get_actuators(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3134 {
3135         return (new CListWrapper(self_v,
3136                                                          ((KX_GameObject *)self_v)->GetProxy(),
3137                                                          NULL,
3138                                                          kx_game_object_get_actuators_size_cb,
3139                                                          kx_game_object_get_actuators_item_cb,
3140                                                          kx_game_object_get_actuators_item_name_cb,
3141                                                          NULL))->NewProxy(true);
3142 }
3143 /* End experimental */
3144
3145 PyObject *KX_GameObject::pyattr_get_children(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3146 {
3147         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
3148         return self->GetChildren()->NewProxy(true);
3149 }
3150
3151 PyObject *KX_GameObject::pyattr_get_children_recursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3152 {
3153         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
3154         return self->GetChildrenRecursive()->NewProxy(true);
3155 }
3156
3157 PyObject *KX_GameObject::pyattr_get_attrDict(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3158 {
3159         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
3160         
3161         if (self->m_attr_dict==NULL)
3162                 self->m_attr_dict= PyDict_New();
3163         
3164         Py_INCREF(self->m_attr_dict);
3165         return self->m_attr_dict;
3166 }
3167
3168 PyObject *KX_GameObject::pyattr_get_debug(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3169 {
3170         KX_Scene *scene = KX_GetActiveScene();
3171         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
3172
3173         return PyBool_FromLong(scene->ObjectInDebugList(self));
3174 }
3175
3176 int KX_GameObject::pyattr_set_debug(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
3177 {
3178         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
3179         int param = PyObject_IsTrue(value);
3180
3181         if (param == -1) {
3182                 PyErr_SetString(PyExc_AttributeError, "gameOb.debug = bool: KX_GameObject, expected True or False");
3183                 return PY_SET_ATTR_FAIL;
3184         }
3185
3186         self->SetUseDebugProperties(param, false);
3187
3188         return PY_SET_ATTR_SUCCESS;
3189 }
3190
3191 PyObject *KX_GameObject::pyattr_get_debugRecursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3192 {
3193         KX_Scene *scene = KX_GetActiveScene();
3194         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
3195
3196         return PyBool_FromLong(scene->ObjectInDebugList(self));
3197 }
3198
3199 int KX_GameObject::pyattr_set_debugRecursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
3200 {
3201         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
3202         int param = PyObject_IsTrue(value);
3203
3204         if (param == -1) {
3205                 PyErr_SetString(PyExc_AttributeError, "gameOb.debugRecursive = bool: KX_GameObject, expected True or False");
3206                 return PY_SET_ATTR_FAIL;
3207         }
3208
3209         self->SetUseDebugProperties(param, true);
3210
3211         return PY_SET_ATTR_SUCCESS;
3212 }
3213
3214 PyObject *KX_GameObject::PyApplyForce(PyObject *args)
3215 {
3216         int local = 0;
3217         PyObject *pyvect;
3218
3219         if (PyArg_ParseTuple(args, "O|i:applyForce", &pyvect, &local)) {
3220                 MT_Vector3 force;
3221                 if (PyVecTo(pyvect, force)) {
3222                         ApplyForce(force, (local!=0));
3223                         Py_RETURN_NONE;
3224                 }
3225         }
3226         return NULL;
3227 }
3228
3229 PyObject *KX_GameObject::PyApplyTorque(PyObject *args)
3230 {
3231         int local = 0;
3232         PyObject *pyvect;
3233
3234         if (PyArg_ParseTuple(args, "O|i:applyTorque", &pyvect, &local)) {
3235                 MT_Vector3 torque;
3236                 if (PyVecTo(pyvect, torque)) {
3237                         ApplyTorque(torque, (local!=0));
3238                         Py_RETURN_NONE;
3239                 }
3240         }
3241         return NULL;
3242 }
3243
3244 PyObject *KX_GameObject::PyApplyRotation(PyObject *args)
3245 {
3246         int local = 0;
3247         PyObject *pyvect;
3248
3249         if (PyArg_ParseTuple(args, "O|i:applyRotation", &pyvect, &local)) {
3250                 MT_Vector3 rotation;
3251                 if (PyVecTo(pyvect, rotation)) {
3252                         ApplyRotation(rotation, (local!=0));
3253                         Py_RETURN_NONE;
3254                 }
3255         }
3256         return NULL;
3257 }
3258
3259 PyObject *KX_GameObject::PyApplyMovement(PyObject *args)
3260 {
3261         int local = 0;
3262         PyObject *pyvect;
3263
3264         if (PyArg_ParseTuple(args, "O|i:applyMovement", &pyvect, &local)) {
3265                 MT_Vector3 movement;
3266                 if (PyVecTo(pyvect, movement)) {
3267                         ApplyMovement(movement, (local!=0));
3268                         Py_RETURN_NONE;
3269                 }
3270         }
3271         return NULL;
3272 }
3273
3274 PyObject *KX_GameObject::PyGetLinearVelocity(PyObject *args)
3275 {
3276         // only can get the velocity if we have a physics object connected to us...
3277         int local = 0;
3278         if (PyArg_ParseTuple(args,"|i:getLinearVelocity",&local))
3279         {
3280                 return PyObjectFrom(GetLinearVelocity((local!=0)));
3281         }
3282         else
3283         {
3284                 return NULL;
3285         }
3286 }
3287
3288 PyObject *KX_GameObject::PySetLinearVelocity(PyObject *args)
3289 {
3290         int local = 0;
3291         PyObject *pyvect;
3292         
3293         if (PyArg_ParseTuple(args,"O|i:setLinearVelocity",&pyvect,&local)) {
3294                 MT_Vector3 velocity;
3295                 if (PyVecTo(pyvect, velocity)) {
3296                         setLinearVelocity(velocity, (local!=0));
3297                         Py_RETURN_NONE;
3298                 }
3299         }
3300         return NULL;
3301 }
3302
3303 PyObject *KX_GameObject::PyGetAngularVelocity(PyObject *args)
3304 {
3305         // only can get the velocity if we have a physics object connected to us...
3306         int local = 0;
3307         if (PyArg_ParseTuple(args,"|i:getAngularVelocity",&local))
3308         {
3309                 return PyObjectFrom(GetAngularVelocity((local!=0)));
3310         }
3311         else
3312         {
3313                 return NULL;
3314         }
3315 }
3316
3317 PyObject *KX_GameObject::PySetAngularVelocity(PyObject *args)
3318 {
3319         int local = 0;
3320         PyObject *pyvect;
3321         
3322         if (PyArg_ParseTuple(args,"O|i:setAngularVelocity",&pyvect,&local)) {
3323                 MT_Vector3 velocity;
3324                 if (PyVecTo(pyvect, velocity)) {
3325                         setAngularVelocity(velocity, (local!=0));
3326                         Py_RETURN_NONE;
3327                 }
3328         }
3329         return NULL;
3330 }
3331
3332 PyObject *KX_GameObject::PySetDamping(PyObject *args)
3333 {
3334         float linear;
3335         float angular;
3336
3337         if (!PyArg_ParseTuple(args,"ff|i:setDamping", &linear, &angular))
3338                 return NULL;
3339
3340         setDamping(linear, angular);
3341         Py_RETURN_NONE;
3342 }
3343
3344 PyObject *KX_GameObject::PySetVisible(PyObject *args)
3345 {
3346         int visible, recursive = 0;
3347         if (!PyArg_ParseTuple(args,"i|i:setVisible",&visible, &recursive))
3348                 return NULL;
3349         
3350         SetVisible(visible ? true:false, recursive ? true:false);
3351         UpdateBuckets(recursive ? true:false);
3352         Py_RETURN_NONE;
3353         
3354 }
3355
3356 PyObject *KX_GameObject::PySetOcclusion(PyObject *args)
3357 {
3358         int occlusion, recursive = 0;
3359         if (!PyArg_ParseTuple(args,"i|i:setOcclusion",&occlusion, &recursive))
3360                 return NULL;
3361         
3362         SetOccluder(occlusion ? true:false, recursive ? true:false);
3363         Py_RETURN_NONE;
3364 }
3365
3366 PyObject *KX_GameObject::PyGetVelocity(PyObject *args)
3367 {
3368         // only can get the velocity if we have a physics object connected to us...
3369         MT_Point3 point(0.0f,0.0f,0.0f);
3370         PyObject *pypos = NULL;
3371         
3372         if (!PyArg_ParseTuple(args, "|O:getVelocity", &pypos) || (pypos && !PyVecTo(pypos, point)))
3373                 return NULL;
3374
3375         return PyObjectFrom(GetVelocity(point));
3376 }
3377
3378 PyObject *KX_GameObject::PyGetReactionForce()
3379 {
3380         // only can get the velocity if we have a physics object connected to us...
3381         
3382         // XXX - Currently not working with bullet intergration, see KX_BulletPhysicsController.cpp's getReactionForce
3383 #if 0
3384         if (GetPhysicsController1())
3385                 return PyObjectFrom(GetPhysicsController1()->getReactionForce());
3386         return PyObjectFrom(dummy_point);
3387 #endif
3388         
3389         return Py_BuildValue("fff", 0.0f, 0.0f, 0.0f);
3390         
3391 }
3392
3393
3394
3395 PyObject *KX_GameObject::PyEnableRigidBody()
3396 {
3397         if (GetPhysicsController())
3398                 GetPhysicsController()->SetRigidBody(true);
3399
3400         Py_RETURN_NONE;
3401 }
3402
3403
3404