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