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