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