69c1af35bd9d59fa94890e6db4f20b4b138cc718
[blender-staging.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         const MT_Scalar eps = 3.0f * MT_EPSILON;
1191         MT_Matrix3x3 orimat;
1192         MT_Vector3 vect,ori,z,x,y;
1193         MT_Scalar len;
1194
1195         // check on valid node in case a python controller holds a reference to a deleted object
1196         if (!GetSGNode())
1197                 return;
1198
1199         vect = dir;
1200         len = vect.length();
1201         if (MT_fuzzyZero(len))
1202         {
1203                 cout << "alignAxisToVect() Error: Null vector!\n";
1204                 return;
1205         }
1206         
1207         if (fac <= 0.0f) {
1208                 return;
1209         }
1210         
1211         // normalize
1212         vect /= len;
1213         orimat = GetSGNode()->GetWorldOrientation();
1214         switch (axis)
1215         {
1216                 case 0: // align x axis of new coord system to vect
1217                         ori.setValue(orimat[0][2], orimat[1][2], orimat[2][2]); // pivot axis
1218                         if (1.0f - MT_abs(vect.dot(ori)) < eps)  { // vect parallel to pivot?
1219                                 ori.setValue(orimat[0][1], orimat[1][1], orimat[2][1]); // change the pivot!
1220                         }
1221
1222                         if (fac == 1.0f) {
1223                                 x = vect;
1224                         } else {
1225                                 x = (vect * fac) + ((orimat * MT_Vector3(1.0f, 0.0f, 0.0f)) * (1.0f - fac));
1226                                 len = x.length();
1227                                 if (MT_fuzzyZero(len)) x = vect;
1228                                 else x /= len;
1229                         }
1230                         y = ori.cross(x);
1231                         z = x.cross(y);
1232                         break;
1233                 case 1: // y axis
1234                         ori.setValue(orimat[0][0], orimat[1][0], orimat[2][0]);
1235                         if (1.0f - MT_abs(vect.dot(ori)) < eps) {
1236                                 ori.setValue(orimat[0][2], orimat[1][2], orimat[2][2]);
1237                         }
1238
1239                         if (fac == 1.0f) {
1240                                 y = vect;
1241                         } else {
1242                                 y = (vect * fac) + ((orimat * MT_Vector3(0.0f, 1.0f, 0.0f)) * (1.0f - fac));
1243                                 len = y.length();
1244                                 if (MT_fuzzyZero(len)) y = vect;
1245                                 else y /= len;
1246                         }
1247                         z = ori.cross(y);
1248                         x = y.cross(z);
1249                         break;
1250                 case 2: // z axis
1251                         ori.setValue(orimat[0][1], orimat[1][1], orimat[2][1]);
1252                         if (1.0f - MT_abs(vect.dot(ori)) < eps) {
1253                                 ori.setValue(orimat[0][0], orimat[1][0], orimat[2][0]);
1254                         }
1255
1256                         if (fac == 1.0f) {
1257                                 z = vect;
1258                         } else {
1259                                 z = (vect * fac) + ((orimat * MT_Vector3(0.0f, 0.0f, 1.0f)) * (1.0f - fac));
1260                                 len = z.length();
1261                                 if (MT_fuzzyZero(len)) z = vect;
1262                                 else z /= len;
1263                         }
1264                         x = ori.cross(z);
1265                         y = z.cross(x);
1266                         break;
1267                 default: // invalid axis specified
1268                         cout << "alignAxisToVect(): Invalid axis '" << axis <<"'\n";
1269                         return;
1270         }
1271         x.normalize(); // normalize the new base vectors
1272         y.normalize();
1273         z.normalize();
1274         orimat.setValue(x[0], y[0], z[0],
1275                         x[1], y[1], z[1],
1276                         x[2], y[2], z[2]);
1277
1278         if (GetSGNode()->GetSGParent() != NULL)
1279         {
1280                 // the object is a child, adapt its local orientation so that 
1281                 // the global orientation is aligned as we want (cancelling out the parent orientation)
1282                 MT_Matrix3x3 invori = GetSGNode()->GetSGParent()->GetWorldOrientation().inverse();
1283                 NodeSetLocalOrientation(invori*orimat);
1284         }
1285         else {
1286                 NodeSetLocalOrientation(orimat);
1287         }
1288 }
1289
1290 MT_Scalar KX_GameObject::GetMass()
1291 {
1292         if (m_pPhysicsController)
1293         {
1294                 return m_pPhysicsController->GetMass();
1295         }
1296         return 0.0f;
1297 }
1298
1299 MT_Vector3 KX_GameObject::GetLocalInertia()
1300 {
1301         MT_Vector3 local_inertia(0.0f,0.0f,0.0f);
1302         if (m_pPhysicsController)
1303         {
1304                 local_inertia = m_pPhysicsController->GetLocalInertia();
1305         }
1306         return local_inertia;
1307 }
1308
1309 MT_Vector3 KX_GameObject::GetLinearVelocity(bool local)
1310 {
1311         MT_Vector3 velocity(0.0f,0.0f,0.0f), locvel;
1312         MT_Matrix3x3 ori;
1313         if (m_pPhysicsController)
1314         {
1315                 velocity = m_pPhysicsController->GetLinearVelocity();
1316                 
1317                 if (local)
1318                 {
1319                         ori = GetSGNode()->GetWorldOrientation();
1320                         
1321                         locvel = velocity * ori;
1322                         return locvel;
1323                 }
1324         }
1325         return velocity;
1326 }
1327
1328 MT_Vector3 KX_GameObject::GetAngularVelocity(bool local)
1329 {
1330         MT_Vector3 velocity(0.0f,0.0f,0.0f), locvel;
1331         MT_Matrix3x3 ori;
1332         if (m_pPhysicsController)
1333         {
1334                 velocity = m_pPhysicsController->GetAngularVelocity();
1335                 
1336                 if (local)
1337                 {
1338                         ori = GetSGNode()->GetWorldOrientation();
1339                         
1340                         locvel = velocity * ori;
1341                         return locvel;
1342                 }
1343         }
1344         return velocity;
1345 }
1346
1347 MT_Vector3 KX_GameObject::GetVelocity(const MT_Point3& point)
1348 {
1349         if (m_pPhysicsController)
1350         {
1351                 return m_pPhysicsController->GetVelocity(point);
1352         }
1353         return MT_Vector3(0.0f,0.0f,0.0f);
1354 }
1355
1356 // scenegraph node stuff
1357
1358 void KX_GameObject::NodeSetLocalPosition(const MT_Point3& trans)
1359 {
1360         // check on valid node in case a python controller holds a reference to a deleted object
1361         if (!GetSGNode())
1362                 return;
1363
1364         if (m_pPhysicsController && !GetSGNode()->GetSGParent())
1365         {
1366                 // don't update physic controller if the object is a child:
1367                 // 1) the transformation will not be right
1368                 // 2) in this case, the physic controller is necessarily a static object
1369                 //    that is updated from the normal kinematic synchronization
1370                 m_pPhysicsController->SetPosition(trans);
1371         }
1372
1373         GetSGNode()->SetLocalPosition(trans);
1374
1375 }
1376
1377
1378
1379 void KX_GameObject::NodeSetLocalOrientation(const MT_Matrix3x3& rot)
1380 {
1381         // check on valid node in case a python controller holds a reference to a deleted object
1382         if (!GetSGNode())
1383                 return;
1384
1385         if (m_pPhysicsController && !GetSGNode()->GetSGParent())
1386         {
1387                 // see note above
1388                 m_pPhysicsController->SetOrientation(rot);
1389         }
1390         GetSGNode()->SetLocalOrientation(rot);
1391 }
1392
1393 void KX_GameObject::NodeSetGlobalOrientation(const MT_Matrix3x3& rot)
1394 {
1395         // check on valid node in case a python controller holds a reference to a deleted object
1396         if (!GetSGNode())
1397                 return;
1398
1399         if (GetSGNode()->GetSGParent())
1400                 GetSGNode()->SetLocalOrientation(GetSGNode()->GetSGParent()->GetWorldOrientation().inverse()*rot);
1401         else
1402                 NodeSetLocalOrientation(rot);
1403 }
1404
1405 void KX_GameObject::NodeSetLocalScale(const MT_Vector3& scale)
1406 {
1407         // check on valid node in case a python controller holds a reference to a deleted object
1408         if (!GetSGNode())
1409                 return;
1410
1411         if (m_pPhysicsController && !GetSGNode()->GetSGParent())
1412         {
1413                 // see note above
1414                 m_pPhysicsController->SetScaling(scale);
1415         }
1416         GetSGNode()->SetLocalScale(scale);
1417 }
1418
1419
1420
1421 void KX_GameObject::NodeSetRelativeScale(const MT_Vector3& scale)
1422 {
1423         if (GetSGNode())
1424         {
1425                 GetSGNode()->RelativeScale(scale);
1426                 if (m_pPhysicsController && (!GetSGNode()->GetSGParent()))
1427                 {
1428                         // see note above
1429                         // we can use the local scale: it's the same thing for a root object 
1430                         // and the world scale is not yet updated
1431                         MT_Vector3 newscale = GetSGNode()->GetLocalScale();
1432                         m_pPhysicsController->SetScaling(newscale);
1433                 }
1434         }
1435 }
1436
1437 void KX_GameObject::NodeSetWorldScale(const MT_Vector3& scale)
1438 {
1439         if (!GetSGNode())
1440                 return;
1441         SG_Node* parent = GetSGNode()->GetSGParent();
1442         if (parent != NULL)
1443         {
1444                 // Make sure the objects have some scale
1445                 MT_Vector3 p_scale = parent->GetWorldScaling();
1446                 if (fabs(p_scale[0]) < (MT_Scalar)FLT_EPSILON ||
1447                         fabs(p_scale[1]) < (MT_Scalar)FLT_EPSILON ||
1448                         fabs(p_scale[2]) < (MT_Scalar)FLT_EPSILON)
1449                 { 
1450                         return; 
1451                 }
1452
1453                 p_scale[0] = 1/p_scale[0];
1454                 p_scale[1] = 1/p_scale[1];
1455                 p_scale[2] = 1/p_scale[2];
1456
1457                 NodeSetLocalScale(scale * p_scale);
1458         }
1459         else
1460         {
1461                 NodeSetLocalScale(scale);
1462         }
1463 }
1464
1465 void KX_GameObject::NodeSetWorldPosition(const MT_Point3& trans)
1466 {
1467         if (!GetSGNode())
1468                 return;
1469         SG_Node* parent = GetSGNode()->GetSGParent();
1470         if (parent != NULL)
1471         {
1472                 // Make sure the objects have some scale
1473                 MT_Vector3 scale = parent->GetWorldScaling();
1474                 if (fabs(scale[0]) < (MT_Scalar)FLT_EPSILON ||
1475                         fabs(scale[1]) < (MT_Scalar)FLT_EPSILON ||
1476                         fabs(scale[2]) < (MT_Scalar)FLT_EPSILON)
1477                 { 
1478                         return; 
1479                 }
1480                 scale[0] = 1.0f/scale[0];
1481                 scale[1] = 1.0f/scale[1];
1482                 scale[2] = 1.0f/scale[2];
1483                 MT_Matrix3x3 invori = parent->GetWorldOrientation().inverse();
1484                 MT_Vector3 newpos = invori*(trans-parent->GetWorldPosition())*scale;
1485                 NodeSetLocalPosition(MT_Point3(newpos[0],newpos[1],newpos[2]));
1486         }
1487         else
1488         {
1489                 NodeSetLocalPosition(trans);
1490         }
1491 }
1492
1493
1494 void KX_GameObject::NodeUpdateGS(double time)
1495 {
1496         if (GetSGNode())
1497                 GetSGNode()->UpdateWorldData(time);
1498 }
1499
1500
1501
1502 const MT_Matrix3x3& KX_GameObject::NodeGetWorldOrientation() const
1503 {
1504         // check on valid node in case a python controller holds a reference to a deleted object
1505         if (!GetSGNode())
1506                 return dummy_orientation;
1507         return GetSGNode()->GetWorldOrientation();
1508 }
1509
1510 const MT_Matrix3x3& KX_GameObject::NodeGetLocalOrientation() const
1511 {
1512         // check on valid node in case a python controller holds a reference to a deleted object
1513         if (!GetSGNode())
1514                 return dummy_orientation;
1515         return GetSGNode()->GetLocalOrientation();
1516 }
1517
1518 const MT_Vector3& KX_GameObject::NodeGetWorldScaling() 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()->GetWorldScaling();
1525 }
1526
1527 const MT_Vector3& KX_GameObject::NodeGetLocalScaling() const
1528 {
1529         // check on valid node in case a python controller holds a reference to a deleted object
1530         if (!GetSGNode())
1531                 return dummy_scaling;
1532
1533         return GetSGNode()->GetLocalScale();
1534 }
1535
1536 const MT_Point3& KX_GameObject::NodeGetWorldPosition() 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()->GetWorldPosition();
1541         else
1542                 return dummy_point;
1543 }
1544
1545 const MT_Point3& KX_GameObject::NodeGetLocalPosition() const
1546 {
1547         // check on valid node in case a python controller holds a reference to a deleted object
1548         if (GetSGNode())
1549                 return GetSGNode()->GetLocalPosition();
1550         else
1551                 return dummy_point;
1552 }
1553
1554
1555 void KX_GameObject::UnregisterCollisionCallbacks()
1556 {
1557         if (!GetPhysicsController()) {
1558                 printf("Warning, trying to unregister collision callbacks for object without collisions: %s!\n", GetName().ReadPtr());
1559                 return;
1560         }
1561
1562         // Unregister from callbacks
1563         KX_Scene* scene = GetScene();
1564         PHY_IPhysicsEnvironment* pe = scene->GetPhysicsEnvironment();
1565         PHY_IPhysicsController* spc = GetPhysicsController();
1566         // If we are the last to unregister on this physics controller
1567         if (pe->RemoveCollisionCallback(spc)){
1568                 // If we are a sensor object
1569                 if (m_pClient_info->isSensor())
1570                         // Remove sensor body from physics world
1571                         pe->RemoveSensor(spc);
1572         }
1573 }
1574
1575 void KX_GameObject::RegisterCollisionCallbacks()
1576 {
1577         if (!GetPhysicsController()) {
1578                 printf("Warning, trying to register collision callbacks for object without collisions: %s!\n", GetName().ReadPtr());
1579                 return;
1580         }
1581
1582         // Register from callbacks
1583         KX_Scene* scene = GetScene();
1584         PHY_IPhysicsEnvironment* pe = scene->GetPhysicsEnvironment();
1585         PHY_IPhysicsController* spc = GetPhysicsController();
1586         // If we are the first to register on this physics controller
1587         if (pe->RequestCollisionCallback(spc)){
1588                 // If we are a sensor object
1589                 if (m_pClient_info->isSensor())
1590                         // Add sensor body to physics world
1591                         pe->AddSensor(spc);
1592         }
1593 }
1594 void KX_GameObject::RunCollisionCallbacks(KX_GameObject *collider, const MT_Vector3 &point, const MT_Vector3 &normal)
1595 {
1596 #ifdef WITH_PYTHON
1597         if (!m_collisionCallbacks || PyList_GET_SIZE(m_collisionCallbacks) == 0)
1598                 return;
1599
1600         PyObject *args[] = {collider->GetProxy(), PyObjectFrom(point), PyObjectFrom(normal)};
1601         RunPythonCallBackList(m_collisionCallbacks, args, 1, ARRAY_SIZE(args));
1602
1603         for (unsigned int i = 0; i < ARRAY_SIZE(args); ++i) {
1604                 Py_DECREF(args[i]);
1605         }
1606 #endif
1607 }
1608
1609 /* Suspend/ resume: for the dynamic behavior, there is a simple
1610  * method. For the residual motion, there is not. I wonder what the
1611  * correct solution is for Sumo. Remove from the motion-update tree?
1612  *
1613  * So far, only switch the physics and logic.
1614  * */
1615
1616 void KX_GameObject::Resume(void)
1617 {
1618         if (m_suspended) {
1619                 SCA_IObject::Resume();
1620                 // Child objects must be static, so we block changing to dynamic
1621                 if (GetPhysicsController() && !GetParent())
1622                         GetPhysicsController()->RestoreDynamics();
1623
1624                 m_suspended = false;
1625         }
1626 }
1627
1628 void KX_GameObject::Suspend()
1629 {
1630         if ((!m_ignore_activity_culling) && (!m_suspended)) {
1631                 SCA_IObject::Suspend();
1632                 if (GetPhysicsController())
1633                         GetPhysicsController()->SuspendDynamics();
1634                 m_suspended = true;
1635         }
1636 }
1637
1638 static void walk_children(SG_Node* node, CListValue* list, bool recursive)
1639 {
1640         if (!node)
1641                 return;
1642         NodeList& children = node->GetSGChildren();
1643
1644         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
1645         {
1646                 SG_Node* childnode = (*childit);
1647                 CValue* childobj = (CValue*)childnode->GetSGClientObject();
1648                 if (childobj != NULL) // This is a GameObject
1649                 {
1650                         // add to the list
1651                         list->Add(childobj->AddRef());
1652                 }
1653                 
1654                 // if the childobj is NULL then this may be an inverse parent link
1655                 // so a non recursive search should still look down this node.
1656                 if (recursive || childobj==NULL) {
1657                         walk_children(childnode, list, recursive);
1658                 }
1659         }
1660 }
1661
1662 CListValue* KX_GameObject::GetChildren()
1663 {
1664         CListValue* list = new CListValue();
1665         walk_children(GetSGNode(), list, 0); /* GetSGNode() is always valid or it would have raised an exception before this */
1666         return list;
1667 }
1668
1669 CListValue* KX_GameObject::GetChildrenRecursive()
1670 {
1671         CListValue* list = new CListValue();
1672         walk_children(GetSGNode(), list, 1);
1673         return list;
1674 }
1675
1676 KX_Scene* KX_GameObject::GetScene()
1677 {
1678         SG_Node* node = this->GetSGNode();
1679         if (node == NULL) {
1680                 // this happens for object in non active layers, rely on static scene then
1681                 return KX_GetActiveScene();
1682         }
1683         return static_cast<KX_Scene*>(node->GetSGClientInfo());
1684 }
1685
1686 /* ---------------------------------------------------------------------
1687  * Some stuff taken from the header
1688  * --------------------------------------------------------------------- */
1689 void KX_GameObject::Relink(CTR_Map<CTR_HashedPtr, void*> *map_parameter)
1690 {
1691         // we will relink the sensors and actuators that use object references
1692         // if the object is part of the replicated hierarchy, use the new
1693         // object reference instead
1694         SCA_SensorList& sensorlist = GetSensors();
1695         SCA_SensorList::iterator sit;
1696         for (sit=sensorlist.begin(); sit != sensorlist.end(); sit++)
1697         {
1698                 (*sit)->Relink(map_parameter);
1699         }
1700         SCA_ActuatorList& actuatorlist = GetActuators();
1701         SCA_ActuatorList::iterator ait;
1702         for (ait=actuatorlist.begin(); ait != actuatorlist.end(); ait++)
1703         {
1704                 (*ait)->Relink(map_parameter);
1705         }
1706 }
1707
1708 #ifdef USE_MATHUTILS
1709
1710 /* These require an SGNode */
1711 #define MATHUTILS_VEC_CB_POS_LOCAL 1
1712 #define MATHUTILS_VEC_CB_POS_GLOBAL 2
1713 #define MATHUTILS_VEC_CB_SCALE_LOCAL 3
1714 #define MATHUTILS_VEC_CB_SCALE_GLOBAL 4
1715 #define MATHUTILS_VEC_CB_INERTIA_LOCAL 5
1716 #define MATHUTILS_VEC_CB_OBJECT_COLOR 6
1717 #define MATHUTILS_VEC_CB_LINVEL_LOCAL 7
1718 #define MATHUTILS_VEC_CB_LINVEL_GLOBAL 8
1719 #define MATHUTILS_VEC_CB_ANGVEL_LOCAL 9
1720 #define MATHUTILS_VEC_CB_ANGVEL_GLOBAL 10
1721
1722 static unsigned char mathutils_kxgameob_vector_cb_index= -1; /* index for our callbacks */
1723
1724 static int mathutils_kxgameob_generic_check(BaseMathObject *bmo)
1725 {
1726         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1727         if (self == NULL)
1728                 return -1;
1729         
1730         return 0;
1731 }
1732
1733 static int mathutils_kxgameob_vector_get(BaseMathObject *bmo, int subtype)
1734 {
1735         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1736         if (self == NULL)
1737                 return -1;
1738
1739 #define PHYS_ERR(attr) PyErr_SetString(PyExc_AttributeError, "KX_GameObject." attr ", is missing a physics controller")
1740
1741         switch (subtype) {
1742                 case MATHUTILS_VEC_CB_POS_LOCAL:
1743                         self->NodeGetLocalPosition().getValue(bmo->data);
1744                         break;
1745                 case MATHUTILS_VEC_CB_POS_GLOBAL:
1746                         self->NodeGetWorldPosition().getValue(bmo->data);
1747                         break;
1748                 case MATHUTILS_VEC_CB_SCALE_LOCAL:
1749                         self->NodeGetLocalScaling().getValue(bmo->data);
1750                         break;
1751                 case MATHUTILS_VEC_CB_SCALE_GLOBAL:
1752                         self->NodeGetWorldScaling().getValue(bmo->data);
1753                         break;
1754                 case MATHUTILS_VEC_CB_INERTIA_LOCAL:
1755                         if (!self->GetPhysicsController()) return PHYS_ERR("localInertia"), -1;
1756                         self->GetPhysicsController()->GetLocalInertia().getValue(bmo->data);
1757                         break;
1758                 case MATHUTILS_VEC_CB_OBJECT_COLOR:
1759                         self->GetObjectColor().getValue(bmo->data);
1760                         break;
1761                 case MATHUTILS_VEC_CB_LINVEL_LOCAL:
1762                         if (!self->GetPhysicsController()) return PHYS_ERR("localLinearVelocity"), -1;
1763                         self->GetLinearVelocity(true).getValue(bmo->data);
1764                         break;
1765                 case MATHUTILS_VEC_CB_LINVEL_GLOBAL:
1766                         if (!self->GetPhysicsController()) return PHYS_ERR("worldLinearVelocity"), -1;
1767                         self->GetLinearVelocity(false).getValue(bmo->data);
1768                         break;
1769                 case MATHUTILS_VEC_CB_ANGVEL_LOCAL:
1770                         if (!self->GetPhysicsController()) return PHYS_ERR("localLinearVelocity"), -1;
1771                         self->GetAngularVelocity(true).getValue(bmo->data);
1772                         break;
1773                 case MATHUTILS_VEC_CB_ANGVEL_GLOBAL:
1774                         if (!self->GetPhysicsController()) return PHYS_ERR("worldLinearVelocity"), -1;
1775                         self->GetAngularVelocity(false).getValue(bmo->data);
1776                         break;
1777                         
1778         }
1779         
1780 #undef PHYS_ERR
1781         
1782         return 0;
1783 }
1784
1785 static int mathutils_kxgameob_vector_set(BaseMathObject *bmo, int subtype)
1786 {
1787         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1788         if (self == NULL)
1789                 return -1;
1790         
1791         switch (subtype) {
1792                 case MATHUTILS_VEC_CB_POS_LOCAL:
1793                         self->NodeSetLocalPosition(MT_Point3(bmo->data));
1794                         self->NodeUpdateGS(0.f);
1795                         break;
1796                 case MATHUTILS_VEC_CB_POS_GLOBAL:
1797                         self->NodeSetWorldPosition(MT_Point3(bmo->data));
1798                         self->NodeUpdateGS(0.f);
1799                         break;
1800                 case MATHUTILS_VEC_CB_SCALE_LOCAL:
1801                         self->NodeSetLocalScale(MT_Point3(bmo->data));
1802                         self->NodeUpdateGS(0.f);
1803                         break;
1804                 case MATHUTILS_VEC_CB_SCALE_GLOBAL:
1805                         PyErr_SetString(PyExc_AttributeError, "KX_GameObject.worldScale is read-only");
1806                         return -1;
1807                 case MATHUTILS_VEC_CB_INERTIA_LOCAL:
1808                         /* read only */
1809                         break;
1810                 case MATHUTILS_VEC_CB_OBJECT_COLOR:
1811                         self->SetObjectColor(MT_Vector4(bmo->data));
1812                         break;
1813                 case MATHUTILS_VEC_CB_LINVEL_LOCAL:
1814                         self->setLinearVelocity(MT_Point3(bmo->data),true);
1815                         break;
1816                 case MATHUTILS_VEC_CB_LINVEL_GLOBAL:
1817                         self->setLinearVelocity(MT_Point3(bmo->data),false);
1818                         break;
1819                 case MATHUTILS_VEC_CB_ANGVEL_LOCAL:
1820                         self->setAngularVelocity(MT_Point3(bmo->data),true);
1821                         break;
1822                 case MATHUTILS_VEC_CB_ANGVEL_GLOBAL:
1823                         self->setAngularVelocity(MT_Point3(bmo->data),false);
1824                         break;
1825         }
1826         
1827         return 0;
1828 }
1829
1830 static int mathutils_kxgameob_vector_get_index(BaseMathObject *bmo, int subtype, int index)
1831 {
1832         /* lazy, avoid repeteing the case statement */
1833         if (mathutils_kxgameob_vector_get(bmo, subtype) == -1)
1834                 return -1;
1835         return 0;
1836 }
1837
1838 static int mathutils_kxgameob_vector_set_index(BaseMathObject *bmo, int subtype, int index)
1839 {
1840         float f= bmo->data[index];
1841         
1842         /* lazy, avoid repeteing the case statement */
1843         if (mathutils_kxgameob_vector_get(bmo, subtype) == -1)
1844                 return -1;
1845         
1846         bmo->data[index] = f;
1847         return mathutils_kxgameob_vector_set(bmo, subtype);
1848 }
1849
1850 static Mathutils_Callback mathutils_kxgameob_vector_cb = {
1851         mathutils_kxgameob_generic_check,
1852         mathutils_kxgameob_vector_get,
1853         mathutils_kxgameob_vector_set,
1854         mathutils_kxgameob_vector_get_index,
1855         mathutils_kxgameob_vector_set_index
1856 };
1857
1858 /* Matrix */
1859 #define MATHUTILS_MAT_CB_ORI_LOCAL 1
1860 #define MATHUTILS_MAT_CB_ORI_GLOBAL 2
1861
1862 static unsigned char mathutils_kxgameob_matrix_cb_index= -1; /* index for our callbacks */
1863
1864 static int mathutils_kxgameob_matrix_get(BaseMathObject *bmo, int subtype)
1865 {
1866         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1867         if (self == NULL)
1868                 return -1;
1869
1870         switch (subtype) {
1871                 case MATHUTILS_MAT_CB_ORI_LOCAL:
1872                         self->NodeGetLocalOrientation().getValue3x3(bmo->data);
1873                         break;
1874                 case MATHUTILS_MAT_CB_ORI_GLOBAL:
1875                         self->NodeGetWorldOrientation().getValue3x3(bmo->data);
1876                         break;
1877         }
1878         
1879         return 0;
1880 }
1881
1882
1883 static int mathutils_kxgameob_matrix_set(BaseMathObject *bmo, int subtype)
1884 {
1885         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1886         if (self == NULL)
1887                 return -1;
1888         
1889         MT_Matrix3x3 mat3x3;
1890         switch (subtype) {
1891                 case MATHUTILS_MAT_CB_ORI_LOCAL:
1892                         mat3x3.setValue3x3(bmo->data);
1893                         self->NodeSetLocalOrientation(mat3x3);
1894                         self->NodeUpdateGS(0.f);
1895                         break;
1896                 case MATHUTILS_MAT_CB_ORI_GLOBAL:
1897                         mat3x3.setValue3x3(bmo->data);
1898                         self->NodeSetLocalOrientation(mat3x3);
1899                         self->NodeUpdateGS(0.f);
1900                         break;
1901         }
1902         
1903         return 0;
1904 }
1905
1906 static Mathutils_Callback mathutils_kxgameob_matrix_cb = {
1907         mathutils_kxgameob_generic_check,
1908         mathutils_kxgameob_matrix_get,
1909         mathutils_kxgameob_matrix_set,
1910         NULL,
1911         NULL
1912 };
1913
1914
1915 void KX_GameObject_Mathutils_Callback_Init(void)
1916 {
1917         // register mathutils callbacks, ok to run more than once.
1918         mathutils_kxgameob_vector_cb_index= Mathutils_RegisterCallback(&mathutils_kxgameob_vector_cb);
1919         mathutils_kxgameob_matrix_cb_index= Mathutils_RegisterCallback(&mathutils_kxgameob_matrix_cb);
1920 }
1921
1922 #endif // USE_MATHUTILS
1923
1924 #ifdef WITH_PYTHON
1925 /* ------- python stuff ---------------------------------------------------*/
1926 PyMethodDef KX_GameObject::Methods[] = {
1927         {"applyForce", (PyCFunction)    KX_GameObject::sPyApplyForce, METH_VARARGS},
1928         {"applyTorque", (PyCFunction)   KX_GameObject::sPyApplyTorque, METH_VARARGS},
1929         {"applyRotation", (PyCFunction) KX_GameObject::sPyApplyRotation, METH_VARARGS},
1930         {"applyMovement", (PyCFunction) KX_GameObject::sPyApplyMovement, METH_VARARGS},
1931         {"getLinearVelocity", (PyCFunction) KX_GameObject::sPyGetLinearVelocity, METH_VARARGS},
1932         {"setLinearVelocity", (PyCFunction) KX_GameObject::sPySetLinearVelocity, METH_VARARGS},
1933         {"getAngularVelocity", (PyCFunction) KX_GameObject::sPyGetAngularVelocity, METH_VARARGS},
1934         {"setAngularVelocity", (PyCFunction) KX_GameObject::sPySetAngularVelocity, METH_VARARGS},
1935         {"getVelocity", (PyCFunction) KX_GameObject::sPyGetVelocity, METH_VARARGS},
1936         {"setDamping", (PyCFunction) KX_GameObject::sPySetDamping, METH_VARARGS},
1937         {"getReactionForce", (PyCFunction) KX_GameObject::sPyGetReactionForce, METH_NOARGS},
1938         {"alignAxisToVect",(PyCFunction) KX_GameObject::sPyAlignAxisToVect, METH_VARARGS},
1939         {"getAxisVect",(PyCFunction) KX_GameObject::sPyGetAxisVect, METH_O},
1940         {"suspendDynamics", (PyCFunction)KX_GameObject::sPySuspendDynamics, METH_VARARGS},
1941         {"restoreDynamics", (PyCFunction)KX_GameObject::sPyRestoreDynamics,METH_NOARGS},
1942         {"enableRigidBody", (PyCFunction)KX_GameObject::sPyEnableRigidBody,METH_NOARGS},
1943         {"disableRigidBody", (PyCFunction)KX_GameObject::sPyDisableRigidBody,METH_NOARGS},
1944         {"applyImpulse", (PyCFunction) KX_GameObject::sPyApplyImpulse, METH_VARARGS},
1945         {"setCollisionMargin", (PyCFunction) KX_GameObject::sPySetCollisionMargin, METH_O},
1946         {"setParent", (PyCFunction)KX_GameObject::sPySetParent,METH_VARARGS},
1947         {"setVisible",(PyCFunction) KX_GameObject::sPySetVisible, METH_VARARGS},
1948         {"setOcclusion",(PyCFunction) KX_GameObject::sPySetOcclusion, METH_VARARGS},
1949         {"removeParent", (PyCFunction)KX_GameObject::sPyRemoveParent,METH_NOARGS},
1950
1951
1952         {"getPhysicsId", (PyCFunction)KX_GameObject::sPyGetPhysicsId,METH_NOARGS},
1953         {"getPropertyNames", (PyCFunction)KX_GameObject::sPyGetPropertyNames,METH_NOARGS},
1954         {"replaceMesh",(PyCFunction) KX_GameObject::sPyReplaceMesh, METH_VARARGS},
1955         {"endObject",(PyCFunction) KX_GameObject::sPyEndObject, METH_NOARGS},
1956         {"reinstancePhysicsMesh", (PyCFunction)KX_GameObject::sPyReinstancePhysicsMesh,METH_VARARGS},
1957         
1958         KX_PYMETHODTABLE(KX_GameObject, rayCastTo),
1959         KX_PYMETHODTABLE(KX_GameObject, rayCast),
1960         KX_PYMETHODTABLE_O(KX_GameObject, getDistanceTo),
1961         KX_PYMETHODTABLE_O(KX_GameObject, getVectTo),
1962         KX_PYMETHODTABLE(KX_GameObject, sendMessage),
1963         KX_PYMETHODTABLE(KX_GameObject, addDebugProperty),
1964
1965         KX_PYMETHODTABLE_KEYWORDS(KX_GameObject, playAction),
1966         KX_PYMETHODTABLE(KX_GameObject, stopAction),
1967         KX_PYMETHODTABLE(KX_GameObject, getActionFrame),
1968         KX_PYMETHODTABLE(KX_GameObject, getActionName),
1969         KX_PYMETHODTABLE(KX_GameObject, setActionFrame),
1970         KX_PYMETHODTABLE(KX_GameObject, isPlayingAction),
1971         
1972         // dict style access for props
1973         {"get",(PyCFunction) KX_GameObject::sPyget, METH_VARARGS},
1974         
1975         {NULL,NULL} //Sentinel
1976 };
1977
1978 PyAttributeDef KX_GameObject::Attributes[] = {
1979         KX_PYATTRIBUTE_INT_RO("currentLodLevel", KX_GameObject, m_currentLodLevel),
1980         KX_PYATTRIBUTE_RO_FUNCTION("name",              KX_GameObject, pyattr_get_name),
1981         KX_PYATTRIBUTE_RO_FUNCTION("parent",    KX_GameObject, pyattr_get_parent),
1982         KX_PYATTRIBUTE_RO_FUNCTION("groupMembers",      KX_GameObject, pyattr_get_group_members),
1983         KX_PYATTRIBUTE_RO_FUNCTION("groupObject",       KX_GameObject, pyattr_get_group_object),
1984         KX_PYATTRIBUTE_RO_FUNCTION("scene",             KX_GameObject, pyattr_get_scene),
1985         KX_PYATTRIBUTE_RO_FUNCTION("life",              KX_GameObject, pyattr_get_life),
1986         KX_PYATTRIBUTE_RW_FUNCTION("mass",              KX_GameObject, pyattr_get_mass,         pyattr_set_mass),
1987         KX_PYATTRIBUTE_RO_FUNCTION("isSuspendDynamics",         KX_GameObject, pyattr_get_is_suspend_dynamics),
1988         KX_PYATTRIBUTE_RW_FUNCTION("linVelocityMin",            KX_GameObject, pyattr_get_lin_vel_min, pyattr_set_lin_vel_min),
1989         KX_PYATTRIBUTE_RW_FUNCTION("linVelocityMax",            KX_GameObject, pyattr_get_lin_vel_max, pyattr_set_lin_vel_max),
1990         KX_PYATTRIBUTE_RW_FUNCTION("angularVelocityMin", KX_GameObject, pyattr_get_ang_vel_min, pyattr_set_ang_vel_min),
1991         KX_PYATTRIBUTE_RW_FUNCTION("angularVelocityMax", KX_GameObject, pyattr_get_ang_vel_max, pyattr_set_ang_vel_max),
1992         KX_PYATTRIBUTE_RW_FUNCTION("visible",   KX_GameObject, pyattr_get_visible,      pyattr_set_visible),
1993         KX_PYATTRIBUTE_RW_FUNCTION("record_animation",  KX_GameObject, pyattr_get_record_animation,     pyattr_set_record_animation),
1994         KX_PYATTRIBUTE_BOOL_RW    ("occlusion", KX_GameObject, m_bOccluder),
1995         KX_PYATTRIBUTE_RW_FUNCTION("position",  KX_GameObject, pyattr_get_worldPosition,        pyattr_set_localPosition),
1996         KX_PYATTRIBUTE_RO_FUNCTION("localInertia",      KX_GameObject, pyattr_get_localInertia),
1997         KX_PYATTRIBUTE_RW_FUNCTION("orientation",KX_GameObject,pyattr_get_worldOrientation,pyattr_set_localOrientation),
1998         KX_PYATTRIBUTE_RW_FUNCTION("scaling",   KX_GameObject, pyattr_get_worldScaling, pyattr_set_localScaling),
1999         KX_PYATTRIBUTE_RW_FUNCTION("timeOffset",KX_GameObject, pyattr_get_timeOffset,pyattr_set_timeOffset),
2000         KX_PYATTRIBUTE_RW_FUNCTION("collisionCallbacks",                KX_GameObject, pyattr_get_collisionCallbacks,   pyattr_set_collisionCallbacks),
2001         KX_PYATTRIBUTE_RW_FUNCTION("collisionGroup",                    KX_GameObject, pyattr_get_collisionGroup, pyattr_set_collisionGroup),
2002         KX_PYATTRIBUTE_RW_FUNCTION("collisionMask",                             KX_GameObject, pyattr_get_collisionMask, pyattr_set_collisionMask),
2003         KX_PYATTRIBUTE_RW_FUNCTION("state",             KX_GameObject, pyattr_get_state,        pyattr_set_state),
2004         KX_PYATTRIBUTE_RO_FUNCTION("meshes",    KX_GameObject, pyattr_get_meshes),
2005         KX_PYATTRIBUTE_RW_FUNCTION("localOrientation",KX_GameObject,pyattr_get_localOrientation,pyattr_set_localOrientation),
2006         KX_PYATTRIBUTE_RW_FUNCTION("worldOrientation",KX_GameObject,pyattr_get_worldOrientation,pyattr_set_worldOrientation),
2007         KX_PYATTRIBUTE_RW_FUNCTION("localPosition",     KX_GameObject, pyattr_get_localPosition,        pyattr_set_localPosition),
2008         KX_PYATTRIBUTE_RW_FUNCTION("worldPosition",     KX_GameObject, pyattr_get_worldPosition,    pyattr_set_worldPosition),
2009         KX_PYATTRIBUTE_RW_FUNCTION("localScale",        KX_GameObject, pyattr_get_localScaling, pyattr_set_localScaling),
2010         KX_PYATTRIBUTE_RW_FUNCTION("worldScale",        KX_GameObject, pyattr_get_worldScaling, pyattr_set_worldScaling),
2011         KX_PYATTRIBUTE_RW_FUNCTION("localTransform",            KX_GameObject, pyattr_get_localTransform, pyattr_set_localTransform),
2012         KX_PYATTRIBUTE_RW_FUNCTION("worldTransform",            KX_GameObject, pyattr_get_worldTransform, pyattr_set_worldTransform),
2013         KX_PYATTRIBUTE_RW_FUNCTION("linearVelocity", KX_GameObject, pyattr_get_localLinearVelocity, pyattr_set_worldLinearVelocity),
2014         KX_PYATTRIBUTE_RW_FUNCTION("localLinearVelocity", KX_GameObject, pyattr_get_localLinearVelocity, pyattr_set_localLinearVelocity),
2015         KX_PYATTRIBUTE_RW_FUNCTION("worldLinearVelocity", KX_GameObject, pyattr_get_worldLinearVelocity, pyattr_set_worldLinearVelocity),
2016         KX_PYATTRIBUTE_RW_FUNCTION("angularVelocity", KX_GameObject, pyattr_get_localAngularVelocity, pyattr_set_worldAngularVelocity),
2017         KX_PYATTRIBUTE_RW_FUNCTION("localAngularVelocity", KX_GameObject, pyattr_get_localAngularVelocity, pyattr_set_localAngularVelocity),
2018         KX_PYATTRIBUTE_RW_FUNCTION("worldAngularVelocity", KX_GameObject, pyattr_get_worldAngularVelocity, pyattr_set_worldAngularVelocity),
2019         KX_PYATTRIBUTE_RW_FUNCTION("linearDamping", KX_GameObject, pyattr_get_linearDamping, pyattr_set_linearDamping),
2020         KX_PYATTRIBUTE_RW_FUNCTION("angularDamping", KX_GameObject, pyattr_get_angularDamping, pyattr_set_angularDamping),
2021         KX_PYATTRIBUTE_RO_FUNCTION("children",  KX_GameObject, pyattr_get_children),
2022         KX_PYATTRIBUTE_RO_FUNCTION("childrenRecursive", KX_GameObject, pyattr_get_children_recursive),
2023         KX_PYATTRIBUTE_RO_FUNCTION("attrDict",  KX_GameObject, pyattr_get_attrDict),
2024         KX_PYATTRIBUTE_RW_FUNCTION("color", KX_GameObject, pyattr_get_obcolor, pyattr_set_obcolor),
2025         KX_PYATTRIBUTE_RW_FUNCTION("debug",     KX_GameObject, pyattr_get_debug, pyattr_set_debug),
2026         KX_PYATTRIBUTE_RW_FUNCTION("debugRecursive",    KX_GameObject, pyattr_get_debugRecursive, pyattr_set_debugRecursive),
2027         
2028         /* experimental, don't rely on these yet */
2029         KX_PYATTRIBUTE_RO_FUNCTION("sensors",           KX_GameObject, pyattr_get_sensors),
2030         KX_PYATTRIBUTE_RO_FUNCTION("controllers",       KX_GameObject, pyattr_get_controllers),
2031         KX_PYATTRIBUTE_RO_FUNCTION("actuators",         KX_GameObject, pyattr_get_actuators),
2032         {NULL} //Sentinel
2033 };
2034
2035 PyObject *KX_GameObject::PyReplaceMesh(PyObject *args)
2036 {
2037         KX_Scene *scene = KX_GetActiveScene();
2038         SCA_LogicManager *logicmgr = GetScene()->GetLogicManager();
2039
2040         PyObject *value;
2041         int use_gfx= 1, use_phys= 0;
2042         RAS_MeshObject *new_mesh;
2043         
2044         if (!PyArg_ParseTuple(args,"O|ii:replaceMesh", &value, &use_gfx, &use_phys))
2045                 return NULL;
2046         
2047         if (!ConvertPythonToMesh(logicmgr, value, &new_mesh, false, "gameOb.replaceMesh(value): KX_GameObject"))
2048                 return NULL;
2049         
2050         scene->ReplaceMesh(this, new_mesh, (bool)use_gfx, (bool)use_phys);
2051         Py_RETURN_NONE;
2052 }
2053
2054 PyObject *KX_GameObject::PyEndObject()
2055 {
2056         KX_Scene* scene = GetScene();
2057         
2058         scene->DelayedRemoveObject(this);
2059         
2060         Py_RETURN_NONE;
2061
2062 }
2063
2064 PyObject *KX_GameObject::PyReinstancePhysicsMesh(PyObject *args)
2065 {
2066         KX_GameObject *gameobj= NULL;
2067         RAS_MeshObject *mesh= NULL;
2068         SCA_LogicManager *logicmgr = GetScene()->GetLogicManager();
2069         
2070         PyObject *gameobj_py= NULL;
2071         PyObject *mesh_py= NULL;
2072
2073         if (    !PyArg_ParseTuple(args,"|OO:reinstancePhysicsMesh",&gameobj_py, &mesh_py) ||
2074                         (gameobj_py && !ConvertPythonToGameObject(logicmgr, gameobj_py, &gameobj, true, "gameOb.reinstancePhysicsMesh(obj, mesh): KX_GameObject")) || 
2075                         (mesh_py && !ConvertPythonToMesh(logicmgr, mesh_py, &mesh, true, "gameOb.reinstancePhysicsMesh(obj, mesh): KX_GameObject"))
2076                 ) {
2077                 return NULL;
2078         }
2079
2080         /* gameobj and mesh can be NULL */
2081         if (GetPhysicsController() && GetPhysicsController()->ReinstancePhysicsShape(gameobj, mesh))
2082                 Py_RETURN_TRUE;
2083
2084         Py_RETURN_FALSE;
2085 }
2086
2087 static PyObject *Map_GetItem(PyObject *self_v, PyObject *item)
2088 {
2089         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
2090         const char *attr_str= _PyUnicode_AsString(item);
2091         CValue* resultattr;
2092         PyObject *pyconvert;
2093         
2094         if (self == NULL) {
2095                 PyErr_SetString(PyExc_SystemError, "val = gameOb[key]: KX_GameObject, " BGE_PROXY_ERROR_MSG);
2096                 return NULL;
2097         }
2098         
2099         /* first see if the attributes a string and try get the cvalue attribute */
2100         if (attr_str && (resultattr=self->GetProperty(attr_str))) {
2101                 pyconvert = resultattr->ConvertValueToPython();
2102                 return pyconvert ? pyconvert:resultattr->GetProxy();
2103         }
2104         /* no CValue attribute, try get the python only m_attr_dict attribute */
2105         else if (self->m_attr_dict && (pyconvert=PyDict_GetItem(self->m_attr_dict, item))) {
2106                 
2107                 if (attr_str)
2108                         PyErr_Clear();
2109                 Py_INCREF(pyconvert);
2110                 return pyconvert;
2111         }
2112         else {
2113                 if (attr_str)   PyErr_Format(PyExc_KeyError, "value = gameOb[key]: KX_GameObject, key \"%s\" does not exist", attr_str);
2114                 else                    PyErr_SetString(PyExc_KeyError, "value = gameOb[key]: KX_GameObject, key does not exist");
2115                 return NULL;
2116         }
2117                 
2118 }
2119
2120
2121 static int Map_SetItem(PyObject *self_v, PyObject *key, PyObject *val)
2122 {
2123         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
2124         const char *attr_str= _PyUnicode_AsString(key);
2125         if (attr_str==NULL)
2126                 PyErr_Clear();
2127         
2128         if (self == NULL) {
2129                 PyErr_SetString(PyExc_SystemError, "gameOb[key] = value: KX_GameObject, " BGE_PROXY_ERROR_MSG);
2130                 return -1;
2131         }
2132         
2133         if (val==NULL) { /* del ob["key"] */
2134                 int del= 0;
2135                 
2136                 /* try remove both just in case */
2137                 if (attr_str)
2138                         del |= (self->RemoveProperty(attr_str)==true) ? 1:0;
2139                 
2140                 if (self->m_attr_dict)
2141                         del |= (PyDict_DelItem(self->m_attr_dict, key)==0) ? 1:0;
2142                 
2143                 if (del==0) {
2144                         if (attr_str)   PyErr_Format(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key \"%s\" could not be set", attr_str);
2145                         else                    PyErr_SetString(PyExc_KeyError, "del gameOb[key]: KX_GameObject, key could not be deleted");
2146                         return -1;
2147                 }
2148                 else if (self->m_attr_dict) {
2149                         PyErr_Clear(); /* PyDict_DelItem sets an error when it fails */
2150                 }
2151         }
2152         else { /* ob["key"] = value */
2153                 bool set = false;
2154                 
2155                 /* as CValue */
2156                 if (attr_str && PyObject_TypeCheck(val, &PyObjectPlus::Type)==0) /* don't allow GameObjects for eg to be assigned to CValue props */
2157                 {
2158                         CValue *vallie = self->ConvertPythonToValue(val, false, "gameOb[key] = value: ");
2159                         
2160                         if (vallie) {
2161                                 CValue* oldprop = self->GetProperty(attr_str);
2162                                 
2163                                 if (oldprop)
2164                                         oldprop->SetValue(vallie);
2165                                 else
2166                                         self->SetProperty(attr_str, vallie);
2167                                 
2168                                 vallie->Release();
2169                                 set = true;
2170                                 
2171                                 /* try remove dict value to avoid double ups */
2172                                 if (self->m_attr_dict) {
2173                                         if (PyDict_DelItem(self->m_attr_dict, key) != 0)
2174                                                 PyErr_Clear();
2175                                 }
2176                         }
2177                         else if (PyErr_Occurred()) {
2178                                 return -1;
2179                         }
2180                 }
2181                 
2182                 if (set == false) {
2183                         if (self->m_attr_dict==NULL) /* lazy init */
2184                                 self->m_attr_dict= PyDict_New();
2185                         
2186                         
2187                         if (PyDict_SetItem(self->m_attr_dict, key, val)==0)
2188                         {
2189                                 if (attr_str)
2190                                         self->RemoveProperty(attr_str); /* overwrite the CValue if it exists */
2191                                 set = true;
2192                         }
2193                         else {
2194                                 if (attr_str)   PyErr_Format(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key \"%s\" not be added to internal dictionary", attr_str);
2195                                 else                    PyErr_SetString(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key not be added to internal dictionary");
2196                         }
2197                 }
2198                 
2199                 if (set == false) {
2200                         return -1; /* pythons error value */
2201                 }
2202                 
2203         }
2204         
2205         return 0; /* success */
2206 }
2207
2208 static int Seq_Contains(PyObject *self_v, PyObject *value)
2209 {
2210         KX_GameObject* self = static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
2211         
2212         if (self == NULL) {
2213                 PyErr_SetString(PyExc_SystemError, "val in gameOb: KX_GameObject, " BGE_PROXY_ERROR_MSG);
2214                 return -1;
2215         }
2216         
2217         if (PyUnicode_Check(value) && self->GetProperty(_PyUnicode_AsString(value)))
2218                 return 1;
2219         
2220         if (self->m_attr_dict && PyDict_GetItem(self->m_attr_dict, value))
2221                 return 1;
2222         
2223         return 0;
2224 }
2225
2226
2227 PyMappingMethods KX_GameObject::Mapping = {
2228         (lenfunc)NULL                                   ,                       /*inquiry mp_length */
2229         (binaryfunc)Map_GetItem,                /*binaryfunc mp_subscript */
2230         (objobjargproc)Map_SetItem,     /*objobjargproc mp_ass_subscript */
2231 };
2232
2233 PySequenceMethods KX_GameObject::Sequence = {
2234         NULL,           /* Cant set the len otherwise it can evaluate as false */
2235         NULL,           /* sq_concat */
2236         NULL,           /* sq_repeat */
2237         NULL,           /* sq_item */
2238         NULL,           /* sq_slice */
2239         NULL,           /* sq_ass_item */
2240         NULL,           /* sq_ass_slice */
2241         (objobjproc)Seq_Contains,       /* sq_contains */
2242         (binaryfunc) NULL, /* sq_inplace_concat */
2243         (ssizeargfunc) NULL, /* sq_inplace_repeat */
2244 };
2245
2246 PyTypeObject KX_GameObject::Type = {
2247         PyVarObject_HEAD_INIT(NULL, 0)
2248         "KX_GameObject",
2249         sizeof(PyObjectPlus_Proxy),
2250         0,
2251         py_base_dealloc,
2252         0,
2253         0,
2254         0,
2255         0,
2256         py_base_repr,
2257         0,
2258         &Sequence,
2259         &Mapping,
2260         0,0,0,
2261         NULL,
2262         NULL,
2263         0,
2264         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
2265         0,0,0,0,0,0,0,
2266         Methods,
2267         0,
2268         0,
2269         &SCA_IObject::Type,
2270         0,0,0,0,0,0,
2271         py_base_new
2272 };
2273
2274 PyObject *KX_GameObject::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2275 {
2276         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2277         return PyUnicode_From_STR_String(self->GetName());
2278 }
2279
2280 PyObject *KX_GameObject::pyattr_get_parent(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2281 {
2282         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2283         KX_GameObject* parent = self->GetParent();
2284         if (parent) {
2285                 return parent->GetProxy();
2286         }
2287         Py_RETURN_NONE;
2288 }
2289
2290 PyObject *KX_GameObject::pyattr_get_group_members(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2291 {
2292         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2293         CListValue* instances = self->GetInstanceObjects();
2294         if (instances) {
2295                 return instances->GetProxy();
2296         }
2297         Py_RETURN_NONE;
2298 }
2299
2300 PyObject* KX_GameObject::pyattr_get_collisionCallbacks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2301 {
2302         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2303
2304         // Only objects with a physics controller should have collision callbacks
2305         if (!self->GetPhysicsController()) {
2306                 PyErr_SetString(PyExc_AttributeError, "KX_GameObject.collisionCallbacks: attribute only available for objects with collisions enabled");
2307                 return NULL;
2308         }
2309
2310         // Return the existing callbacks
2311         if (self->m_collisionCallbacks == NULL)
2312         {
2313                 self->m_collisionCallbacks = PyList_New(0);
2314                 // Subscribe to collision update from KX_TouchManager
2315                 self->RegisterCollisionCallbacks();
2316         }
2317         Py_INCREF(self->m_collisionCallbacks);
2318         return self->m_collisionCallbacks;
2319 }
2320
2321 int KX_GameObject::pyattr_set_collisionCallbacks(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2322 {
2323         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2324
2325         // Only objects with a physics controller should have collision callbacks
2326         if (!self->GetPhysicsController()) {
2327                 PyErr_SetString(PyExc_AttributeError, "KX_GameObject.collisionCallbacks: attribute only available for objects with collisions enabled");
2328                 return PY_SET_ATTR_FAIL;
2329         }
2330
2331         if (!PyList_CheckExact(value))
2332         {
2333                 PyErr_SetString(PyExc_ValueError, "Expected a list");
2334                 return PY_SET_ATTR_FAIL;
2335         }
2336
2337         if (self->m_collisionCallbacks == NULL) {
2338                 self->RegisterCollisionCallbacks();
2339         } else {
2340                 Py_DECREF(self->m_collisionCallbacks);
2341         }
2342
2343         Py_INCREF(value);
2344
2345
2346         self->m_collisionCallbacks = value;
2347
2348         return PY_SET_ATTR_SUCCESS;
2349 }
2350
2351 PyObject *KX_GameObject::pyattr_get_collisionGroup(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2352 {
2353         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2354         return PyLong_FromLong(self->GetUserCollisionGroup());
2355 }
2356
2357 int KX_GameObject::pyattr_set_collisionGroup(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2358 {
2359         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2360         int val = PyLong_AsLong(value);
2361
2362         if (val == -1 && PyErr_Occurred()) {
2363                 PyErr_SetString(PyExc_TypeError, "gameOb.collisionGroup = int: KX_GameObject, expected an int bit field");
2364                 return PY_SET_ATTR_FAIL;
2365         }
2366
2367         if (val == 0 || val & ~((1 << OB_MAX_COL_MASKS) - 1)) {
2368                 PyErr_Format(PyExc_AttributeError, "gameOb.collisionGroup = int: KX_GameObject, expected a int bit field, 0 < group < %i", (1 << OB_MAX_COL_MASKS));
2369                 return PY_SET_ATTR_FAIL;
2370         }
2371
2372         self->SetUserCollisionGroup(val);
2373         return PY_SET_ATTR_SUCCESS;
2374 }
2375
2376 PyObject *KX_GameObject::pyattr_get_collisionMask(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2377 {
2378         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2379         return PyLong_FromLong(self->GetUserCollisionMask());
2380 }
2381
2382 int KX_GameObject::pyattr_set_collisionMask(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2383 {
2384         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2385         int val = PyLong_AsLong(value);
2386
2387         if (val == -1 && PyErr_Occurred()) {
2388                 PyErr_SetString(PyExc_TypeError, "gameOb.collisionMask = int: KX_GameObject, expected an int bit field");
2389                 return PY_SET_ATTR_FAIL;
2390         }
2391
2392         if (val == 0 || val & ~((1 << OB_MAX_COL_MASKS) - 1)) {
2393                 PyErr_Format(PyExc_AttributeError, "gameOb.collisionMask = int: KX_GameObject, expected a int bit field, 0 < mask < %i", (1 << OB_MAX_COL_MASKS));
2394                 return PY_SET_ATTR_FAIL;
2395         }
2396
2397         self->SetUserCollisionMask(val);
2398         return PY_SET_ATTR_SUCCESS;
2399 }
2400
2401 PyObject* KX_GameObject::pyattr_get_scene(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2402 {
2403         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
2404         KX_Scene *scene = self->GetScene();
2405         if (scene) {
2406                 return scene->GetProxy();
2407         }
2408         Py_RETURN_NONE;
2409 }
2410
2411 PyObject *KX_GameObject::pyattr_get_group_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2412 {
2413         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2414         KX_GameObject* pivot = self->GetDupliGroupObject();
2415         if (pivot) {
2416                 return pivot->GetProxy();
2417         }
2418         Py_RETURN_NONE;
2419 }
2420
2421 PyObject *KX_GameObject::pyattr_get_life(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2422 {
2423         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2424
2425         CValue *life = self->GetProperty("::timebomb");
2426         if (life)
2427                 // this convert the timebomb seconds to frames, hard coded 50.0f (assuming 50fps)
2428                 // value hardcoded in KX_Scene::AddReplicaObject()
2429                 return PyFloat_FromDouble(life->GetNumber() * 50.0);
2430         else
2431                 Py_RETURN_NONE;
2432 }
2433
2434 PyObject *KX_GameObject::pyattr_get_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2435 {
2436         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2437         PHY_IPhysicsController *spc = self->GetPhysicsController();
2438         return PyFloat_FromDouble(spc ? spc->GetMass() : 0.0f);
2439 }
2440
2441 int KX_GameObject::pyattr_set_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2442 {
2443         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2444         PHY_IPhysicsController *spc = self->GetPhysicsController();
2445         MT_Scalar val = PyFloat_AsDouble(value);
2446         if (val < 0.0f) { /* also accounts for non float */
2447                 PyErr_SetString(PyExc_AttributeError, "gameOb.mass = float: KX_GameObject, expected a float zero or above");
2448                 return PY_SET_ATTR_FAIL;
2449         }
2450
2451         if (spc)
2452                 spc->SetMass(val);
2453
2454         return PY_SET_ATTR_SUCCESS;
2455 }
2456
2457 PyObject *KX_GameObject::pyattr_get_is_suspend_dynamics(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2458 {
2459         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2460
2461         // Only objects with a physics controller can be suspended
2462         if (!self->GetPhysicsController()) {
2463                 PyErr_SetString(PyExc_AttributeError, "This object has not Physics Controller");
2464                 return NULL;
2465         }
2466
2467         return PyBool_FromLong(self->IsDynamicsSuspended());
2468 }
2469
2470 PyObject *KX_GameObject::pyattr_get_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2471 {
2472         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2473         PHY_IPhysicsController *spc = self->GetPhysicsController();
2474         return PyFloat_FromDouble(spc ? spc->GetLinVelocityMin() : 0.0f);
2475 }
2476
2477 int KX_GameObject::pyattr_set_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2478 {
2479         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2480         PHY_IPhysicsController *spc = self->GetPhysicsController();
2481         MT_Scalar val = PyFloat_AsDouble(value);
2482         if (val < 0.0f) { /* also accounts for non float */
2483                 PyErr_SetString(PyExc_AttributeError, "gameOb.linVelocityMin = float: KX_GameObject, expected a float zero or above");
2484                 return PY_SET_ATTR_FAIL;
2485         }
2486
2487         if (spc)
2488                 spc->SetLinVelocityMin(val);
2489
2490         return PY_SET_ATTR_SUCCESS;
2491 }
2492
2493 PyObject *KX_GameObject::pyattr_get_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2494 {
2495         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2496         PHY_IPhysicsController *spc = self->GetPhysicsController();
2497         return PyFloat_FromDouble(spc ? spc->GetLinVelocityMax() : 0.0f);
2498 }
2499
2500 int KX_GameObject::pyattr_set_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2501 {
2502         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2503         PHY_IPhysicsController *spc = self->GetPhysicsController();
2504         MT_Scalar val = PyFloat_AsDouble(value);
2505         if (val < 0.0f) { /* also accounts for non float */
2506                 PyErr_SetString(PyExc_AttributeError, "gameOb.linVelocityMax = float: KX_GameObject, expected a float zero or above");
2507                 return PY_SET_ATTR_FAIL;
2508         }
2509
2510         if (spc)
2511                 spc->SetLinVelocityMax(val);
2512
2513         return PY_SET_ATTR_SUCCESS;
2514 }
2515
2516 PyObject *KX_GameObject::pyattr_get_ang_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2517 {
2518         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
2519         PHY_IPhysicsController *spc = self->GetPhysicsController();
2520         return PyFloat_FromDouble(spc ? spc->GetAngularVelocityMin() : 0.0f);
2521 }
2522
2523 int KX_GameObject::pyattr_set_ang_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2524 {
2525         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
2526         PHY_IPhysicsController *spc = self->GetPhysicsController();
2527         MT_Scalar val = PyFloat_AsDouble(value);
2528         if (val < 0.0f) { /* also accounts for non float */
2529                 PyErr_SetString(PyExc_AttributeError,
2530                                 "gameOb.angularVelocityMin = float: KX_GameObject, expected a nonnegative float");
2531                 return PY_SET_ATTR_FAIL;
2532         }
2533
2534         if (spc)
2535                 spc->SetAngularVelocityMin(val);
2536
2537         return PY_SET_ATTR_SUCCESS;
2538 }
2539
2540 PyObject *KX_GameObject::pyattr_get_ang_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2541 {
2542         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
2543         PHY_IPhysicsController *spc = self->GetPhysicsController();
2544         return PyFloat_FromDouble(spc ? spc->GetAngularVelocityMax() : 0.0f);
2545 }
2546
2547 int KX_GameObject::pyattr_set_ang_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2548 {
2549         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
2550         PHY_IPhysicsController *spc = self->GetPhysicsController();
2551         MT_Scalar val = PyFloat_AsDouble(value);
2552         if (val < 0.0f) { /* also accounts for non float */
2553                 PyErr_SetString(PyExc_AttributeError,
2554                                 "gameOb.angularVelocityMax = float: KX_GameObject, expected a nonnegative float");
2555                 return PY_SET_ATTR_FAIL;
2556         }
2557
2558         if (spc)
2559                 spc->SetAngularVelocityMax(val);
2560
2561         return PY_SET_ATTR_SUCCESS;
2562 }
2563
2564
2565 PyObject *KX_GameObject::pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2566 {
2567         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2568         return PyBool_FromLong(self->GetVisible());
2569 }
2570
2571 int KX_GameObject::pyattr_set_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2572 {
2573         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2574         int param = PyObject_IsTrue( value );
2575         if (param == -1) {
2576                 PyErr_SetString(PyExc_AttributeError, "gameOb.visible = bool: KX_GameObject, expected True or False");
2577                 return PY_SET_ATTR_FAIL;
2578         }
2579
2580         self->SetVisible(param, false);
2581         self->UpdateBuckets(false);
2582         return PY_SET_ATTR_SUCCESS;
2583 }
2584
2585 PyObject *KX_GameObject::pyattr_get_record_animation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2586 {
2587         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2588         return PyBool_FromLong(self->IsRecordAnimation());
2589 }
2590
2591 int KX_GameObject::pyattr_set_record_animation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2592 {
2593         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2594         int param = PyObject_IsTrue(value);
2595         if (param == -1) {
2596                 PyErr_SetString(PyExc_AttributeError, "gameOb.record_animation = bool: KX_GameObject, expected boolean");
2597                 return PY_SET_ATTR_FAIL;
2598         }
2599
2600         self->SetRecordAnimation(param);
2601
2602         return PY_SET_ATTR_SUCCESS;
2603 }
2604
2605
2606
2607 PyObject *KX_GameObject::pyattr_get_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2608 {
2609 #ifdef USE_MATHUTILS
2610         return Vector_CreatePyObject_cb(
2611                 BGE_PROXY_FROM_REF_BORROW(self_v), 3,
2612                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_POS_GLOBAL);
2613 #else
2614         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2615         return PyObjectFrom(self->NodeGetWorldPosition());
2616 #endif
2617 }
2618
2619 int KX_GameObject::pyattr_set_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2620 {
2621         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2622         MT_Point3 pos;
2623         if (!PyVecTo(value, pos))
2624                 return PY_SET_ATTR_FAIL;
2625         
2626         self->NodeSetWorldPosition(pos);
2627         self->NodeUpdateGS(0.f);
2628         return PY_SET_ATTR_SUCCESS;
2629 }
2630
2631 PyObject *KX_GameObject::pyattr_get_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2632 {
2633 #ifdef USE_MATHUTILS
2634         return Vector_CreatePyObject_cb(
2635                 BGE_PROXY_FROM_REF_BORROW(self_v), 3,
2636                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_POS_LOCAL);
2637 #else
2638         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2639         return PyObjectFrom(self->NodeGetLocalPosition());
2640 #endif
2641 }
2642
2643 int KX_GameObject::pyattr_set_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2644 {
2645         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2646         MT_Point3 pos;
2647         if (!PyVecTo(value, pos))
2648                 return PY_SET_ATTR_FAIL;
2649         
2650         self->NodeSetLocalPosition(pos);
2651         self->NodeUpdateGS(0.f);
2652         return PY_SET_ATTR_SUCCESS;
2653 }
2654
2655 PyObject *KX_GameObject::pyattr_get_localInertia(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2656 {
2657 #ifdef USE_MATHUTILS
2658         return Vector_CreatePyObject_cb(
2659                 BGE_PROXY_FROM_REF_BORROW(self_v), 3,
2660                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_INERTIA_LOCAL);
2661 #else
2662         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2663         if (self->GetPhysicsController1())
2664                 return PyObjectFrom(self->GetPhysicsController1()->GetLocalInertia());
2665         return Py_BuildValue("fff", 0.0f, 0.0f, 0.0f);
2666 #endif
2667 }
2668
2669 PyObject *KX_GameObject::pyattr_get_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2670 {
2671 #ifdef USE_MATHUTILS
2672         return Matrix_CreatePyObject_cb(
2673                 BGE_PROXY_FROM_REF_BORROW(self_v), 3, 3,
2674                 mathutils_kxgameob_matrix_cb_index, MATHUTILS_MAT_CB_ORI_GLOBAL);
2675 #else
2676         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2677         return PyObjectFrom(self->NodeGetWorldOrientation());
2678 #endif
2679 }
2680
2681 int KX_GameObject::pyattr_set_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2682 {
2683         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2684         
2685         /* if value is not a sequence PyOrientationTo makes an error */
2686         MT_Matrix3x3 rot;
2687         if (!PyOrientationTo(value, rot, "gameOb.worldOrientation = sequence: KX_GameObject, "))
2688                 return PY_SET_ATTR_FAIL;
2689
2690         self->NodeSetGlobalOrientation(rot);
2691         
2692         self->NodeUpdateGS(0.f);
2693         return PY_SET_ATTR_SUCCESS;
2694 }
2695
2696 PyObject *KX_GameObject::pyattr_get_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2697 {
2698 #ifdef USE_MATHUTILS
2699         return Matrix_CreatePyObject_cb(
2700                 BGE_PROXY_FROM_REF_BORROW(self_v), 3, 3,
2701                 mathutils_kxgameob_matrix_cb_index, MATHUTILS_MAT_CB_ORI_LOCAL);
2702 #else
2703         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2704         return PyObjectFrom(self->NodeGetLocalOrientation());
2705 #endif
2706 }
2707
2708 int KX_GameObject::pyattr_set_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2709 {
2710         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2711         
2712         /* if value is not a sequence PyOrientationTo makes an error */
2713         MT_Matrix3x3 rot;
2714         if (!PyOrientationTo(value, rot, "gameOb.localOrientation = sequence: KX_GameObject, "))
2715                 return PY_SET_ATTR_FAIL;
2716
2717         self->NodeSetLocalOrientation(rot);
2718         self->NodeUpdateGS(0.f);
2719         return PY_SET_ATTR_SUCCESS;
2720 }
2721
2722 PyObject *KX_GameObject::pyattr_get_worldScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2723 {
2724 #ifdef USE_MATHUTILS
2725         return Vector_CreatePyObject_cb(
2726                 BGE_PROXY_FROM_REF_BORROW(self_v), 3,
2727                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_SCALE_GLOBAL);
2728 #else
2729         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2730         return PyObjectFrom(self->NodeGetWorldScaling());
2731 #endif
2732 }
2733
2734 int KX_GameObject::pyattr_set_worldScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2735 {
2736         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2737         MT_Vector3 scale;
2738         if (!PyVecTo(value, scale))
2739                 return PY_SET_ATTR_FAIL;
2740
2741         self->NodeSetWorldScale(scale);
2742         self->NodeUpdateGS(0.f);
2743         return PY_SET_ATTR_SUCCESS;
2744 }
2745
2746 PyObject *KX_GameObject::pyattr_get_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2747 {
2748 #ifdef USE_MATHUTILS
2749         return Vector_CreatePyObject_cb(
2750                 BGE_PROXY_FROM_REF_BORROW(self_v), 3,
2751                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_SCALE_LOCAL);
2752 #else
2753         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2754         return PyObjectFrom(self->NodeGetLocalScaling());
2755 #endif
2756 }
2757
2758 int KX_GameObject::pyattr_set_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2759 {
2760         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2761         MT_Vector3 scale;
2762         if (!PyVecTo(value, scale))
2763                 return PY_SET_ATTR_FAIL;
2764
2765         self->NodeSetLocalScale(scale);
2766         self->NodeUpdateGS(0.f);
2767         return PY_SET_ATTR_SUCCESS;
2768 }
2769
2770 PyObject *KX_GameObject::pyattr_get_localTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2771 {
2772         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2773
2774         float mat[16];
2775
2776         MT_Transform trans;
2777         
2778         trans.setOrigin(self->GetSGNode()->GetLocalPosition());
2779         trans.setBasis(self->GetSGNode()->GetLocalOrientation());
2780         
2781         MT_Vector3 scaling = self->GetSGNode()->GetLocalScale();
2782         trans.scale(scaling[0], scaling[1], scaling[2]);
2783
2784         trans.getValue(mat);
2785
2786         return PyObjectFrom(MT_Matrix4x4(mat));
2787 }
2788
2789 int KX_GameObject::pyattr_set_localTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2790 {
2791         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2792         MT_Matrix4x4 temp;
2793         if (!PyMatTo(value, temp))
2794                 return PY_SET_ATTR_FAIL;
2795
2796         float transform[4][4];
2797         float loc[3], size[3];
2798         float rot[3][3];
2799         MT_Matrix3x3 orientation;
2800
2801         temp.getValue(*transform);
2802         mat4_to_loc_rot_size(loc, rot, size, transform);
2803
2804         self->NodeSetLocalPosition(MT_Point3(loc));
2805
2806         //MT_Matrix3x3's constructor expects a 4x4 matrix
2807         orientation = MT_Matrix3x3();
2808         orientation.setValue3x3(*rot);
2809         self->NodeSetLocalOrientation(orientation);
2810
2811         self->NodeSetLocalScale(MT_Vector3(size));
2812
2813         return PY_SET_ATTR_SUCCESS;
2814 }
2815
2816 PyObject *KX_GameObject::pyattr_get_worldTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2817 {
2818         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2819
2820         return PyObjectFrom(MT_Matrix4x4(self->GetOpenGLMatrix()));
2821 }
2822
2823 int KX_GameObject::pyattr_set_worldTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2824 {
2825         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2826         MT_Matrix4x4 temp;
2827         if (!PyMatTo(value, temp))
2828                 return PY_SET_ATTR_FAIL;
2829
2830         float transform[4][4];
2831         float loc[3], size[3];
2832         float rot[3][3];
2833         MT_Matrix3x3 orientation;
2834
2835         temp.getValue(*transform);
2836         mat4_to_loc_rot_size(loc, rot, size, transform);
2837
2838         self->NodeSetWorldPosition(MT_Point3(loc));
2839
2840         //MT_Matrix3x3's constructor expects a 4x4 matrix
2841         orientation = MT_Matrix3x3();
2842         orientation.setValue3x3(*rot);
2843         self->NodeSetGlobalOrientation(orientation);
2844
2845         self->NodeSetWorldScale(MT_Vector3(size));
2846
2847         return PY_SET_ATTR_SUCCESS;
2848 }
2849
2850 PyObject *KX_GameObject::pyattr_get_worldLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2851 {
2852 #ifdef USE_MATHUTILS
2853         return Vector_CreatePyObject_cb(
2854                 BGE_PROXY_FROM_REF_BORROW(self_v), 3,
2855                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_LINVEL_GLOBAL);
2856 #else
2857         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2858         return PyObjectFrom(GetLinearVelocity(false));
2859 #endif
2860 }
2861
2862 int KX_GameObject::pyattr_set_worldLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2863 {
2864         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2865         MT_Vector3 velocity;
2866         if (!PyVecTo(value, velocity))
2867                 return PY_SET_ATTR_FAIL;
2868
2869         self->setLinearVelocity(velocity, false);
2870
2871         return PY_SET_ATTR_SUCCESS;
2872 }
2873
2874 PyObject *KX_GameObject::pyattr_get_localLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2875 {
2876 #ifdef USE_MATHUTILS
2877         return Vector_CreatePyObject_cb(
2878                 BGE_PROXY_FROM_REF_BORROW(self_v), 3,
2879                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_LINVEL_LOCAL);
2880 #else
2881         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2882         return PyObjectFrom(GetLinearVelocity(true));
2883 #endif
2884 }
2885
2886 int KX_GameObject::pyattr_set_localLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2887 {
2888         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2889         MT_Vector3 velocity;
2890         if (!PyVecTo(value, velocity))
2891                 return PY_SET_ATTR_FAIL;
2892
2893         self->setLinearVelocity(velocity, true);
2894
2895         return PY_SET_ATTR_SUCCESS;
2896 }
2897
2898 PyObject *KX_GameObject::pyattr_get_worldAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2899 {
2900 #ifdef USE_MATHUTILS
2901         return Vector_CreatePyObject_cb(
2902                 BGE_PROXY_FROM_REF_BORROW(self_v), 3,
2903                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_ANGVEL_GLOBAL);
2904 #else
2905         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2906         return PyObjectFrom(GetAngularVelocity(false));
2907 #endif
2908 }
2909
2910 int KX_GameObject::pyattr_set_worldAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2911 {
2912         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2913         MT_Vector3 velocity;
2914         if (!PyVecTo(value, velocity))
2915                 return PY_SET_ATTR_FAIL;
2916
2917         self->setAngularVelocity(velocity, false);
2918
2919         return PY_SET_ATTR_SUCCESS;
2920 }
2921
2922 PyObject *KX_GameObject::pyattr_get_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2923 {
2924 #ifdef USE_MATHUTILS
2925         return Vector_CreatePyObject_cb(
2926                 BGE_PROXY_FROM_REF_BORROW(self_v), 3,
2927                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_ANGVEL_LOCAL);
2928 #else
2929         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2930         return PyObjectFrom(GetAngularVelocity(true));
2931 #endif
2932 }
2933
2934 int KX_GameObject::pyattr_set_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2935 {
2936         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2937         MT_Vector3 velocity;
2938         if (!PyVecTo(value, velocity))
2939                 return PY_SET_ATTR_FAIL;
2940
2941         self->setAngularVelocity(velocity, true);
2942
2943         return PY_SET_ATTR_SUCCESS;
2944 }
2945
2946 PyObject *KX_GameObject::pyattr_get_linearDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2947 {
2948         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2949         return PyFloat_FromDouble(self->getLinearDamping());
2950 }
2951
2952 int KX_GameObject::pyattr_set_linearDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2953 {
2954         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2955         float val = PyFloat_AsDouble(value);
2956         self->setLinearDamping(val);
2957         return PY_SET_ATTR_SUCCESS;
2958 }
2959
2960 PyObject *KX_GameObject::pyattr_get_angularDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2961 {
2962         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2963         return PyFloat_FromDouble(self->getAngularDamping());
2964 }
2965
2966 int KX_GameObject::pyattr_set_angularDamping(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2967 {
2968         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2969         float val = PyFloat_AsDouble(value);
2970         self->setAngularDamping(val);
2971         return PY_SET_ATTR_SUCCESS;
2972 }
2973
2974
2975 PyObject *KX_GameObject::pyattr_get_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2976 {
2977         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2978         SG_Node* sg_parent;
2979         if (self->GetSGNode() && (sg_parent = self->GetSGNode()->GetSGParent()) != NULL && sg_parent->IsSlowParent()) {
2980                 return PyFloat_FromDouble(static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->GetTimeOffset());
2981         } else {
2982                 return PyFloat_FromDouble(0.0f);
2983         }
2984 }
2985
2986 int KX_GameObject::pyattr_set_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2987 {
2988         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2989         if (self->GetSGNode()) {
2990                 MT_Scalar val = PyFloat_AsDouble(value);
2991                 SG_Node *sg_parent= self->GetSGNode()->GetSGParent();
2992                 if (val < 0.0f) { /* also accounts for non float */
2993                         PyErr_SetString(PyExc_AttributeError, "gameOb.timeOffset = float: KX_GameObject, expected a float zero or above");
2994                         return PY_SET_ATTR_FAIL;
2995                 }
2996                 if (sg_parent && sg_parent->IsSlowParent())
2997                         static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->SetTimeOffset(val);
2998         }
2999         return PY_SET_ATTR_SUCCESS;
3000 }
3001
3002 PyObject *KX_GameObject::pyattr_get_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3003 {
3004         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
3005         int state = 0;
3006         state |= self->GetState();
3007         return PyLong_FromLong(state);
3008 }
3009
3010 int KX_GameObject::pyattr_set_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
3011 {
3012         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
3013         int state_i = PyLong_AsLong(value);
3014         unsigned int state = 0;
3015         
3016         if (state_i == -1 && PyErr_Occurred()) {
3017                 PyErr_SetString(PyExc_TypeError, "gameOb.state = int: KX_GameObject, expected an int bit field");
3018                 return PY_SET_ATTR_FAIL;
3019         }
3020         
3021         state |= state_i;
3022         if ((state & ((1<<30)-1)) == 0) {
3023                 PyErr_SetString(PyExc_AttributeError, "gameOb.state = int: KX_GameObject, state bitfield was not between 0 and 30 (1<<0 and 1<<29)");
3024                 return PY_SET_ATTR_FAIL;
3025         }
3026         self->SetState(state);
3027         return PY_SET_ATTR_SUCCESS;
3028 }
3029
3030 PyObject *KX_GameObject::pyattr_get_meshes(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3031 {
3032         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
3033         PyObject *meshes= PyList_New(self->m_meshes.size());
3034         int i;
3035         
3036         for (i=0; i < (int)self->m_meshes.size(); i++)
3037         {
3038                 KX_MeshProxy* meshproxy = new KX_MeshProxy(self->m_meshes[i]);
3039                 PyList_SET_ITEM(meshes, i, meshproxy->NewProxy(true));
3040         }
3041         
3042         return meshes;
3043 }
3044
3045 PyObject *KX_GameObject::pyattr_get_obcolor(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3046 {
3047 #ifdef USE_MATHUTILS
3048         return Vector_CreatePyObject_cb(
3049                 BGE_PROXY_FROM_REF_BORROW(self_v), 4,
3050                 mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_OBJECT_COLOR);
3051 #else
3052         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
3053         return PyObjectFrom(self->GetObjectColor());
3054 #endif
3055 }
3056
3057 int KX_GameObject::pyattr_set_obcolor(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
3058 {
3059         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
3060         MT_Vector4 obcolor;
3061         if (!PyVecTo(value, obcolor))
3062                 return PY_SET_ATTR_FAIL;
3063
3064         self->SetObjectColor(obcolor);
3065         return PY_SET_ATTR_SUCCESS;
3066 }
3067
3068 static int kx_game_object_get_sensors_size_cb(void *self_v)
3069 {
3070         return ((KX_GameObject *)self_v)->GetSensors().size();
3071 }
3072
3073 static PyObject *kx_game_object_get_sensors_item_cb(void *self_v, int index)
3074 {
3075         return ((KX_GameObject *)self_v)->GetSensors()[index]->GetProxy();
3076 }
3077
3078 static const char *kx_game_object_get_sensors_item_name_cb(void *self_v, int index)
3079 {
3080         return ((KX_GameObject *)self_v)->GetSensors()[index]->GetName().ReadPtr();
3081 }
3082
3083 /* These are experimental! */
3084 PyObject *KX_GameObject::pyattr_get_sensors(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3085 {
3086         return (new CListWrapper(self_v,
3087                                                          ((KX_GameObject *)self_v)->GetProxy(),
3088                                                          NULL,
3089                                                          kx_game_object_get_sensors_size_cb,
3090                                                          kx_game_object_get_sensors_item_cb,
3091                                                          kx_game_object_get_sensors_item_name_cb,
3092                                                          NULL))->NewProxy(true);
3093 }
3094
3095 static int kx_game_object_get_controllers_size_cb(void *self_v)
3096 {
3097         return ((KX_GameObject *)self_v)->GetControllers().size();
3098 }
3099
3100 static PyObject *kx_game_object_get_controllers_item_cb(void *self_v, int index)
3101 {
3102         return ((KX_GameObject *)self_v)->GetControllers()[index]->GetProxy();
3103 }
3104
3105 static const char *kx_game_object_get_controllers_item_name_cb(void *self_v, int index)
3106 {
3107         return ((KX_GameObject *)self_v)->GetControllers()[index]->GetName().ReadPtr();
3108 }
3109
3110 PyObject *KX_GameObject::pyattr_get_controllers(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3111 {
3112         return (new CListWrapper(self_v,
3113                                                          ((KX_GameObject *)self_v)->GetProxy(),
3114                                                          NULL,
3115                                                          kx_game_object_get_controllers_size_cb,
3116                                                          kx_game_object_get_controllers_item_cb,
3117                                                          kx_game_object_get_controllers_item_name_cb,
3118                                                          NULL))->NewProxy(true);
3119 }
3120
3121 static int kx_game_object_get_actuators_size_cb(void *self_v)
3122 {
3123         return ((KX_GameObject *)self_v)->GetActuators().size();
3124 }
3125
3126 static PyObject *kx_game_object_get_actuators_item_cb(void *self_v, int index)
3127 {
3128         return ((KX_GameObject *)self_v)->GetActuators()[index]->GetProxy();
3129 }
3130
3131 static const char *kx_game_object_get_actuators_item_name_cb(void *self_v, int index)
3132 {
3133         return ((KX_GameObject *)self_v)->GetActuators()[index]->GetName().ReadPtr();
3134 }
3135
3136 PyObject *KX_GameObject::pyattr_get_actuators(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3137 {
3138         return (new CListWrapper(self_v,
3139                                                          ((KX_GameObject *)self_v)->GetProxy(),
3140                                                          NULL,
3141                                                          kx_game_object_get_actuators_size_cb,
3142                                                          kx_game_object_get_actuators_item_cb,
3143                                                          kx_game_object_get_actuators_item_name_cb,
3144                                                          NULL))->NewProxy(true);
3145 }
3146 /* End experimental */
3147
3148 PyObject *KX_GameObject::pyattr_get_children(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3149 {
3150         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
3151         return self->GetChildren()->NewProxy(true);
3152 }
3153
3154 PyObject *KX_GameObject::pyattr_get_children_recursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3155 {
3156         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
3157         return self->GetChildrenRecursive()->NewProxy(true);
3158 }
3159
3160 PyObject *KX_GameObject::pyattr_get_attrDict(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3161 {
3162         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
3163         
3164         if (self->m_attr_dict==NULL)
3165                 self->m_attr_dict= PyDict_New();
3166         
3167         Py_INCREF(self->m_attr_dict);
3168         return self->m_attr_dict;
3169 }
3170
3171 PyObject *KX_GameObject::pyattr_get_debug(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3172 {
3173         KX_Scene *scene = KX_GetActiveScene();
3174         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
3175
3176         return PyBool_FromLong(scene->ObjectInDebugList(self));
3177 }
3178
3179 int KX_GameObject::pyattr_set_debug(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
3180 {
3181         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
3182         int param = PyObject_IsTrue(value);
3183
3184         if (param == -1) {
3185                 PyErr_SetString(PyExc_AttributeError, "gameOb.debug = bool: KX_GameObject, expected True or False");
3186                 return PY_SET_ATTR_FAIL;
3187         }
3188
3189         self->SetUseDebugProperties(param, false);
3190
3191         return PY_SET_ATTR_SUCCESS;
3192 }
3193
3194 PyObject *KX_GameObject::pyattr_get_debugRecursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
3195 {
3196         KX_Scene *scene = KX_GetActiveScene();
3197         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
3198
3199         return PyBool_FromLong(scene->ObjectInDebugList(self));
3200 }
3201
3202 int KX_GameObject::pyattr_set_debugRecursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
3203 {
3204         KX_GameObject *self = static_cast<KX_GameObject*>(self_v);
3205         int param = PyObject_IsTrue(value);
3206
3207         if (param == -1) {
3208                 PyErr_SetString(PyExc_AttributeError, "gameOb.debugRecursive = bool: KX_GameObject, expected True or False");
3209                 return PY_SET_ATTR_FAIL;
3210         }
3211
3212         self->SetUseDebugProperties(param, true);
3213
3214         return PY_SET_ATTR_SUCCESS;
3215 }
3216
3217 PyObject *KX_GameObject::PyApplyForce(PyObject *args)
3218 {
3219         int local = 0;
3220         PyObject *pyvect;
3221
3222         if (PyArg_ParseTuple(args, "O|i:applyForce", &pyvect, &local)) {
3223                 MT_Vector3 force;
3224                 if (PyVecTo(pyvect, force)) {
3225                         ApplyForce(force, (local!=0));
3226                         Py_RETURN_NONE;
3227                 }
3228         }
3229         return NULL;
3230 }
3231
3232 PyObject *KX_GameObject::PyApplyTorque(PyObject *args)
3233 {
3234         int local = 0;
3235         PyObject *pyvect;
3236
3237         if (PyArg_ParseTuple(args, "O|i:applyTorque", &pyvect, &local)) {
3238                 MT_Vector3 torque;
3239                 if (PyVecTo(pyvect, torque)) {
3240                         ApplyTorque(torque, (local!=0));
3241                         Py_RETURN_NONE;
3242                 }
3243         }
3244         return NULL;
3245 }
3246
3247 PyObject *KX_GameObject::PyApplyRotation(PyObject *args)
3248 {
3249         int local = 0;
3250         PyObject *pyvect;
3251
3252         if (PyArg_ParseTuple(args, "O|i:applyRotation", &pyvect, &local)) {
3253                 MT_Vector3 rotation;
3254                 if (PyVecTo(pyvect, rotation)) {
3255                         ApplyRotation(rotation, (local!=0));
3256                         Py_RETURN_NONE;
3257                 }
3258         }
3259         return NULL;
3260 }
3261
3262 PyObject *KX_GameObject::PyApplyMovement(PyObject *args)
3263 {
3264         int local = 0;
3265         PyObject *pyvect;
3266
3267         if (PyArg_ParseTuple(args, "O|i:applyMovement", &pyvect, &local)) {
3268                 MT_Vector3 movement;
3269                 if (PyVecTo(pyvect, movement)) {
3270                         ApplyMovement(movement, (local!=0));
3271                         Py_RETURN_NONE;
3272                 }
3273         }
3274         return NULL;
3275 }
3276
3277 PyObject *KX_GameObject::PyGetLinearVelocity(PyObject *args)
3278 {
3279         // only can get the velocity if we have a physics object connected to us...
3280         int local = 0;
3281         if (PyArg_ParseTuple(args,"|i:getLinearVelocity",&local))
3282         {
3283                 return PyObjectFrom(GetLinearVelocity((local!=0)));
3284         }
3285         else
3286         {
3287                 return NULL;
3288         }
3289 }
3290
3291 PyObject *KX_GameObject::PySetLinearVelocity(PyObject *args)
3292 {
3293         int local = 0;
3294         PyObject *pyvect;
3295         
3296         if (PyArg_ParseTuple(args,"O|i:setLinearVelocity",&pyvect,&local)) {
3297                 MT_Vector3 velocity;
3298                 if (PyVecTo(pyvect, velocity)) {
3299                         setLinearVelocity(velocity, (local!=0));
3300                         Py_RETURN_NONE;
3301                 }
3302         }
3303         return NULL;
3304 }
3305