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