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