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