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