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