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