[#18681] Mousesensor Over doesn't work in ortho mode of 3dview camera
[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(CValue* event)
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(event);
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         m_kxengine->GetSceneViewport(m_kxscene, cam, area, viewport);
201         
202         /* Check if the mouse is in the viewport */
203         if ((   m_x < viewport.m_x2 &&  // less then right
204                         m_x > viewport.m_x1 &&  // more then then left
205                         m_y < viewport.m_y2 &&  // below top
206                         m_y > viewport.m_y1) == 0)      // above bottom
207         {
208                 return false;
209         }
210
211         float height = float(viewport.m_y2 - viewport.m_y1 + 1);
212         float width  = float(viewport.m_x2 - viewport.m_x1 + 1);
213         
214         float x_lb = float(viewport.m_x1);
215         float y_lb = float(viewport.m_y1);
216
217         MT_Vector4 frompoint;
218         MT_Vector4 topoint;
219         
220         /* There's some strangeness I don't fully get here... These values
221          * _should_ be wrong! - see from point Z values */
222         
223         
224         /*      build the from and to point in normalized device coordinates 
225          *      Looks like normailized device coordinates are [-1,1] in x [-1,1] in y
226          *      [0,-1] in z 
227          *      
228          *      The actual z coordinates used don't have to be exact just infront and 
229          *      behind of the near and far clip planes.
230          */ 
231         frompoint.setValue(     (2 * (m_x-x_lb) / width) - 1.0,
232                                                 1.0 - (2 * (m_y - y_lb) / height),
233                                                 /*cam->GetCameraData()->m_perspective ? 0.0:cdata->m_clipstart,*/ /* real clipstart is scaled in ortho for some reason, zero is ok */
234                                                 0.0, /* nearclip, see above comments */
235                                                 1.0 );
236         
237         topoint.setValue(       (2 * (m_x-x_lb) / width) - 1.0,
238                                                 1.0 - (2 * (m_y-y_lb) / height),
239                                                 cam->GetCameraData()->m_perspective ? 1.0:cam->GetCameraData()->m_clipend, /* farclip, see above comments */
240                                                 1.0 );
241
242         /* camera to world  */
243         MT_Transform wcs_camcs_tranform = cam->GetWorldToCamera();
244         MT_Transform cams_wcs_transform;
245         cams_wcs_transform.invert(wcs_camcs_tranform);
246         
247         MT_Matrix4x4 camcs_wcs_matrix = MT_Matrix4x4(cams_wcs_transform);
248
249         /* badly defined, the first time round.... I wonder why... I might
250          * want to guard against floating point errors here.*/
251         MT_Matrix4x4 clip_camcs_matrix = MT_Matrix4x4(cam->GetProjectionMatrix());
252         clip_camcs_matrix.invert();
253
254         /* shoot-points: clip to cam to wcs . win to clip was already done.*/
255         frompoint = clip_camcs_matrix * frompoint;
256         topoint   = clip_camcs_matrix * topoint;
257         frompoint = camcs_wcs_matrix * frompoint;
258         topoint   = camcs_wcs_matrix * topoint;
259         
260         /* from hom wcs to 3d wcs: */
261         m_prevSourcePoint.setValue(     frompoint[0]/frompoint[3],
262                                                                 frompoint[1]/frompoint[3],
263                                                                 frompoint[2]/frompoint[3]); 
264         
265         m_prevTargetPoint.setValue(     topoint[0]/topoint[3],
266                                                                 topoint[1]/topoint[3],
267                                                                 topoint[2]/topoint[3]); 
268         
269         /* 2. Get the object from PhysicsEnvironment */
270         /* Shoot! Beware that the first argument here is an
271          * ignore-object. We don't ignore anything... */
272         KX_IPhysicsController* physics_controller = cam->GetPhysicsController();
273         PHY_IPhysicsEnvironment* physics_environment = m_kxscene->GetPhysicsEnvironment();
274
275         KX_RayCast::Callback<KX_MouseFocusSensor> callback(this,physics_controller);
276          
277         KX_RayCast::RayTest(physics_environment, m_prevSourcePoint, m_prevTargetPoint, callback);
278         
279         if (m_hitObject)
280                 return true;
281         
282         return false;
283 }
284
285 bool KX_MouseFocusSensor::ParentObjectHasFocus()
286 {
287         m_hitObject = 0;
288         m_hitPosition.setValue(0,0,0);
289         m_hitNormal.setValue(1,0,0);
290         
291         KX_Camera *cam= m_kxscene->GetActiveCamera();
292         
293         if(ParentObjectHasFocusCamera(cam))
294                 return true;
295
296         list<class KX_Camera*>* cameras = m_kxscene->GetCameras();
297         list<KX_Camera*>::iterator it = cameras->begin();
298         
299         while(it != cameras->end())
300         {
301                 if(((*it) != cam) && (*it)->GetViewport())
302                         if (ParentObjectHasFocusCamera(*it))
303                                 return true;
304                 
305                 it++;
306         }
307         
308         return false;
309 }
310
311 const MT_Point3& KX_MouseFocusSensor::RaySource() const
312 {
313         return m_prevSourcePoint;
314 }
315
316 const MT_Point3& KX_MouseFocusSensor::RayTarget() const
317 {
318         return m_prevTargetPoint;
319 }
320
321 const MT_Point3& KX_MouseFocusSensor::HitPosition() const
322 {
323         return m_hitPosition;
324 }
325
326 const MT_Vector3& KX_MouseFocusSensor::HitNormal() const
327 {
328         return m_hitNormal;
329 }
330
331 /* ------------------------------------------------------------------------- */
332 /* Python functions                                                          */
333 /* ------------------------------------------------------------------------- */
334
335 /* Integration hooks ------------------------------------------------------- */
336 PyTypeObject KX_MouseFocusSensor::Type = {
337 #if (PY_VERSION_HEX >= 0x02060000)
338         PyVarObject_HEAD_INIT(NULL, 0)
339 #else
340         /* python 2.5 and below */
341         PyObject_HEAD_INIT( NULL )  /* required py macro */
342         0,                          /* ob_size */
343 #endif
344         "KX_MouseFocusSensor",
345         sizeof(PyObjectPlus_Proxy),
346         0,
347         py_base_dealloc,
348         0,
349         0,
350         0,
351         0,
352         py_base_repr,
353         0,0,0,0,0,0,
354         py_base_getattro,
355         py_base_setattro,
356         0,0,0,0,0,0,0,0,0,
357         Methods
358 };
359
360 PyParentObject KX_MouseFocusSensor::Parents[] = {
361         &KX_MouseFocusSensor::Type,
362         &SCA_MouseSensor::Type,
363         &SCA_ISensor::Type,
364         &SCA_ILogicBrick::Type,
365         &CValue::Type,
366         NULL
367 };
368
369 PyMethodDef KX_MouseFocusSensor::Methods[] = {
370         {"getRayTarget", (PyCFunction) KX_MouseFocusSensor::sPyGetRayTarget, METH_NOARGS, (PY_METHODCHAR)GetRayTarget_doc},
371         {"getRaySource", (PyCFunction) KX_MouseFocusSensor::sPyGetRaySource, METH_NOARGS, (PY_METHODCHAR)GetRaySource_doc},
372         {"getHitObject",(PyCFunction) KX_MouseFocusSensor::sPyGetHitObject,METH_NOARGS, (PY_METHODCHAR)GetHitObject_doc},
373         {"getHitPosition",(PyCFunction) KX_MouseFocusSensor::sPyGetHitPosition,METH_NOARGS, (PY_METHODCHAR)GetHitPosition_doc},
374         {"getHitNormal",(PyCFunction) KX_MouseFocusSensor::sPyGetHitNormal,METH_NOARGS, (PY_METHODCHAR)GetHitNormal_doc},
375         {"getRayDirection",(PyCFunction) KX_MouseFocusSensor::sPyGetRayDirection,METH_NOARGS, (PY_METHODCHAR)GetRayDirection_doc},
376
377         {NULL,NULL} //Sentinel
378 };
379
380 PyAttributeDef KX_MouseFocusSensor::Attributes[] = {
381         KX_PYATTRIBUTE_RO_FUNCTION("raySource",         KX_MouseFocusSensor, pyattr_get_ray_source),
382         KX_PYATTRIBUTE_RO_FUNCTION("rayTarget",         KX_MouseFocusSensor, pyattr_get_ray_target),
383         KX_PYATTRIBUTE_RO_FUNCTION("rayDirection",      KX_MouseFocusSensor, pyattr_get_ray_direction),
384         KX_PYATTRIBUTE_RO_FUNCTION("hitObject",         KX_MouseFocusSensor, pyattr_get_hit_object),
385         KX_PYATTRIBUTE_RO_FUNCTION("hitPosition",       KX_MouseFocusSensor, pyattr_get_hit_position),
386         KX_PYATTRIBUTE_RO_FUNCTION("hitNormal",         KX_MouseFocusSensor, pyattr_get_hit_normal),
387         { NULL }        //Sentinel
388 };
389
390 PyObject* KX_MouseFocusSensor::py_getattro(PyObject *attr) {
391         py_getattro_up(SCA_MouseSensor);
392 }
393
394 PyObject* KX_MouseFocusSensor::py_getattro_dict() {
395         py_getattro_dict_up(SCA_MouseSensor);
396 }
397
398
399 const char KX_MouseFocusSensor::GetHitObject_doc[] = 
400 "getHitObject()\n"
401 "\tReturns the object that was hit by this ray.\n";
402 PyObject* KX_MouseFocusSensor::PyGetHitObject()
403 {
404         ShowDeprecationWarning("GetHitObject()", "the hitObject property");
405         
406         if (m_hitObject)
407                 return m_hitObject->GetProxy();
408         
409         Py_RETURN_NONE;
410 }
411
412
413 const char KX_MouseFocusSensor::GetHitPosition_doc[] = 
414 "getHitPosition()\n"
415 "\tReturns the position (in worldcoordinates) where the object was hit by this ray.\n";
416 PyObject* KX_MouseFocusSensor::PyGetHitPosition()
417 {
418         ShowDeprecationWarning("getHitPosition()", "the hitPosition property");
419         
420         return PyObjectFrom(m_hitPosition);
421 }
422
423 const char KX_MouseFocusSensor::GetRayDirection_doc[] = 
424 "getRayDirection()\n"
425 "\tReturns the direction from the ray (in worldcoordinates) .\n";
426 PyObject* KX_MouseFocusSensor::PyGetRayDirection()
427 {
428         ShowDeprecationWarning("getRayDirection()", "the rayDirection property");
429         
430         MT_Vector3 dir = m_prevTargetPoint - m_prevSourcePoint;
431         if(MT_fuzzyZero(dir))   dir.setValue(0,0,0);
432         else                                    dir.normalize();
433         return PyObjectFrom(dir);
434 }
435
436 const char KX_MouseFocusSensor::GetHitNormal_doc[] = 
437 "getHitNormal()\n"
438 "\tReturns the normal (in worldcoordinates) at the point of collision where the object was hit by this ray.\n";
439 PyObject* KX_MouseFocusSensor::PyGetHitNormal()
440 {
441         ShowDeprecationWarning("getHitNormal()", "the hitNormal property");
442         
443         return PyObjectFrom(m_hitNormal);
444 }
445
446
447 /*  getRayTarget                                                */
448 const char KX_MouseFocusSensor::GetRayTarget_doc[] = 
449 "getRayTarget()\n"
450 "\tReturns the target of the ray that seeks the focus object,\n"
451 "\tin worldcoordinates.";
452 PyObject* KX_MouseFocusSensor::PyGetRayTarget()
453 {
454         ShowDeprecationWarning("getRayTarget()", "the rayTarget property");
455         
456         return PyObjectFrom(m_prevTargetPoint);
457 }
458
459 /*  getRayTarget                                                */
460 const char KX_MouseFocusSensor::GetRaySource_doc[] = 
461 "getRaySource()\n"
462 "\tReturns the source of the ray that seeks the focus object,\n"
463 "\tin worldcoordinates.";
464 PyObject* KX_MouseFocusSensor::PyGetRaySource()
465 {
466         ShowDeprecationWarning("getRaySource()", "the raySource property");
467         
468         return PyObjectFrom(m_prevSourcePoint);
469 }
470
471 /* Attributes */
472 PyObject* KX_MouseFocusSensor::pyattr_get_ray_source(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
473 {
474         KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
475         return PyObjectFrom(self->RaySource());
476 }
477
478 PyObject* KX_MouseFocusSensor::pyattr_get_ray_target(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
479 {
480         KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
481         return PyObjectFrom(self->RayTarget());
482 }
483
484 PyObject* KX_MouseFocusSensor::pyattr_get_ray_direction(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
485 {
486         KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
487         MT_Vector3 dir = self->RayTarget() - self->RaySource();
488         if(MT_fuzzyZero(dir))   dir.setValue(0,0,0);
489         else                                    dir.normalize();
490         return PyObjectFrom(dir);
491 }
492
493 PyObject* KX_MouseFocusSensor::pyattr_get_hit_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
494 {
495         KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
496         
497         if(self->m_hitObject)
498                 return self->m_hitObject->GetProxy();
499         
500         Py_RETURN_NONE;
501 }
502
503 PyObject* KX_MouseFocusSensor::pyattr_get_hit_position(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
504 {
505         KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
506         return PyObjectFrom(self->HitPosition());
507 }
508
509 PyObject* KX_MouseFocusSensor::pyattr_get_hit_normal(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
510 {
511         KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
512         return PyObjectFrom(self->HitNormal());
513 }
514
515
516
517 /* eof */
518