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