KX_MouseFocusSensor - bug reported by Micro27 on blenderartist
[blender.git] / source / gameengine / Ketsji / KX_MouseFocusSensor.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  * KX_MouseFocusSensor determines mouse in/out/over events.
29  */
30
31 #ifdef WIN32
32 // This warning tells us about truncation of __long__ stl-generated names.
33 // It can occasionally cause DevStudio to have internal compiler warnings.
34 #pragma warning( disable : 4786 )     
35 #endif
36
37 #include "MT_Point3.h"
38 #include "RAS_FramingManager.h"
39 #include "RAS_ICanvas.h"
40 #include "RAS_IRasterizer.h"
41 #include "SCA_IScene.h"
42 #include "KX_Scene.h"
43 #include "KX_Camera.h"
44 #include "KX_MouseFocusSensor.h"
45 #include "KX_PyMath.h"
46
47 #include "KX_RayCast.h"
48 #include "KX_IPhysicsController.h"
49 #include "PHY_IPhysicsController.h"
50 #include "PHY_IPhysicsEnvironment.h"
51
52
53 #include "KX_ClientObjectInfo.h"
54
55 /* ------------------------------------------------------------------------- */
56 /* Native functions                                                          */
57 /* ------------------------------------------------------------------------- */
58
59 KX_MouseFocusSensor::KX_MouseFocusSensor(SCA_MouseManager* eventmgr, 
60                                                                                  int startx,
61                                                                                  int starty,
62                                                                                  short int mousemode,
63                                                                                  int focusmode,
64                                                                                  KX_Scene* kxscene,
65                                                                                  KX_KetsjiEngine *kxengine,
66                                                                                  SCA_IObject* gameobj, 
67                                                                                  PyTypeObject* T)
68     : SCA_MouseSensor(eventmgr, startx, starty, mousemode, gameobj, T),
69           m_focusmode(focusmode),
70           m_kxscene(kxscene),
71           m_kxengine(kxengine)
72 {
73         Init();
74 }
75
76 void KX_MouseFocusSensor::Init()
77 {
78         m_mouse_over_in_previous_frame = (m_invert)?true:false;
79         m_positive_event = false;
80         m_hitObject = 0;
81         m_reset = true;
82         
83         m_hitPosition.setValue(0,0,0);
84         m_prevTargetPoint.setValue(0,0,0);
85         m_prevSourcePoint.setValue(0,0,0);
86         m_hitNormal.setValue(0,0,1);
87 }
88
89 bool KX_MouseFocusSensor::Evaluate()
90 {
91         bool result = false;
92         bool obHasFocus = false;
93         bool reset = m_reset && m_level;
94
95 //      cout << "evaluate focus mouse sensor "<<endl;
96         m_reset = false;
97         if (m_focusmode) {
98                 /* Focus behaviour required. Test mouse-on. The rest is
99                  * equivalent to handling a key. */
100                 obHasFocus = ParentObjectHasFocus();
101                 
102                 if (!obHasFocus) {
103                         m_positive_event = false;
104                         if (m_mouse_over_in_previous_frame) {
105                                 result = true;
106                         } 
107                 } else {
108                         m_positive_event = true;
109                         if (!m_mouse_over_in_previous_frame) {
110                                 result = true;
111                         } 
112                 } 
113                 if (reset) {
114                         // force an event 
115                         result = true;
116                 }
117         } else {
118                 /* No focus behaviour required: revert to the basic mode. This
119          * mode is never used, because the converter never makes this
120          * sensor for a mouse-key event. It is here for
121          * completeness. */
122                 result = SCA_MouseSensor::Evaluate();
123                 m_positive_event = (m_val!=0);
124         }
125
126         m_mouse_over_in_previous_frame = obHasFocus;
127
128         return result;
129 }
130
131 bool KX_MouseFocusSensor::RayHit(KX_ClientObjectInfo* client_info, KX_RayCast* result, void * const data)
132 {
133         KX_GameObject* hitKXObj = client_info->m_gameobject;
134         
135         /* Is this me? In the ray test, there are a lot of extra checks
136         * for aliasing artefacts from self-hits. That doesn't happen
137         * here, so a simple test suffices. Or does the camera also get
138         * self-hits? (No, and the raysensor shouldn't do it either, since
139         * self-hits are excluded by setting the correct ignore-object.)
140         * Hitspots now become valid. */
141         KX_GameObject* thisObj = (KX_GameObject*) GetParent();
142         if ((m_focusmode == 2) || hitKXObj == thisObj)
143         {
144                 m_hitObject = hitKXObj;
145                 m_hitPosition = result->m_hitPoint;
146                 m_hitNormal = result->m_hitNormal;
147                 return true;
148         }
149         
150         return true;     // object must be visible to trigger
151         //return false;  // occluded objects can trigger
152 }
153
154
155
156 bool KX_MouseFocusSensor::ParentObjectHasFocusCamera(KX_Camera *cam)
157 {
158         /* All screen handling in the gameengine is done by GL,
159          * specifically the model/view and projection parts. The viewport
160          * part is in the creator. 
161          *
162          * The theory is this:
163          * WCS - world coordinates
164          * -> wcs_camcs_trafo ->
165          * camCS - camera coordinates
166          * -> camcs_clip_trafo ->
167          * clipCS - normalized device coordinates?
168          * -> normview_win_trafo
169          * winCS - window coordinates
170          *
171          * The first two transforms are respectively the model/view and
172          * the projection matrix. These are passed to the rasterizer, and
173          * we store them in the camera for easy access.
174          *
175          * For normalized device coords (xn = x/w, yn = y/w/zw) the
176          * windows coords become (lb = left bottom)
177          *
178          * xwin = [(xn + 1.0) * width]/2 + x_lb
179          * ywin = [(yn + 1.0) * height]/2 + y_lb
180          *
181          * Inverting (blender y is flipped!):
182          *
183          * xn = 2(xwin - x_lb)/width - 1.0
184          * yn = 2(ywin - y_lb)/height - 1.0 
185          *    = 2(height - y_blender - y_lb)/height - 1.0
186          *    = 1.0 - 2(y_blender - y_lb)/height
187          *
188          * */
189          
190         
191         /* Because we don't want to worry about resize events, camera
192          * changes and all that crap, we just determine this over and
193          * over. Stop whining. We have lots of other calculations to do
194          * here as well. These reads are not the main cost. If there is no
195          * canvas, the test is irrelevant. The 1.0 makes sure the
196          * calculations don't bomb. Maybe we should explicitly guard for
197          * division by 0.0...*/
198         
199         RAS_Rect area, viewport;
200         short m_y_inv = m_kxengine->GetCanvas()->GetHeight()-m_y;
201         
202         m_kxengine->GetSceneViewport(m_kxscene, cam, area, viewport);
203         
204         /* Check if the mouse is in the viewport */
205         if ((   m_x < viewport.m_x2 &&  // less then right
206                         m_x > viewport.m_x1 &&  // more then then left
207                         m_y_inv < viewport.m_y2 &&      // below top
208                         m_y_inv > viewport.m_y1) == 0)  // above bottom
209         {
210                 return false;
211         }
212
213         float height = float(viewport.m_y2 - viewport.m_y1 + 1);
214         float width  = float(viewport.m_x2 - viewport.m_x1 + 1);
215         
216         float x_lb = float(viewport.m_x1);
217         float y_lb = float(viewport.m_y1);
218
219         MT_Vector4 frompoint;
220         MT_Vector4 topoint;
221         
222         /* m_y_inv - inverting for a bounds check is only part of it, now make relative to view bounds */
223         m_y_inv = (viewport.m_y2 - m_y_inv) + viewport.m_y1;
224         
225         
226         /* There's some strangeness I don't fully get here... These values
227          * _should_ be wrong! - see from point Z values */
228         
229         
230         /*      build the from and to point in normalized device coordinates 
231          *      Looks like normailized device coordinates are [-1,1] in x [-1,1] in y
232          *      [0,-1] in z 
233          *      
234          *      The actual z coordinates used don't have to be exact just infront and 
235          *      behind of the near and far clip planes.
236          */ 
237         frompoint.setValue(     (2 * (m_x-x_lb) / width) - 1.0,
238                                                 1.0 - (2 * (m_y_inv - y_lb) / height),
239                                                 /*cam->GetCameraData()->m_perspective ? 0.0:cdata->m_clipstart,*/ /* real clipstart is scaled in ortho for some reason, zero is ok */
240                                                 0.0, /* nearclip, see above comments */
241                                                 1.0 );
242         
243         topoint.setValue(       (2 * (m_x-x_lb) / width) - 1.0,
244                                                 1.0 - (2 * (m_y_inv-y_lb) / height),
245                                                 cam->GetCameraData()->m_perspective ? 1.0:cam->GetCameraData()->m_clipend, /* farclip, see above comments */
246                                                 1.0 );
247
248         /* camera to world  */
249         MT_Transform wcs_camcs_tranform = cam->GetWorldToCamera();
250         MT_Transform cams_wcs_transform;
251         cams_wcs_transform.invert(wcs_camcs_tranform);
252         
253         MT_Matrix4x4 camcs_wcs_matrix = MT_Matrix4x4(cams_wcs_transform);
254
255         /* badly defined, the first time round.... I wonder why... I might
256          * want to guard against floating point errors here.*/
257         MT_Matrix4x4 clip_camcs_matrix = MT_Matrix4x4(cam->GetProjectionMatrix());
258         clip_camcs_matrix.invert();
259
260         /* shoot-points: clip to cam to wcs . win to clip was already done.*/
261         frompoint = clip_camcs_matrix * frompoint;
262         topoint   = clip_camcs_matrix * topoint;
263         frompoint = camcs_wcs_matrix * frompoint;
264         topoint   = camcs_wcs_matrix * topoint;
265         
266         /* from hom wcs to 3d wcs: */
267         m_prevSourcePoint.setValue(     frompoint[0]/frompoint[3],
268                                                                 frompoint[1]/frompoint[3],
269                                                                 frompoint[2]/frompoint[3]); 
270         
271         m_prevTargetPoint.setValue(     topoint[0]/topoint[3],
272                                                                 topoint[1]/topoint[3],
273                                                                 topoint[2]/topoint[3]); 
274         
275         /* 2. Get the object from PhysicsEnvironment */
276         /* Shoot! Beware that the first argument here is an
277          * ignore-object. We don't ignore anything... */
278         KX_IPhysicsController* physics_controller = cam->GetPhysicsController();
279         PHY_IPhysicsEnvironment* physics_environment = m_kxscene->GetPhysicsEnvironment();
280
281         KX_RayCast::Callback<KX_MouseFocusSensor> callback(this,physics_controller);
282          
283         KX_RayCast::RayTest(physics_environment, m_prevSourcePoint, m_prevTargetPoint, callback);
284         
285         if (m_hitObject)
286                 return true;
287         
288         return false;
289 }
290
291 bool KX_MouseFocusSensor::ParentObjectHasFocus()
292 {
293         m_hitObject = 0;
294         m_hitPosition.setValue(0,0,0);
295         m_hitNormal.setValue(1,0,0);
296         
297         KX_Camera *cam= m_kxscene->GetActiveCamera();
298         
299         if(ParentObjectHasFocusCamera(cam))
300                 return true;
301
302         list<class KX_Camera*>* cameras = m_kxscene->GetCameras();
303         list<KX_Camera*>::iterator it = cameras->begin();
304         
305         while(it != cameras->end())
306         {
307                 if(((*it) != cam) && (*it)->GetViewport())
308                         if (ParentObjectHasFocusCamera(*it))
309                                 return true;
310                 
311                 it++;
312         }
313         
314         return false;
315 }
316
317 const MT_Point3& KX_MouseFocusSensor::RaySource() const
318 {
319         return m_prevSourcePoint;
320 }
321
322 const MT_Point3& KX_MouseFocusSensor::RayTarget() const
323 {
324         return m_prevTargetPoint;
325 }
326
327 const MT_Point3& KX_MouseFocusSensor::HitPosition() const
328 {
329         return m_hitPosition;
330 }
331
332 const MT_Vector3& KX_MouseFocusSensor::HitNormal() const
333 {
334         return m_hitNormal;
335 }
336
337 /* ------------------------------------------------------------------------- */
338 /* Python functions                                                          */
339 /* ------------------------------------------------------------------------- */
340
341 /* Integration hooks ------------------------------------------------------- */
342 PyTypeObject KX_MouseFocusSensor::Type = {
343 #if (PY_VERSION_HEX >= 0x02060000)
344         PyVarObject_HEAD_INIT(NULL, 0)
345 #else
346         /* python 2.5 and below */
347         PyObject_HEAD_INIT( NULL )  /* required py macro */
348         0,                          /* ob_size */
349 #endif
350         "KX_MouseFocusSensor",
351         sizeof(PyObjectPlus_Proxy),
352         0,
353         py_base_dealloc,
354         0,
355         0,
356         0,
357         0,
358         py_base_repr,
359         0,0,0,0,0,0,
360         py_base_getattro,
361         py_base_setattro,
362         0,0,0,0,0,0,0,0,0,
363         Methods
364 };
365
366 PyParentObject KX_MouseFocusSensor::Parents[] = {
367         &KX_MouseFocusSensor::Type,
368         &SCA_MouseSensor::Type,
369         &SCA_ISensor::Type,
370         &SCA_ILogicBrick::Type,
371         &CValue::Type,
372         NULL
373 };
374
375 PyMethodDef KX_MouseFocusSensor::Methods[] = {
376         {"getRayTarget", (PyCFunction) KX_MouseFocusSensor::sPyGetRayTarget, METH_NOARGS, (PY_METHODCHAR)GetRayTarget_doc},
377         {"getRaySource", (PyCFunction) KX_MouseFocusSensor::sPyGetRaySource, METH_NOARGS, (PY_METHODCHAR)GetRaySource_doc},
378         {"getHitObject",(PyCFunction) KX_MouseFocusSensor::sPyGetHitObject,METH_NOARGS, (PY_METHODCHAR)GetHitObject_doc},
379         {"getHitPosition",(PyCFunction) KX_MouseFocusSensor::sPyGetHitPosition,METH_NOARGS, (PY_METHODCHAR)GetHitPosition_doc},
380         {"getHitNormal",(PyCFunction) KX_MouseFocusSensor::sPyGetHitNormal,METH_NOARGS, (PY_METHODCHAR)GetHitNormal_doc},
381         {"getRayDirection",(PyCFunction) KX_MouseFocusSensor::sPyGetRayDirection,METH_NOARGS, (PY_METHODCHAR)GetRayDirection_doc},
382
383         {NULL,NULL} //Sentinel
384 };
385
386 PyAttributeDef KX_MouseFocusSensor::Attributes[] = {
387         KX_PYATTRIBUTE_RO_FUNCTION("raySource",         KX_MouseFocusSensor, pyattr_get_ray_source),
388         KX_PYATTRIBUTE_RO_FUNCTION("rayTarget",         KX_MouseFocusSensor, pyattr_get_ray_target),
389         KX_PYATTRIBUTE_RO_FUNCTION("rayDirection",      KX_MouseFocusSensor, pyattr_get_ray_direction),
390         KX_PYATTRIBUTE_RO_FUNCTION("hitObject",         KX_MouseFocusSensor, pyattr_get_hit_object),
391         KX_PYATTRIBUTE_RO_FUNCTION("hitPosition",       KX_MouseFocusSensor, pyattr_get_hit_position),
392         KX_PYATTRIBUTE_RO_FUNCTION("hitNormal",         KX_MouseFocusSensor, pyattr_get_hit_normal),
393         { NULL }        //Sentinel
394 };
395
396 PyObject* KX_MouseFocusSensor::py_getattro(PyObject *attr) {
397         py_getattro_up(SCA_MouseSensor);
398 }
399
400 PyObject* KX_MouseFocusSensor::py_getattro_dict() {
401         py_getattro_dict_up(SCA_MouseSensor);
402 }
403
404
405 const char KX_MouseFocusSensor::GetHitObject_doc[] = 
406 "getHitObject()\n"
407 "\tReturns the object that was hit by this ray.\n";
408 PyObject* KX_MouseFocusSensor::PyGetHitObject()
409 {
410         ShowDeprecationWarning("GetHitObject()", "the hitObject property");
411         
412         if (m_hitObject)
413                 return m_hitObject->GetProxy();
414         
415         Py_RETURN_NONE;
416 }
417
418
419 const char KX_MouseFocusSensor::GetHitPosition_doc[] = 
420 "getHitPosition()\n"
421 "\tReturns the position (in worldcoordinates) where the object was hit by this ray.\n";
422 PyObject* KX_MouseFocusSensor::PyGetHitPosition()
423 {
424         ShowDeprecationWarning("getHitPosition()", "the hitPosition property");
425         
426         return PyObjectFrom(m_hitPosition);
427 }
428
429 const char KX_MouseFocusSensor::GetRayDirection_doc[] = 
430 "getRayDirection()\n"
431 "\tReturns the direction from the ray (in worldcoordinates) .\n";
432 PyObject* KX_MouseFocusSensor::PyGetRayDirection()
433 {
434         ShowDeprecationWarning("getRayDirection()", "the rayDirection property");
435         
436         MT_Vector3 dir = m_prevTargetPoint - m_prevSourcePoint;
437         if(MT_fuzzyZero(dir))   dir.setValue(0,0,0);
438         else                                    dir.normalize();
439         return PyObjectFrom(dir);
440 }
441
442 const char KX_MouseFocusSensor::GetHitNormal_doc[] = 
443 "getHitNormal()\n"
444 "\tReturns the normal (in worldcoordinates) at the point of collision where the object was hit by this ray.\n";
445 PyObject* KX_MouseFocusSensor::PyGetHitNormal()
446 {
447         ShowDeprecationWarning("getHitNormal()", "the hitNormal property");
448         
449         return PyObjectFrom(m_hitNormal);
450 }
451
452
453 /*  getRayTarget                                                */
454 const char KX_MouseFocusSensor::GetRayTarget_doc[] = 
455 "getRayTarget()\n"
456 "\tReturns the target of the ray that seeks the focus object,\n"
457 "\tin worldcoordinates.";
458 PyObject* KX_MouseFocusSensor::PyGetRayTarget()
459 {
460         ShowDeprecationWarning("getRayTarget()", "the rayTarget property");
461         
462         return PyObjectFrom(m_prevTargetPoint);
463 }
464
465 /*  getRayTarget                                                */
466 const char KX_MouseFocusSensor::GetRaySource_doc[] = 
467 "getRaySource()\n"
468 "\tReturns the source of the ray that seeks the focus object,\n"
469 "\tin worldcoordinates.";
470 PyObject* KX_MouseFocusSensor::PyGetRaySource()
471 {
472         ShowDeprecationWarning("getRaySource()", "the raySource property");
473         
474         return PyObjectFrom(m_prevSourcePoint);
475 }
476
477 /* Attributes */
478 PyObject* KX_MouseFocusSensor::pyattr_get_ray_source(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
479 {
480         KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
481         return PyObjectFrom(self->RaySource());
482 }
483
484 PyObject* KX_MouseFocusSensor::pyattr_get_ray_target(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
485 {
486         KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
487         return PyObjectFrom(self->RayTarget());
488 }
489
490 PyObject* KX_MouseFocusSensor::pyattr_get_ray_direction(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
491 {
492         KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
493         MT_Vector3 dir = self->RayTarget() - self->RaySource();
494         if(MT_fuzzyZero(dir))   dir.setValue(0,0,0);
495         else                                    dir.normalize();
496         return PyObjectFrom(dir);
497 }
498
499 PyObject* KX_MouseFocusSensor::pyattr_get_hit_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
500 {
501         KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
502         
503         if(self->m_hitObject)
504                 return self->m_hitObject->GetProxy();
505         
506         Py_RETURN_NONE;
507 }
508
509 PyObject* KX_MouseFocusSensor::pyattr_get_hit_position(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
510 {
511         KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
512         return PyObjectFrom(self->HitPosition());
513 }
514
515 PyObject* KX_MouseFocusSensor::pyattr_get_hit_normal(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
516 {
517         KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
518         return PyObjectFrom(self->HitNormal());
519 }
520
521
522
523 /* eof */
524