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