fix BGE bug #8869: Added objects are not lit correctly
[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 <stdio.h> // printf
55 #include "SG_Controller.h"
56 #include "KX_IPhysicsController.h"
57 #include "SG_Node.h"
58 #include "SG_Controller.h"
59 #include "KX_ClientObjectInfo.h"
60 #include "RAS_BucketManager.h"
61 #include "KX_RayCast.h"
62 #include "KX_PythonInit.h"
63 #include "KX_PyMath.h"
64
65 // This file defines relationships between parents and children
66 // in the game engine.
67
68 #include "KX_SG_NodeRelationships.h"
69
70 KX_GameObject::KX_GameObject(
71         void* sgReplicationInfo,
72         SG_Callbacks callbacks,
73         PyTypeObject* T
74 ) : 
75         SCA_IObject(T),
76         m_bDyna(false),
77         m_layer(0),
78         m_bSuspendDynamics(false),
79         m_bUseObjectColor(false),
80         m_bVisible(true),
81         m_pPhysicsController1(NULL),
82         m_pPhysicsEnvironment(NULL),
83         m_isDeformable(false),
84         m_pHitObject(NULL)
85 {
86         m_ignore_activity_culling = false;
87         m_pClient_info = new KX_ClientObjectInfo(this, KX_ClientObjectInfo::ACTOR);
88         m_pSGNode = new SG_Node(this,sgReplicationInfo,callbacks);
89
90         // define the relationship between this node and it's parent.
91         
92         KX_NormalParentRelation * parent_relation = 
93                 KX_NormalParentRelation::New();
94         m_pSGNode->SetParentRelation(parent_relation);
95         
96
97 };
98
99
100
101 KX_GameObject::~KX_GameObject()
102 {
103         // is this delete somewhere ?
104         //if (m_sumoObj)
105         //      delete m_sumoObj;
106         delete m_pClient_info;
107         //if (m_pSGNode)
108         //      delete m_pSGNode;
109         if (m_pSGNode)
110         {
111                 // must go through controllers and make sure they will not use us anymore
112                 // This is important for KX_BulletPhysicsControllers that unregister themselves
113                 // from the object when they are deleted.
114                 SGControllerList::iterator contit;
115                 SGControllerList& controllers = m_pSGNode->GetSGControllerList();
116                 for (contit = controllers.begin();contit!=controllers.end();++contit)
117                 {
118                         (*contit)->ClearObject();
119                 }
120                 m_pSGNode->SetSGClientObject(NULL);
121         }
122 }
123
124
125
126 CValue* KX_GameObject:: Calc(VALUE_OPERATOR op, CValue *val) 
127 {
128         return NULL;
129 }
130
131
132
133 CValue* KX_GameObject::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val)
134 {
135         return NULL;
136 }
137
138
139
140 const STR_String & KX_GameObject::GetText()
141 {
142         return m_text;
143 }
144
145
146
147 float KX_GameObject::GetNumber()
148 {
149         return 0;
150 }
151
152
153
154 STR_String KX_GameObject::GetName()
155 {
156         return m_name;
157 }
158
159
160
161 void KX_GameObject::SetName(STR_String name)
162 {
163         m_name = name;
164 };                                                              // Set the name of the value
165
166
167
168 void KX_GameObject::ReplicaSetName(STR_String name)
169 {
170 }
171
172
173
174
175
176
177 KX_IPhysicsController* KX_GameObject::GetPhysicsController()
178 {
179         return m_pPhysicsController1;
180 }
181
182
183
184
185
186 KX_GameObject* KX_GameObject::GetParent()
187 {
188         KX_GameObject* result = NULL;
189         SG_Node* node = m_pSGNode;
190         
191         while (node && !result)
192         {
193                 node = node->GetSGParent();
194                 if (node)
195                         result = (KX_GameObject*)node->GetSGClientObject();
196         }
197         
198         if (result)
199                 result->AddRef();
200
201         return result;
202         
203 }
204
205 void KX_GameObject::SetParent(KX_Scene *scene, KX_GameObject* obj)
206 {
207         if (obj && GetSGNode()->GetSGParent() != obj->GetSGNode())
208         {
209                 // Make sure the objects have some scale
210                 MT_Vector3 scale1 = NodeGetWorldScaling();
211                 MT_Vector3 scale2 = obj->NodeGetWorldScaling();
212                 if (fabs(scale2[0]) < FLT_EPSILON || 
213                         fabs(scale2[1]) < FLT_EPSILON || 
214                         fabs(scale2[2]) < FLT_EPSILON || 
215                         fabs(scale1[0]) < FLT_EPSILON || 
216                         fabs(scale1[1]) < FLT_EPSILON || 
217                         fabs(scale1[2]) < FLT_EPSILON) { return; }
218
219                 // Remove us from our old parent and set our new parent
220                 RemoveParent(scene);
221                 obj->GetSGNode()->AddChild(GetSGNode());
222
223                 // Set us to our new scale, position, and orientation
224                 scale1[0] = scale1[0]/scale2[0];
225                 scale1[1] = scale1[1]/scale2[1];
226                 scale1[2] = scale1[2]/scale2[2];
227                 MT_Matrix3x3 invori = obj->NodeGetWorldOrientation().inverse();
228                 MT_Vector3 newpos = invori*(NodeGetWorldPosition()-obj->NodeGetWorldPosition())*scale1;
229
230                 NodeSetLocalScale(scale1);
231                 NodeSetLocalPosition(MT_Point3(newpos[0],newpos[1],newpos[2]));
232                 NodeSetLocalOrientation(NodeGetWorldOrientation()*invori);
233                 NodeUpdateGS(0.f,true);
234                 // object will now be a child, it must be removed from the parent list
235                 CListValue* rootlist = scene->GetRootParentList();
236                 if (rootlist->RemoveValue(this))
237                         // the object was in parent list, decrement ref count as it's now removed
238                         Release();
239         }
240 }
241
242 void KX_GameObject::RemoveParent(KX_Scene *scene)
243 {
244         if (GetSGNode()->GetSGParent())
245         {
246                 // Set us to the right spot 
247                 GetSGNode()->SetLocalScale(GetSGNode()->GetWorldScaling());
248                 GetSGNode()->SetLocalOrientation(GetSGNode()->GetWorldOrientation());
249                 GetSGNode()->SetLocalPosition(GetSGNode()->GetWorldPosition());
250
251                 // Remove us from our parent
252                 GetSGNode()->DisconnectFromParent();
253                 NodeUpdateGS(0.f,true);
254                 // the object is now a root object, add it to the parentlist
255                 CListValue* rootlist = scene->GetRootParentList();
256                 if (!rootlist->SearchValue(this))
257                         // object was not in root list, add it now and increment ref count
258                         rootlist->Add(AddRef());
259         }
260 }
261
262 void KX_GameObject::ProcessReplica(KX_GameObject* replica)
263 {
264         replica->m_pPhysicsController1 = NULL;
265         replica->m_pSGNode = NULL;
266         replica->m_pClient_info = new KX_ClientObjectInfo(*m_pClient_info);
267         replica->m_pClient_info->m_gameobject = replica;
268 }
269
270
271
272 CValue* KX_GameObject::GetReplica()
273 {
274         KX_GameObject* replica = new KX_GameObject(*this);
275         
276         // this will copy properties and so on...
277         CValue::AddDataToReplica(replica);
278         ProcessReplica(replica);
279         
280         return replica;
281 }
282
283
284
285 void KX_GameObject::ApplyForce(const MT_Vector3& force,bool local)
286 {
287         if (m_pPhysicsController1)
288                 m_pPhysicsController1->ApplyForce(force,local);
289 }
290
291
292
293 void KX_GameObject::ApplyTorque(const MT_Vector3& torque,bool local)
294 {
295         if (m_pPhysicsController1)
296                 m_pPhysicsController1->ApplyTorque(torque,local);
297 }
298
299
300
301 void KX_GameObject::ApplyMovement(const MT_Vector3& dloc,bool local)
302 {
303         if (m_pPhysicsController1) // (IsDynamic())
304         {
305                 m_pPhysicsController1->RelativeTranslate(dloc,local);
306         }
307         GetSGNode()->RelativeTranslate(dloc,GetSGNode()->GetSGParent(),local);
308 }
309
310
311
312 void KX_GameObject::ApplyRotation(const MT_Vector3& drot,bool local)
313 {
314         MT_Matrix3x3 rotmat(drot);
315
316         GetSGNode()->RelativeRotate(rotmat,local);
317
318         if (m_pPhysicsController1) { // (IsDynamic())
319                 m_pPhysicsController1->RelativeRotate(rotmat,local); 
320         }
321 }
322
323
324
325 /**
326 GetOpenGL Matrix, returns an OpenGL 'compatible' matrix
327 */
328 double* KX_GameObject::GetOpenGLMatrix()
329 {
330         // todo: optimize and only update if necessary
331         double* fl = m_OpenGL_4x4Matrix.getPointer();
332         MT_Transform trans;
333         
334         trans.setOrigin(GetSGNode()->GetWorldPosition());
335         trans.setBasis(GetSGNode()->GetWorldOrientation());
336         
337         MT_Vector3 scaling = GetSGNode()->GetWorldScaling();
338         
339         trans.scale(scaling[0], scaling[1], scaling[2]);
340         trans.getValue(fl);
341
342         return fl;
343 }
344
345
346
347 void KX_GameObject::Bucketize()
348 {
349         double* fl = GetOpenGLMatrix();
350
351         for (size_t i=0;i<m_meshes.size();i++)
352                 m_meshes[i]->Bucketize(fl, this, m_bUseObjectColor, m_objectColor);
353 }
354
355
356
357 void KX_GameObject::RemoveMeshes()
358 {
359         double* fl = GetOpenGLMatrix();
360
361         for (size_t i=0;i<m_meshes.size();i++)
362                 m_meshes[i]->RemoveFromBuckets(fl, this);
363
364         //note: meshes can be shared, and are deleted by KX_BlenderSceneConverter
365
366         m_meshes.clear();
367 }
368
369
370
371 void KX_GameObject::UpdateNonDynas()
372 {
373         if (m_pPhysicsController1)
374         {
375                 m_pPhysicsController1->SetSumoTransform(true);
376         }
377 }
378
379
380
381 void KX_GameObject::UpdateTransform()
382 {
383         if (m_pPhysicsController1)
384                 m_pPhysicsController1->SetSumoTransform(false);
385 }
386
387 void KX_GameObject::UpdateTransformFunc(SG_IObject* node, void* gameobj, void* scene)
388 {
389         ((KX_GameObject*)gameobj)->UpdateTransform();
390 }
391
392
393 void KX_GameObject::SetDebugColor(unsigned int bgra)
394 {
395         for (size_t i=0;i<m_meshes.size();i++)
396                 m_meshes[i]->DebugColor(bgra);  
397 }
398
399
400
401 void KX_GameObject::ResetDebugColor()
402 {
403         SetDebugColor(0xff000000);
404 }
405
406
407
408 void KX_GameObject::UpdateIPO(float curframetime,
409                                                           bool recurse,
410                                                           bool ipo_as_force,
411                                                           bool force_local) 
412 {
413
414         // The ipo-actuator needs a sumo reference... this is retrieved (unfortunately)
415         // by the iposgcontr itself...
416 //              ipocontr->SetSumoReference(gameobj->GetSumoScene(), 
417 //                                                                 gameobj->GetSumoObject());
418
419
420         // The ipo has to be treated as a force, and not a displacement!
421         // For this case, we send some settings to the controller. This
422         // may need some caching...
423         if (ipo_as_force) {
424                 SGControllerList::iterator it = GetSGNode()->GetSGControllerList().begin();
425
426                 while (it != GetSGNode()->GetSGControllerList().end()) {
427                         (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_AS_FORCE, ipo_as_force);
428                         (*it)->SetOption(SG_Controller::SG_CONTR_IPO_FORCES_ACT_LOCAL, force_local);
429                         it++;
430                 }
431         } 
432
433         // The rest is the 'normal' update procedure.
434         GetSGNode()->SetSimulatedTime(curframetime,recurse);
435         GetSGNode()->UpdateWorldData(curframetime);
436         UpdateTransform();
437 }
438
439 // IPO update
440 void 
441 KX_GameObject::UpdateMaterialData(
442                 MT_Vector4 rgba,
443                 MT_Vector3 specrgb,
444                 MT_Scalar hard,
445                 MT_Scalar spec,
446                 MT_Scalar ref,
447                 MT_Scalar emit,
448                 MT_Scalar alpha
449
450         )
451 {
452         int mesh = 0;
453         if (((unsigned int)mesh < m_meshes.size()) && mesh >= 0) {
454                 RAS_MaterialBucket::Set::iterator mit = m_meshes[mesh]->GetFirstMaterial();
455                 for(; mit != m_meshes[mesh]->GetLastMaterial(); ++mit)
456                 {
457                         RAS_IPolyMaterial* poly = (*mit)->GetPolyMaterial();
458                         if(poly->GetFlag() & RAS_BLENDERMAT )
459                         {
460                                 SetObjectColor(rgba);
461                                 KX_BlenderMaterial *m =  static_cast<KX_BlenderMaterial*>(poly);
462                                 m->UpdateIPO(rgba, specrgb,hard,spec,ref,emit, alpha);
463                         }
464                 }
465         }
466 }
467 bool
468 KX_GameObject::GetVisible(
469         void
470         )
471 {
472         return m_bVisible;
473 }
474
475 void
476 KX_GameObject::SetVisible(
477         bool v
478         )
479 {
480         m_bVisible = v;
481 }
482
483 void
484 KX_GameObject::SetLayer(
485         int l
486         )
487 {
488         m_layer = l;
489 }
490
491 int
492 KX_GameObject::GetLayer(
493         void
494         )
495 {
496         return m_layer;
497 }
498
499 // used by Python, and the actuatorshould _not_ be misused by the
500 // scene!
501 void 
502 KX_GameObject::MarkVisible(
503         bool visible
504         )
505 {
506         /* If explicit visibility settings are used, this is
507          * determined on this level. Maybe change this to mesh level
508          * later on? */
509         
510         double* fl = GetOpenGLMatrixPtr()->getPointer();
511         for (size_t i=0;i<m_meshes.size();i++)
512         {
513                 m_meshes[i]->MarkVisible(fl,this,visible,m_bUseObjectColor,m_objectColor);
514         }
515 }
516
517
518 // Always use the flag?
519 void 
520 KX_GameObject::MarkVisible(
521         void
522         )
523 {
524         double* fl = GetOpenGLMatrixPtr()->getPointer();
525         for (size_t i=0;i<m_meshes.size();i++)
526         {
527                 m_meshes[i]->MarkVisible(fl,
528                                          this,
529                                          m_bVisible,
530                                          m_bUseObjectColor,
531                                          m_objectColor
532                         );
533         }
534 }
535
536
537 void KX_GameObject::addLinearVelocity(const MT_Vector3& lin_vel,bool local)
538 {
539         if (m_pPhysicsController1)
540                 m_pPhysicsController1->SetLinearVelocity(lin_vel + m_pPhysicsController1->GetLinearVelocity(),local);
541 }
542
543
544
545 void KX_GameObject::setLinearVelocity(const MT_Vector3& lin_vel,bool local)
546 {
547         if (m_pPhysicsController1)
548                 m_pPhysicsController1->SetLinearVelocity(lin_vel,local);
549 }
550
551
552
553 void KX_GameObject::setAngularVelocity(const MT_Vector3& ang_vel,bool local)
554 {
555         if (m_pPhysicsController1)
556                 m_pPhysicsController1->SetAngularVelocity(ang_vel,local);
557 }
558
559 void KX_GameObject::ResolveCombinedVelocities(
560         const MT_Vector3 & lin_vel,
561         const MT_Vector3 & ang_vel,
562         bool lin_vel_local,
563         bool ang_vel_local
564 ){
565         if (m_pPhysicsController1)
566         {
567
568                 MT_Vector3 lv = lin_vel_local ? NodeGetWorldOrientation() * lin_vel : lin_vel;
569                 MT_Vector3 av = ang_vel_local ? NodeGetWorldOrientation() * ang_vel : ang_vel;
570                 m_pPhysicsController1->resolveCombinedVelocities(
571                         lv.x(),lv.y(),lv.z(),av.x(),av.y(),av.z());
572         }
573 }
574
575
576 void KX_GameObject::SetObjectColor(const MT_Vector4& rgbavec)
577 {
578         m_bUseObjectColor = true;
579         m_objectColor = rgbavec;
580 }
581
582
583
584 MT_Vector3 KX_GameObject::GetLinearVelocity()
585 {
586         MT_Vector3 velocity(0.0,0.0,0.0);
587         
588         if (m_pPhysicsController1)
589         {
590                 velocity = m_pPhysicsController1->GetLinearVelocity();
591         }
592         return velocity;
593         
594 }
595
596
597 // scenegraph node stuff
598
599 void KX_GameObject::NodeSetLocalPosition(const MT_Point3& trans)
600 {
601         if (m_pPhysicsController1)
602         {
603                 m_pPhysicsController1->setPosition(trans);
604         }
605
606         if (GetSGNode())
607                 GetSGNode()->SetLocalPosition(trans);
608 }
609
610
611
612 void KX_GameObject::NodeSetLocalOrientation(const MT_Matrix3x3& rot)
613 {
614         if (m_pPhysicsController1)
615         {
616                 m_pPhysicsController1->setOrientation(rot.getRotation());
617         }
618         if (GetSGNode())
619                 GetSGNode()->SetLocalOrientation(rot);
620         else
621         {
622                 int i;
623                 i=0;
624         }
625 }
626
627
628
629 void KX_GameObject::NodeSetLocalScale(const MT_Vector3& scale)
630 {
631         if (m_pPhysicsController1)
632         {
633                 m_pPhysicsController1->setScaling(scale);
634         }
635         
636         if (GetSGNode())
637                 GetSGNode()->SetLocalScale(scale);
638 }
639
640
641
642 void KX_GameObject::NodeSetRelativeScale(const MT_Vector3& scale)
643 {
644         if (GetSGNode())
645                 GetSGNode()->RelativeScale(scale);
646 }
647
648
649
650 void KX_GameObject::NodeUpdateGS(double time,bool bInitiator)
651 {
652         if (GetSGNode())
653                 GetSGNode()->UpdateWorldData(time);
654 }
655
656
657
658 const MT_Matrix3x3& KX_GameObject::NodeGetWorldOrientation() const
659 {
660         return GetSGNode()->GetWorldOrientation();
661 }
662
663
664
665 const MT_Vector3& KX_GameObject::NodeGetWorldScaling() const
666 {
667         return GetSGNode()->GetWorldScaling();
668 }
669
670
671
672 const MT_Point3& KX_GameObject::NodeGetWorldPosition() const
673 {
674         return GetSGNode()->GetWorldPosition();
675 }
676
677 /* Suspend/ resume: for the dynamic behaviour, there is a simple
678  * method. For the residual motion, there is not. I wonder what the
679  * correct solution is for Sumo. Remove from the motion-update tree?
680  *
681  * So far, only switch the physics and logic.
682  * */
683
684 void KX_GameObject::Resume(void)
685 {
686         if (m_suspended) {
687                 SCA_IObject::Resume();
688                 GetPhysicsController()->RestoreDynamics();
689
690                 m_suspended = false;
691         }
692 }
693
694 void KX_GameObject::Suspend(void)
695 {
696         if ((!m_ignore_activity_culling) 
697                 && (!m_suspended))  {
698                 SCA_IObject::Suspend();
699                 GetPhysicsController()->SuspendDynamics();
700                 m_suspended = true;
701         }
702 }
703
704
705
706
707 /* ------- python stuff ---------------------------------------------------*/
708
709
710
711
712 PyMethodDef KX_GameObject::Methods[] = {
713         {"setVisible",(PyCFunction) KX_GameObject::sPySetVisible, METH_VARARGS},  
714         {"setPosition", (PyCFunction) KX_GameObject::sPySetPosition, METH_VARARGS},
715         {"getPosition", (PyCFunction) KX_GameObject::sPyGetPosition, METH_VARARGS},
716         {"getOrientation", (PyCFunction) KX_GameObject::sPyGetOrientation, METH_VARARGS},
717         {"setOrientation", (PyCFunction) KX_GameObject::sPySetOrientation, METH_VARARGS},
718         {"getLinearVelocity", (PyCFunction) KX_GameObject::sPyGetLinearVelocity, METH_VARARGS},
719         {"getVelocity", (PyCFunction) KX_GameObject::sPyGetVelocity, METH_VARARGS},
720         {"getMass", (PyCFunction) KX_GameObject::sPyGetMass, METH_VARARGS},
721         {"getReactionForce", (PyCFunction) KX_GameObject::sPyGetReactionForce, METH_VARARGS},
722         {"applyImpulse", (PyCFunction) KX_GameObject::sPyApplyImpulse, METH_VARARGS},
723         {"setCollisionMargin", (PyCFunction) KX_GameObject::sPySetCollisionMargin, METH_VARARGS},
724         {"suspendDynamics", (PyCFunction)KX_GameObject::sPySuspendDynamics,METH_VARARGS},
725         {"restoreDynamics", (PyCFunction)KX_GameObject::sPyRestoreDynamics,METH_VARARGS},
726         {"enableRigidBody", (PyCFunction)KX_GameObject::sPyEnableRigidBody,METH_VARARGS},
727         {"disableRigidBody", (PyCFunction)KX_GameObject::sPyDisableRigidBody,METH_VARARGS},
728         {"getParent", (PyCFunction)KX_GameObject::sPyGetParent,METH_VARARGS},
729         {"setParent", (PyCFunction)KX_GameObject::sPySetParent,METH_VARARGS},
730         {"removeParent", (PyCFunction)KX_GameObject::sPyRemoveParent,METH_VARARGS},
731         {"getMesh", (PyCFunction)KX_GameObject::sPyGetMesh,METH_VARARGS},
732         {"getPhysicsId", (PyCFunction)KX_GameObject::sPyGetPhysicsId,METH_VARARGS},
733         KX_PYMETHODTABLE(KX_GameObject, getDistanceTo),
734         KX_PYMETHODTABLE(KX_GameObject, rayCastTo),
735         {NULL,NULL} //Sentinel
736 };
737
738
739
740 /*
741 bool KX_GameObject::ConvertPythonVectorArgs(PyObject* args,
742                                                                                         MT_Vector3& pos,
743                                                                                         MT_Vector3& pos2)
744 {
745         PyObject* pylist;
746         PyObject* pylist2;
747         bool error = (PyArg_ParseTuple(args,"OO",&pylist,&pylist2)) != 0;
748
749         pos = ConvertPythonPylist(pylist);
750         pos2 = ConvertPythonPylist(pylist2);
751                 
752         return error;
753 }
754 */
755
756
757 PyObject* KX_GameObject::sPySetPosition(PyObject* self,
758                                                                                 PyObject* args,
759                                                                                 PyObject* kwds)
760 {
761         return ((KX_GameObject*) self)->PySetPosition(self, args, kwds);
762 }
763         
764
765
766 PyObject* KX_GameObject::PyGetPosition(PyObject* self,
767                                                                            PyObject* args, 
768                                                                            PyObject* kwds)
769 {
770         return PyObjectFrom(NodeGetWorldPosition());
771 }
772
773
774
775 PyTypeObject KX_GameObject::Type = {
776         PyObject_HEAD_INIT(&PyType_Type)
777                 0,
778                 "KX_GameObject",
779                 sizeof(KX_GameObject),
780                 0,
781                 PyDestructor,
782                 0,
783                 __getattr,
784                 __setattr,
785                 0, //&MyPyCompare,
786                 __repr,
787                 0, //&cvalue_as_number,
788                 0,
789                 0,
790                 0,
791                 0
792 };
793
794
795
796 PyParentObject KX_GameObject::Parents[] = {
797         &KX_GameObject::Type,
798                 &SCA_IObject::Type,
799                 &CValue::Type,
800                 NULL
801 };
802
803
804
805
806 PyObject* KX_GameObject::_getattr(const STR_String& attr)
807 {
808         if (m_pPhysicsController1)
809         {
810                 if (attr == "mass")
811                         return PyFloat_FromDouble(GetPhysicsController()->GetMass());
812         }
813
814         if (attr == "parent")
815         {       
816                 KX_GameObject* parent = GetParent();
817                 if (parent)
818                 {
819                         parent->AddRef();
820                         return parent;
821                 }
822                 Py_Return;
823         }
824
825         if (attr == "visible")
826                 return PyInt_FromLong(m_bVisible);
827         
828         if (attr == "position")
829                 return PyObjectFrom(NodeGetWorldPosition());
830         
831         if (attr == "orientation")
832                 return PyObjectFrom(NodeGetWorldOrientation());
833         
834         if (attr == "scaling")
835                 return PyObjectFrom(NodeGetWorldScaling());
836                 
837         if (attr == "name")
838                 return PyString_FromString(m_name.ReadPtr());
839         
840         _getattr_up(SCA_IObject);
841 }
842
843 int KX_GameObject::_setattr(const STR_String& attr, PyObject *value)    // _setattr method
844 {
845         if (attr == "mass")
846                 return 1;
847         
848         if (attr == "parent")
849                 return 1;
850                 
851         if (PyInt_Check(value))
852         {
853                 int val = PyInt_AsLong(value);
854                 if (attr == "visible")
855                 {
856                         SetVisible(val != 0);
857                         return 0;
858                 }
859         }
860         
861         if (PySequence_Check(value))
862         {
863                 if (attr == "orientation")
864                 {
865                         MT_Matrix3x3 rot;
866                         if (PyObject_IsMT_Matrix(value, 3))
867                         {
868                                 if (PyMatTo(value, rot))
869                                 {
870                                         NodeSetLocalOrientation(rot);
871                                         NodeUpdateGS(0.f,true);
872                                         return 0;
873                                 }
874                                 return 1;
875                         }
876                         
877                         if (PySequence_Size(value) == 4)
878                         {
879                                 MT_Quaternion qrot;
880                                 if (PyVecTo(value, qrot))
881                                 {
882                                         rot.setRotation(qrot);
883                                         NodeSetLocalOrientation(rot);
884                                         NodeUpdateGS(0.f,true);
885                                         return 0;
886                                 }
887                                 return 1;
888                         }
889                         
890                         if (PySequence_Size(value) == 3)
891                         {
892                                 MT_Vector3 erot;
893                                 if (PyVecTo(value, erot))
894                                 {
895                                         rot.setEuler(erot);
896                                         NodeSetLocalOrientation(rot);
897                                         NodeUpdateGS(0.f,true);
898                                         return 0;
899                                 }
900                                 return 1;
901                         }
902                         
903                         return 1;
904                 }
905                 
906                 if (attr == "position")
907                 {
908                         MT_Point3 pos;
909                         if (PyVecTo(value, pos))
910                         {
911                                 NodeSetLocalPosition(pos);
912                                 NodeUpdateGS(0.f,true);
913                                 return 0;
914                         }
915                         return 1;
916                 }
917                 
918                 if (attr == "scaling")
919                 {
920                         MT_Vector3 scale;
921                         if (PyVecTo(value, scale))
922                         {
923                                 NodeSetLocalScale(scale);
924                                 NodeUpdateGS(0.f,true);
925                                 return 0;
926                         }
927                         return 1;
928                 }
929         }
930         
931         if (PyString_Check(value))
932         {
933                 if (attr == "name")
934                 {
935                         m_name = PyString_AsString(value);
936                         return 0;
937                 }
938         }
939         
940         /* Need to have parent settable here too */
941         
942         return SCA_IObject::_setattr(attr, value);
943 }
944
945
946 PyObject* KX_GameObject::PyGetLinearVelocity(PyObject* self, 
947                                                                                          PyObject* args, 
948                                                                                          PyObject* kwds)
949 {
950         // only can get the velocity if we have a physics object connected to us...
951         return PyObjectFrom(GetLinearVelocity());
952 }
953
954
955
956 PyObject* KX_GameObject::PySetVisible(PyObject* self,
957                                                                           PyObject* args,
958                                                                           PyObject* kwds)
959 {
960         int visible = 1;
961         
962         if (PyArg_ParseTuple(args,"i",&visible))
963         {
964                 MarkVisible(visible!=0);
965                 m_bVisible = (visible!=0);
966         }
967         else
968         {
969                 return NULL;         
970         }
971         Py_Return;
972         
973 }
974
975
976
977 PyObject* KX_GameObject::PyGetVelocity(PyObject* self, 
978                                                                            PyObject* args, 
979                                                                            PyObject* kwds)
980 {
981         // only can get the velocity if we have a physics object connected to us...
982         MT_Vector3 velocity(0.0,0.0,0.0);
983         MT_Point3 point(0.0,0.0,0.0);
984         
985         
986         PyObject* pypos = NULL;
987         if (PyArg_ParseTuple(args, "|O", &pypos))
988         {
989                 if (pypos)
990                         PyVecTo(pypos, point);
991         }
992         
993         if (m_pPhysicsController1)
994         {
995                 velocity = m_pPhysicsController1->GetVelocity(point);
996         }
997         
998         return PyObjectFrom(velocity);
999 }
1000
1001
1002
1003 PyObject* KX_GameObject::PyGetMass(PyObject* self, 
1004                                                                    PyObject* args, 
1005                                                                    PyObject* kwds)
1006 {
1007         PyObject* pymass = NULL;
1008         
1009         float mass = GetPhysicsController()->GetMass();
1010         pymass = PyFloat_FromDouble(mass);
1011
1012         if (pymass)
1013                 return pymass;
1014         
1015         Py_Return;
1016 }
1017
1018
1019
1020 PyObject* KX_GameObject::PyGetReactionForce(PyObject* self, 
1021                                                                                         PyObject* args, 
1022                                                                                         PyObject* kwds)
1023 {
1024         // only can get the velocity if we have a physics object connected to us...
1025         return PyObjectFrom(GetPhysicsController()->getReactionForce());
1026 }
1027
1028
1029
1030 PyObject* KX_GameObject::PyEnableRigidBody(PyObject* self, 
1031                                                                                    PyObject* args, 
1032                                                                                    PyObject* kwds)
1033 {
1034         
1035         GetPhysicsController()->setRigidBody(true);
1036
1037         Py_Return;
1038 }
1039
1040
1041
1042 PyObject* KX_GameObject::PyDisableRigidBody(PyObject* self, 
1043                                                                                         PyObject* args, 
1044                                                                                         PyObject* kwds)
1045 {
1046         GetPhysicsController()->setRigidBody(false);
1047
1048         Py_Return;
1049 }
1050
1051
1052
1053 PyObject* KX_GameObject::PyGetParent(PyObject* self, 
1054                                                                          PyObject* args, 
1055                                                                          PyObject* kwds)
1056 {
1057         KX_GameObject* parent = this->GetParent();
1058         if (parent)
1059         {
1060                 parent->AddRef();
1061                 return parent;
1062         }
1063         Py_Return;
1064 }
1065
1066 PyObject* KX_GameObject::PySetParent(PyObject* self, 
1067                                                                          PyObject* args, 
1068                                                                          PyObject* kwds)
1069 {
1070         PyObject* gameobj;
1071         if (PyArg_ParseTuple(args, "O!", &KX_GameObject::Type, &gameobj))
1072         {
1073                 // The object we want to set as parent
1074                 CValue *m_ob = (CValue*)gameobj;
1075                 KX_GameObject *obj = ((KX_GameObject*)m_ob);
1076                 KX_Scene *scene = PHY_GetActiveScene();
1077                 
1078                 this->SetParent(scene, obj);
1079         }
1080         Py_Return;
1081 }
1082
1083 PyObject* KX_GameObject::PyRemoveParent(PyObject* self, 
1084                                                                          PyObject* args, 
1085                                                                          PyObject* kwds)
1086 {
1087         KX_Scene *scene = PHY_GetActiveScene();
1088         this->RemoveParent(scene);
1089         Py_Return;
1090 }
1091
1092 PyObject* KX_GameObject::PyGetMesh(PyObject* self, 
1093                                                                    PyObject* args, 
1094                                                                    PyObject* kwds)
1095 {
1096         int mesh = 0;
1097
1098         if (PyArg_ParseTuple(args, "|i", &mesh))
1099         {
1100                 if (((unsigned int)mesh < m_meshes.size()) && mesh >= 0)
1101                 {
1102                         KX_MeshProxy* meshproxy = new KX_MeshProxy(m_meshes[mesh]);
1103                         return meshproxy;
1104                 }
1105         }
1106         Py_Return;
1107 }
1108
1109
1110
1111
1112
1113 PyObject* KX_GameObject::PySetCollisionMargin(PyObject* self, 
1114                                                                                 PyObject* args, 
1115                                                                                 PyObject* kwds)
1116 {
1117         float collisionMargin;
1118         if (PyArg_ParseTuple(args, "f", &collisionMargin))
1119         {
1120                 if (m_pPhysicsController1)
1121                 {
1122                         m_pPhysicsController1->setMargin(collisionMargin);
1123                         Py_Return;
1124                 }
1125
1126         }
1127         
1128         return NULL;
1129 }
1130
1131
1132
1133 PyObject* KX_GameObject::PyApplyImpulse(PyObject* self, 
1134                                                                                 PyObject* args, 
1135                                                                                 PyObject* kwds)
1136 {
1137         PyObject* pyattach;
1138         PyObject* pyimpulse;
1139         if (PyArg_ParseTuple(args, "OO", &pyattach, &pyimpulse))
1140         {
1141                 MT_Point3  attach;
1142                 MT_Vector3 impulse;
1143                 if (m_pPhysicsController1)
1144                 {
1145                         if (PyVecTo(pyattach, attach) && PyVecTo(pyimpulse, impulse))
1146                         {
1147                                 m_pPhysicsController1->applyImpulse(attach, impulse);
1148                                 Py_Return;
1149                         }
1150                 }
1151
1152         }
1153         
1154         return NULL;
1155 }
1156
1157
1158
1159 PyObject* KX_GameObject::PySuspendDynamics(PyObject* self, 
1160                                                                                    PyObject* args, 
1161                                                                                    PyObject* kwds)
1162 {
1163         if (m_bSuspendDynamics)
1164         {
1165                 Py_Return;
1166         }
1167         
1168         if (m_pPhysicsController1)
1169         {
1170                 m_pPhysicsController1->SuspendDynamics();
1171         }
1172         m_bSuspendDynamics = true;
1173         
1174         Py_Return;
1175 }
1176
1177
1178
1179 PyObject* KX_GameObject::PyRestoreDynamics(PyObject* self, 
1180                                                                                    PyObject* args, 
1181                                                                                    PyObject* kwds)
1182 {
1183         
1184         if (!m_bSuspendDynamics)
1185         {
1186                 Py_Return;
1187         }
1188         
1189         if (m_pPhysicsController1)
1190         {
1191                 m_pPhysicsController1->RestoreDynamics();
1192         }
1193         m_bSuspendDynamics = false;
1194         
1195         Py_Return;
1196 }
1197
1198
1199
1200 PyObject* KX_GameObject::PyGetOrientation(PyObject* self,
1201                                                                                   PyObject* args,
1202                                                                                   PyObject* kwds) //keywords
1203 {
1204         return PyObjectFrom(NodeGetWorldOrientation());
1205 }
1206
1207
1208
1209 PyObject* KX_GameObject::PySetOrientation(PyObject* self, 
1210                                                                                   PyObject* args, 
1211                                                                                   PyObject* kwds)
1212 {
1213         PyObject* pylist;
1214         
1215         if (PyArg_ParseTuple(args,"O",&pylist))
1216         {
1217                 MT_Matrix3x3 matrix;
1218                 if (PyObject_IsMT_Matrix(pylist, 3) && PyMatTo(pylist, matrix))
1219                 {
1220                         NodeSetLocalOrientation(matrix);
1221                         NodeUpdateGS(0.f,true);
1222                         Py_Return;
1223                 }
1224         
1225                 MT_Quaternion quat;
1226                 if (PyVecTo(pylist, quat))
1227                 {
1228                         matrix.setRotation(quat);
1229                         NodeSetLocalOrientation(matrix);
1230                         NodeUpdateGS(0.f,true);
1231                         Py_Return;
1232                 }
1233         }
1234         return NULL;
1235 }
1236
1237
1238
1239 PyObject* KX_GameObject::PySetPosition(PyObject* self, 
1240                                                                            PyObject* args, 
1241                                                                            PyObject* kwds)
1242 {
1243         MT_Point3 pos;
1244         if (PyVecArgTo(args, pos))
1245         {
1246                 NodeSetLocalPosition(pos);
1247                 NodeUpdateGS(0.f,true);
1248                 Py_Return;
1249         }
1250         
1251         return NULL;
1252 }
1253
1254 PyObject* KX_GameObject::PyGetPhysicsId(PyObject* self,
1255                                                                                            PyObject* args,
1256                                                                                            PyObject* kwds)
1257 {
1258         KX_IPhysicsController* ctrl = GetPhysicsController();
1259         uint_ptr physid=0;
1260         if (ctrl)
1261         {
1262                 physid= (uint_ptr)ctrl->GetUserData();
1263         }
1264         return PyInt_FromLong((long)physid);
1265 }
1266
1267 KX_PYMETHODDEF_DOC(KX_GameObject, getDistanceTo,
1268 "getDistanceTo(other): get distance to another point/KX_GameObject")
1269 {
1270         MT_Point3 b;
1271         if (PyVecArgTo(args, b))
1272         {
1273                 return PyFloat_FromDouble(NodeGetWorldPosition().distance(b));
1274         }
1275         PyErr_Clear();
1276         
1277         PyObject *pyother;
1278         if (PyArg_ParseTuple(args, "O!", &KX_GameObject::Type, &pyother))
1279         {
1280                 KX_GameObject *other = static_cast<KX_GameObject*>(pyother);
1281                 return PyFloat_FromDouble(NodeGetWorldPosition().distance(other->NodeGetWorldPosition()));
1282         }
1283         
1284         return NULL;
1285 }
1286
1287 bool KX_GameObject::RayHit(KX_ClientObjectInfo* client, MT_Point3& hit_point, MT_Vector3& hit_normal, void * const data)
1288 {
1289
1290         KX_GameObject* hitKXObj = client->m_gameobject;
1291         
1292         if (client->m_type > KX_ClientObjectInfo::ACTOR)
1293         {
1294                 // false hit
1295                 return false;
1296         }
1297
1298         if (m_testPropName.Length() == 0 || hitKXObj->GetProperty(m_testPropName) != NULL)
1299         {
1300                 m_pHitObject = hitKXObj;
1301                 return true;
1302         }
1303
1304         return false;
1305         
1306 }
1307
1308 KX_PYMETHODDEF_DOC(KX_GameObject, rayCastTo,
1309 "rayCastTo(other,dist,prop): look towards another point/KX_GameObject and return first object hit within dist that match prop\n"
1310 " prop = property name that object must have; can be omitted => detect any object\n"
1311 " dist = max distance to look (can be negative => look behind); 0 or omitted => detect up to other\n"
1312 " other = 3-tuple or object reference")
1313 {
1314         MT_Point3 toPoint;
1315         PyObject* pyarg;
1316         float dist = 0.0f;
1317         char *propName = NULL;
1318
1319         if (!PyArg_ParseTuple(args,"O|fs", &pyarg, &dist, &propName))
1320                 return NULL;
1321
1322         if (!PyVecTo(pyarg, toPoint))
1323         {
1324                 KX_GameObject *other;
1325                 PyErr_Clear();
1326                 if (!PyType_IsSubtype(pyarg->ob_type, &KX_GameObject::Type))
1327                         return NULL;
1328                 other = static_cast<KX_GameObject*>(pyarg);
1329                 toPoint = other->NodeGetWorldPosition();
1330         }
1331         MT_Point3 fromPoint = NodeGetWorldPosition();
1332         if (dist != 0.0f)
1333         {
1334                 MT_Vector3 toDir = toPoint-fromPoint;
1335                 toDir.normalize();
1336                 toPoint = fromPoint + (dist) * toDir;
1337         }
1338
1339         MT_Point3 resultPoint;
1340         MT_Vector3 resultNormal;
1341         PHY_IPhysicsEnvironment* pe = GetPhysicsEnvironment();
1342         KX_IPhysicsController *spc = GetPhysicsController();
1343         KX_GameObject *parent = GetParent();
1344         if (!spc && parent)
1345                 spc = parent->GetPhysicsController();
1346         if (parent)
1347                 parent->Release();
1348         
1349         m_pHitObject = NULL;
1350         if (propName)
1351                 m_testPropName = propName;
1352         else
1353                 m_testPropName.SetLength(0);
1354         KX_RayCast::RayTest(spc, pe, fromPoint, toPoint, resultPoint, resultNormal, KX_RayCast::Callback<KX_GameObject>(this));
1355
1356     if (m_pHitObject)
1357         {
1358                 m_pHitObject->AddRef();
1359                 return m_pHitObject;
1360         }
1361         Py_Return;
1362 }
1363
1364 /* --------------------------------------------------------------------- 
1365  * Some stuff taken from the header
1366  * --------------------------------------------------------------------- */
1367 void KX_GameObject::Relink(GEN_Map<GEN_HashedPtr, void*> *map_parameter)        
1368 {
1369         /* intentionally empty ? */
1370 }
1371