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