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