Merge from trunk
[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
46 #include "KX_RayCast.h"
47 #include "KX_IPhysicsController.h"
48 #include "PHY_IPhysicsController.h"
49 #include "PHY_IPhysicsEnvironment.h"
50
51
52 #include "KX_ClientObjectInfo.h"
53
54 /* ------------------------------------------------------------------------- */
55 /* Native functions                                                          */
56 /* ------------------------------------------------------------------------- */
57
58 KX_MouseFocusSensor::KX_MouseFocusSensor(SCA_MouseManager* eventmgr, 
59                                                                                  int startx,
60                                                                                  int starty,
61                                                                                  short int mousemode,
62                                                                                  int focusmode,
63                                                                                  RAS_ICanvas* canvas,
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_gp_canvas(canvas),
71           m_kxscene(kxscene),
72           m_kxengine(kxengine)
73 {
74         Init();
75 }
76
77 void KX_MouseFocusSensor::Init()
78 {
79         m_mouse_over_in_previous_frame = (m_invert)?true:false;
80         m_positive_event = false;
81         m_hitObject = 0;
82         m_reset = true;
83 }
84
85 bool KX_MouseFocusSensor::Evaluate(CValue* event)
86 {
87         bool result = false;
88         bool obHasFocus = false;
89         bool reset = m_reset && m_level;
90
91 //      cout << "evaluate focus mouse sensor "<<endl;
92         m_reset = false;
93         if (m_focusmode) {
94                 /* Focus behaviour required. Test mouse-on. The rest is
95                  * equivalent to handling a key. */
96                 obHasFocus = ParentObjectHasFocus();
97                 
98                 if (!obHasFocus) {
99                         m_positive_event = false;
100                         if (m_mouse_over_in_previous_frame) {
101                                 result = true;
102                         } 
103                 } else {
104                         m_positive_event = true;
105                         if (!m_mouse_over_in_previous_frame) {
106                                 result = true;
107                         } 
108                 } 
109                 if (reset) {
110                         // force an event 
111                         result = true;
112                 }
113         } else {
114                 /* No focus behaviour required: revert to the basic mode. This
115          * mode is never used, because the converter never makes this
116          * sensor for a mouse-key event. It is here for
117          * completeness. */
118                 result = SCA_MouseSensor::Evaluate(event);
119                 m_positive_event = (m_val!=0);
120         }
121
122         m_mouse_over_in_previous_frame = obHasFocus;
123
124         return result;
125 }
126
127 bool KX_MouseFocusSensor::RayHit(KX_ClientObjectInfo* client_info, KX_RayCast* result, void * const data)
128 {
129         KX_GameObject* hitKXObj = client_info->m_gameobject;
130         
131         /* Is this me? In the ray test, there are a lot of extra checks
132         * for aliasing artefacts from self-hits. That doesn't happen
133         * here, so a simple test suffices. Or does the camera also get
134         * self-hits? (No, and the raysensor shouldn't do it either, since
135         * self-hits are excluded by setting the correct ignore-object.)
136         * Hitspots now become valid. */
137         KX_GameObject* thisObj = (KX_GameObject*) GetParent();
138         if ((m_focusmode == 2) || hitKXObj == thisObj)
139         {
140                 m_hitObject = hitKXObj;
141                 m_hitPosition = result->m_hitPoint;
142                 m_hitNormal = result->m_hitNormal;
143                 return true;
144         }
145         
146         return true;     // object must be visible to trigger
147         //return false;  // occluded objects can trigger
148 }
149
150
151
152 bool KX_MouseFocusSensor::ParentObjectHasFocus(void)
153 {
154         m_hitObject = 0;
155         m_hitPosition = MT_Vector3(0,0,0);
156         m_hitNormal =   MT_Vector3(1,0,0);
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         /* Because we don't want to worry about resize events, camera
191          * changes and all that crap, we just determine this over and
192          * over. Stop whining. We have lots of other calculations to do
193          * here as well. These reads are not the main cost. If there is no
194          * canvas, the test is irrelevant. The 1.0 makes sure the
195          * calculations don't bomb. Maybe we should explicitly guard for
196          * division by 0.0...*/
197
198         KX_Camera* cam = m_kxscene->GetActiveCamera();
199
200         /* get the scenes current viewport. we recompute it because there
201          * may be multiple cameras and m_kxscene->GetSceneViewport() only
202          * has the one that was last drawn */
203
204         RAS_Rect area, viewport;
205         m_kxengine->GetSceneViewport(m_kxscene, cam, area, viewport);
206
207         float height = float(viewport.m_y2 - viewport.m_y1 + 1);
208         float width  = float(viewport.m_x2 - viewport.m_x1 + 1);
209         
210         float x_lb = float(viewport.m_x1);
211         float y_lb = float(viewport.m_y1);
212
213         /* There's some strangeness I don't fully get here... These values
214          * _should_ be wrong! */
215         
216
217         /* old: */
218         float nearclip = 0.0;
219         float farclip = 1.0;
220
221         /*      build the from and to point in normalized device coordinates 
222          *      Looks like normailized device coordinates are [-1,1] in x [-1,1] in y
223          *      [0,-1] in z 
224          *      
225          *      The actual z coordinates used don't have to be exact just infront and 
226          *      behind of the near and far clip planes.
227          */ 
228         MT_Vector4 frompoint = MT_Vector4( 
229                 (2 * (m_x-x_lb) / width) - 1.0,
230                 1.0 - (2 * (m_y - y_lb) / height),
231                 nearclip,
232                 1.0
233         );
234         MT_Vector4 topoint = MT_Vector4( 
235                 (2 * (m_x-x_lb) / width) - 1.0,
236                 1.0 - (2 * (m_y-y_lb) / height),
237                 farclip,
238                 1.0
239         );
240
241         /* camera to world  */
242         MT_Transform wcs_camcs_tranform = cam->GetWorldToCamera();
243         if (!cam->GetCameraData()->m_perspective)
244                 wcs_camcs_tranform.getOrigin()[2] *= 100.0;
245         MT_Transform cams_wcs_transform;
246         cams_wcs_transform.invert(wcs_camcs_tranform);
247         
248         MT_Matrix4x4 camcs_wcs_matrix = MT_Matrix4x4(cams_wcs_transform);
249
250         /* badly defined, the first time round.... I wonder why... I might
251          * want to guard against floating point errors here.*/
252         MT_Matrix4x4 clip_camcs_matrix = MT_Matrix4x4(cam->GetProjectionMatrix());
253         clip_camcs_matrix.invert();
254
255         /* shoot-points: clip to cam to wcs . win to clip was already done.*/
256         frompoint = clip_camcs_matrix * frompoint;
257         topoint   = clip_camcs_matrix * topoint;
258         frompoint = camcs_wcs_matrix * frompoint;
259         topoint   = camcs_wcs_matrix * topoint;
260         
261         /* from hom wcs to 3d wcs: */
262         MT_Point3 frompoint3 = MT_Point3(frompoint[0]/frompoint[3], 
263                                                                          frompoint[1]/frompoint[3], 
264                                                                          frompoint[2]/frompoint[3]); 
265         MT_Point3 topoint3 = MT_Point3(topoint[0]/topoint[3], 
266                                                                    topoint[1]/topoint[3], 
267                                                                    topoint[2]/topoint[3]); 
268         m_prevTargetPoint = topoint3;
269         m_prevSourcePoint = frompoint3;
270         
271         /* 2. Get the object from PhysicsEnvironment */
272         /* Shoot! Beware that the first argument here is an
273          * ignore-object. We don't ignore anything... */
274         
275         KX_IPhysicsController* physics_controller = cam->GetPhysicsController();
276         PHY_IPhysicsEnvironment* physics_environment = m_kxscene->GetPhysicsEnvironment();
277
278         bool result = false;
279
280         KX_RayCast::Callback<KX_MouseFocusSensor> callback(this,physics_controller);
281         KX_RayCast::RayTest(physics_environment, frompoint3, topoint3, callback);
282         
283         result = (m_hitObject!=0);
284
285         return result;
286
287 }
288
289 /* ------------------------------------------------------------------------- */
290 /* Python functions                                                          */
291 /* ------------------------------------------------------------------------- */
292
293 /* Integration hooks ------------------------------------------------------- */
294 PyTypeObject KX_MouseFocusSensor::Type = {
295         PyObject_HEAD_INIT(&PyType_Type)
296         0,
297         "KX_MouseFocusSensor",
298         sizeof(KX_MouseFocusSensor),
299         0,
300         PyDestructor,
301         0,
302         __getattr,
303         __setattr,
304         0, //&MyPyCompare,
305         __repr,
306         0, //&cvalue_as_number,
307         0,
308         0,
309         0,
310         0
311 };
312
313 PyParentObject KX_MouseFocusSensor::Parents[] = {
314         &KX_MouseFocusSensor::Type,
315         &SCA_MouseSensor::Type,
316         &SCA_ISensor::Type,
317         &SCA_ILogicBrick::Type,
318         &CValue::Type,
319         NULL
320 };
321
322 PyMethodDef KX_MouseFocusSensor::Methods[] = {
323         {"getRayTarget", (PyCFunction) KX_MouseFocusSensor::sPyGetRayTarget, 
324          METH_VARARGS, GetRayTarget_doc},
325         {"getRaySource", (PyCFunction) KX_MouseFocusSensor::sPyGetRaySource, 
326          METH_VARARGS, GetRaySource_doc},
327         {"getHitObject",(PyCFunction) KX_MouseFocusSensor::sPyGetHitObject,METH_VARARGS, GetHitObject_doc},
328         {"getHitPosition",(PyCFunction) KX_MouseFocusSensor::sPyGetHitPosition,METH_VARARGS, GetHitPosition_doc},
329         {"getHitNormal",(PyCFunction) KX_MouseFocusSensor::sPyGetHitNormal,METH_VARARGS, GetHitNormal_doc},
330         {"getRayDirection",(PyCFunction) KX_MouseFocusSensor::sPyGetRayDirection,METH_VARARGS, GetRayDirection_doc},
331
332
333         {NULL,NULL} //Sentinel
334 };
335
336 PyObject* KX_MouseFocusSensor::_getattr(const STR_String& attr) {
337         _getattr_up(SCA_MouseSensor);
338 }
339
340
341 char KX_MouseFocusSensor::GetHitObject_doc[] = 
342 "getHitObject()\n"
343 "\tReturns the name of the object that was hit by this ray.\n";
344 PyObject* KX_MouseFocusSensor::PyGetHitObject(PyObject* self, 
345                                                                                    PyObject* args, 
346                                                                                    PyObject* kwds)
347 {
348         if (m_hitObject)
349         {
350                 return m_hitObject->AddRef();
351         }
352         Py_Return;
353 }
354
355
356 char KX_MouseFocusSensor::GetHitPosition_doc[] = 
357 "getHitPosition()\n"
358 "\tReturns the position (in worldcoordinates) where the object was hit by this ray.\n";
359 PyObject* KX_MouseFocusSensor::PyGetHitPosition(PyObject* self, 
360                                PyObject* args, 
361                                PyObject* kwds)
362 {
363
364         MT_Point3 pos = m_hitPosition;
365
366         PyObject* resultlist = PyList_New(3);
367         int index;
368         for (index=0;index<3;index++)
369         {
370                 PyList_SetItem(resultlist,index,PyFloat_FromDouble(pos[index]));
371         }
372         return resultlist;
373
374 }
375
376 char KX_MouseFocusSensor::GetRayDirection_doc[] = 
377 "getRayDirection()\n"
378 "\tReturns the direction from the ray (in worldcoordinates) .\n";
379 PyObject* KX_MouseFocusSensor::PyGetRayDirection(PyObject* self, 
380                                PyObject* args, 
381                                PyObject* kwds)
382 {
383
384         MT_Vector3 dir = m_prevTargetPoint - m_prevSourcePoint;
385         dir.normalize();
386
387         PyObject* resultlist = PyList_New(3);
388         int index;
389         for (index=0;index<3;index++)
390         {
391                 PyList_SetItem(resultlist,index,PyFloat_FromDouble(dir[index]));
392         }
393         return resultlist;
394
395 }
396
397 char KX_MouseFocusSensor::GetHitNormal_doc[] = 
398 "getHitNormal()\n"
399 "\tReturns the normal (in worldcoordinates) of the object at the location where the object was hit by this ray.\n";
400 PyObject* KX_MouseFocusSensor::PyGetHitNormal(PyObject* self, 
401                                PyObject* args, 
402                                PyObject* kwds)
403 {
404         MT_Vector3 pos = m_hitNormal;
405
406         PyObject* resultlist = PyList_New(3);
407         int index;
408         for (index=0;index<3;index++)
409         {
410                 PyList_SetItem(resultlist,index,PyFloat_FromDouble(pos[index]));
411         }
412         return resultlist;
413
414 }
415
416
417 /*  getRayTarget                                                */
418 char KX_MouseFocusSensor::GetRayTarget_doc[] = 
419 "getRayTarget()\n"
420 "\tReturns the target of the ray that seeks the focus object,\n"
421 "\tin worldcoordinates.";
422 PyObject* KX_MouseFocusSensor::PyGetRayTarget(PyObject* self, 
423                                                                                           PyObject* args, 
424                                                                                           PyObject* kwds) {
425         PyObject *retVal = PyList_New(3);
426
427         PyList_SetItem(retVal, 0, PyFloat_FromDouble(m_prevTargetPoint[0]));
428         PyList_SetItem(retVal, 1, PyFloat_FromDouble(m_prevTargetPoint[1]));
429         PyList_SetItem(retVal, 2, PyFloat_FromDouble(m_prevTargetPoint[2]));
430         
431         return retVal;
432 }
433
434 /*  getRayTarget                                                */
435 char KX_MouseFocusSensor::GetRaySource_doc[] = 
436 "getRaySource()\n"
437 "\tReturns the source of the ray that seeks the focus object,\n"
438 "\tin worldcoordinates.";
439 PyObject* KX_MouseFocusSensor::PyGetRaySource(PyObject* self, 
440                                                                                           PyObject* args, 
441                                                                                           PyObject* kwds) {
442         PyObject *retVal = PyList_New(3);
443
444         PyList_SetItem(retVal, 0, PyFloat_FromDouble(m_prevSourcePoint[0]));
445         PyList_SetItem(retVal, 1, PyFloat_FromDouble(m_prevSourcePoint[1]));
446         PyList_SetItem(retVal, 2, PyFloat_FromDouble(m_prevSourcePoint[2]));
447         
448         return retVal;
449 }
450
451 /* eof */
452