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