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