Fix MouseFocus Sensor objects for dynamic cameras. (Bug 1165)
[blender.git] / source / gameengine / Ketsji / KX_MouseFocusSensor.cpp
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL/BL DUAL 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. The Blender
10  * Foundation also sells licenses for use in proprietary software under
11  * the Blender License.  See http://www.blender.org/BL/ for information
12  * about this.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22  *
23  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
24  * All rights reserved.
25  *
26  * The Original Code is: all of this file.
27  *
28  * Contributor(s): none yet.
29  *
30  * ***** END GPL/BL DUAL LICENSE BLOCK *****
31  * KX_MouseFocusSensor determines mouse in/out/over events.
32  */
33
34 #ifdef HAVE_CONFIG_H
35 #include <config.h>
36 #endif
37
38 #ifdef WIN32
39 // This warning tells us about truncation of __long__ stl-generated names.
40 // It can occasionally cause DevStudio to have internal compiler warnings.
41 #pragma warning( disable : 4786 )     
42 #endif
43
44 #include "MT_Point3.h"
45 #include "KX_ClientObjectInfo.h"
46 #include "RAS_FramingManager.h"
47 #include "RAS_ICanvas.h"
48 #include "RAS_IRasterizer.h"
49 #include "SCA_IScene.h"
50 #include "KX_Scene.h"
51 #include "KX_Camera.h"
52 #include "KX_MouseFocusSensor.h"
53
54 #include "KX_ClientObjectInfo.h"
55 #include "SM_Object.h"
56 #include "SM_Scene.h"
57 #include "SumoPhysicsEnvironment.h"
58 #include "KX_SumoPhysicsController.h"
59
60 /* ------------------------------------------------------------------------- */
61 /* Native functions                                                          */
62 /* ------------------------------------------------------------------------- */
63
64 KX_MouseFocusSensor::KX_MouseFocusSensor(SCA_MouseManager* eventmgr, 
65                                                                                  int startx,
66                                                                                  int starty,
67                                                                                  short int mousemode,
68                                                                                  bool focusmode,
69                                                                                  RAS_ICanvas* canvas,
70                                                                                  KX_Scene* kxscene,
71                                                                                  SCA_IObject* gameobj, 
72                                                                                  PyTypeObject* T)
73     : SCA_MouseSensor(eventmgr, startx, starty, mousemode, gameobj, T),
74           m_focusmode(focusmode),
75           m_gp_canvas(canvas),
76           m_kxscene(kxscene)
77 {
78         /* Or postpone? I think a sumo scene and kx scene go pretty much
79          * together, so it should be safe to do it here. */
80         m_mouse_over_in_previous_frame = false;
81         m_positive_event = false;
82 }
83
84 bool KX_MouseFocusSensor::Evaluate(CValue* event)
85 {
86         bool result = false;
87         bool obHasFocus = false;
88
89 //      cout << "evaluate focus mouse sensor "<<endl;
90
91         if (m_focusmode) {
92                 /* Focus behaviour required. Test mouse-on. The rest is
93                  * equivalent to handling a key. */
94                 obHasFocus = ParentObjectHasFocus();
95                 
96                 if (!obHasFocus) {
97                         if (m_mouse_over_in_previous_frame) {
98                                         m_positive_event = false;
99                                         result = true;
100                         } 
101                 } else {
102                         if (!m_mouse_over_in_previous_frame) {
103                                 m_positive_event = true;
104                                 result = true;
105                         } 
106                 } 
107         } else {
108                 /* No focus behaviour required: revert to the basic mode. This
109          * mode is never used, because the converter never makes this
110          * sensor for a mouse-key event. It is here for
111          * completeness. */
112                 result = SCA_MouseSensor::Evaluate(event);
113                 m_positive_event = (m_val!=0);
114         }
115
116         m_mouse_over_in_previous_frame = obHasFocus;
117
118         return result;
119 }
120
121 bool KX_MouseFocusSensor::ParentObjectHasFocus(void)
122 {
123         
124         bool res = false;
125         m_hitPosition = MT_Vector3(0,0,0);
126         m_hitNormal =   MT_Vector3(1,0,0);
127         MT_Point3 resultpoint;
128         MT_Vector3 resultnormal;
129
130         /* All screen handling in the gameengine is done by GL,
131          * specifically the model/view and projection parts. The viewport
132          * part is in the creator. 
133          *
134          * The theory is this:
135          * WCS - world coordinates
136          * -> wcs_camcs_trafo ->
137          * camCS - camera coordinates
138          * -> camcs_clip_trafo ->
139          * clipCS - normalised device coordinates?
140          * -> normview_win_trafo
141          * winCS - window coordinates
142          *
143          * The first two transforms are respectively the model/view and
144          * the projection matrix. These are passed to the rasterizer, and
145          * we store them in the camera for easy access.
146          *
147          * For normalised device coords (xn = x/w, yn = y/w/zw) the
148          * windows coords become (lb = left bottom)
149          *
150          * xwin = [(xn + 1.0) * width]/2 + x_lb
151          * ywin = [(yn + 1.0) * height]/2 + y_lb
152          *
153          * Inverting (blender y is flipped!):
154          *
155          * xn = 2(xwin - x_lb)/width - 1.0
156          * yn = 2(ywin - y_lb)/height - 1.0 
157          *    = 2(height - y_blender - y_lb)/height - 1.0
158          *    = 1.0 - 2(y_blender - y_lb)/height
159          *
160          * */
161         
162         /* Because we don't want to worry about resize events, camera
163          * changes and all that crap, we just determine this over and
164          * over. Stop whining. We have lots of other calculations to do
165          * here as well. These reads are not the main cost. If there is no
166          * canvas, the test is irrelevant. The 1.0 makes sure the
167          * calculations don't bomb. Maybe we should explicitly guard for
168          * division by 0.0...*/
169
170         /**
171          * Get the scenes current viewport.
172          */
173
174         const RAS_Rect & viewport = m_kxscene->GetSceneViewport();
175
176         float height = float(viewport.m_y2 - viewport.m_y1 + 1);
177         float width  = float(viewport.m_x2 - viewport.m_x1 + 1);
178         
179         float x_lb = float(viewport.m_x1);
180         float y_lb = float(viewport.m_y1);
181
182         KX_Camera* cam = m_kxscene->GetActiveCamera();
183         /* There's some strangeness I don't fully get here... These values
184          * _should_ be wrong! */
185
186         /* old: */
187         float nearclip = 0.0;
188         float farclip = 1.0;
189
190         /*      build the from and to point in normalised device coordinates 
191          *      Looks like normailized device coordinates are [-1,1] in x [-1,1] in y
192          *      [0,-1] in z 
193          *      
194          *      The actual z coordinates used don't have to be exact just infront and 
195          *      behind of the near and far clip planes.
196          */ 
197         MT_Vector4 frompoint = MT_Vector4( 
198                 (2 * (m_x-x_lb) / width) - 1.0,
199                 1.0 - (2 * (m_y - y_lb) / height),
200                 nearclip,
201                 1.0
202         );
203         MT_Vector4 topoint = MT_Vector4( 
204                 (2 * (m_x-x_lb) / width) - 1.0,
205                 1.0 - (2 * (m_y-y_lb) / height),
206                 farclip,
207                 1.0
208         );
209
210         /* camera to world  */
211         MT_Matrix4x4 camcs_wcs_matrix = MT_Matrix4x4(cam->GetCameraToWorld());
212
213         /* badly defined, the first time round.... I wonder why... I might
214          * want to guard against floating point errors here.*/
215         MT_Matrix4x4 clip_camcs_matrix = MT_Matrix4x4(cam->GetProjectionMatrix());
216         clip_camcs_matrix.invert();
217
218         /* shoot-points: clip to cam to wcs . win to clip was already done.*/
219         frompoint = clip_camcs_matrix * frompoint;
220         topoint   = clip_camcs_matrix * topoint;
221         frompoint = camcs_wcs_matrix * frompoint;
222         topoint   = camcs_wcs_matrix * topoint;
223         
224         /* from hom wcs to 3d wcs: */
225         MT_Point3 frompoint3 = MT_Point3(frompoint[0]/frompoint[3], 
226                                                                          frompoint[1]/frompoint[3], 
227                                                                          frompoint[2]/frompoint[3]); 
228         MT_Point3 topoint3 = MT_Point3(topoint[0]/topoint[3], 
229                                                                    topoint[1]/topoint[3], 
230                                                                    topoint[2]/topoint[3]); 
231         m_prevTargetPoint = topoint3;
232         
233         /* 2. Get the object from SuMO*/
234         /* Shoot! Beware that the first argument here is an
235          * ignore-object. We don't ignore anything... */
236         KX_GameObject* thisObj = (KX_GameObject*) GetParent();
237         
238         SumoPhysicsEnvironment *spe = dynamic_cast<SumoPhysicsEnvironment* > (m_kxscene->GetPhysicsEnvironment());
239         SM_Scene *sumoScene = spe->GetSumoScene();
240         KX_SumoPhysicsController *spc = dynamic_cast<KX_SumoPhysicsController*> (cam->GetPhysicsController());
241         SM_Object *sumoCam = spc?spc->GetSumoObject():NULL;
242         MT_Vector3 todir = topoint3 - frompoint3;
243         if (todir.dot(todir) < MT_EPSILON)
244                 return false;
245         todir.normalize();
246
247         while (true)
248         {       
249                 SM_Object* hitSMObj = sumoScene->rayTest(sumoCam, 
250                                                         frompoint3,
251                                                         topoint3,
252                                                         resultpoint, 
253                                                         resultnormal);
254                 
255                 if (!hitSMObj)
256                         return false;
257                         
258                 /* all this casting makes me nervous... */
259                 KX_ClientObjectInfo* client_info 
260                         = ( hitSMObj ?
261                                 (KX_ClientObjectInfo*) hitSMObj->getClientObject() :
262                                 NULL);
263                 
264                 if (!client_info)
265                 {
266                         std::cout<< "WARNING:  MouseOver sensor " << GetName() << " cannot sense SM_Object " << hitSMObj << " - no client info.\n" << std::endl;
267                         return false;
268                 } 
269         
270                 KX_GameObject* hitKXObj = (KX_GameObject*)client_info->m_clientobject;
271                 
272                 if (client_info->m_type > KX_ClientObjectInfo::ACTOR)
273                 {
274                         // false hit
275                         KX_SumoPhysicsController *hitspc = dynamic_cast<KX_SumoPhysicsController *> (static_cast<KX_GameObject*> (hitKXObj) ->GetPhysicsController());
276                         if (hitspc)
277                         {
278                                 /* We add 0.01 of fudge, so that if the margin && radius == 0., we don't endless loop. */
279                                 MT_Scalar marg = 0.01 + hitspc->GetSumoObject()->getMargin();
280                                 if (hitspc->GetSumoObject()->getShapeProps())
281                                 {
282                                         marg += 2*hitspc->GetSumoObject()->getShapeProps()->m_radius;
283                                 }
284                                 
285                                 /* Calculate the other side of this object */
286                                 MT_Point3 hitObjPos;
287                                 hitspc->GetWorldPosition(hitObjPos);
288                                 MT_Vector3 hitvector = hitObjPos - resultpoint;
289                                 if (hitvector.dot(hitvector) > MT_EPSILON)
290                                 {
291                                         hitvector.normalize();
292                                         marg *= 2.*todir.dot(hitvector);
293                                 }
294                                 frompoint3 = resultpoint + marg * todir;
295                         } else {
296                                 return false;
297                         }
298                         continue;
299                 }
300                 /* Is this me? In the ray test, there are a lot of extra checks
301                 * for aliasing artefacts from self-hits. That doesn't happen
302                 * here, so a simple test suffices. Or does the camera also get
303                 * self-hits? (No, and the raysensor shouldn't do it either, since
304                 * self-hits are excluded by setting the correct ignore-object.)
305                 * Hitspots now become valid. */
306                 if (hitKXObj == thisObj)
307                 {
308                         m_hitPosition = resultpoint;
309                         m_hitNormal = resultnormal;
310                         return true;
311                 }
312                 
313                 return false;
314         }
315
316         return false;
317 }
318
319 /* ------------------------------------------------------------------------- */
320 /* Python functions                                                          */
321 /* ------------------------------------------------------------------------- */
322
323 /* Integration hooks ------------------------------------------------------- */
324 PyTypeObject KX_MouseFocusSensor::Type = {
325         PyObject_HEAD_INIT(&PyType_Type)
326         0,
327         "KX_MouseFocusSensor",
328         sizeof(KX_MouseFocusSensor),
329         0,
330         PyDestructor,
331         0,
332         __getattr,
333         __setattr,
334         0, //&MyPyCompare,
335         __repr,
336         0, //&cvalue_as_number,
337         0,
338         0,
339         0,
340         0
341 };
342
343 PyParentObject KX_MouseFocusSensor::Parents[] = {
344         &KX_MouseFocusSensor::Type,
345         &SCA_MouseSensor::Type,
346         &SCA_ISensor::Type,
347         &SCA_ILogicBrick::Type,
348         &CValue::Type,
349         NULL
350 };
351
352 PyMethodDef KX_MouseFocusSensor::Methods[] = {
353         {"getRayTarget", (PyCFunction) KX_MouseFocusSensor::sPyGetRayTarget, 
354          METH_VARARGS, GetRayTarget_doc},
355         {"getRaySource", (PyCFunction) KX_MouseFocusSensor::sPyGetRaySource, 
356          METH_VARARGS, GetRaySource_doc},
357         {NULL,NULL} //Sentinel
358 };
359
360 PyObject* KX_MouseFocusSensor::_getattr(char* attr) {
361         _getattr_up(SCA_MouseSensor);
362 }
363
364 /*  getRayTarget                                                */
365 char KX_MouseFocusSensor::GetRayTarget_doc[] = 
366 "getRayTarget()\n"
367 "\tReturns the target of the ray that seeks the focus object,\n"
368 "\tin worldcoordinates.";
369 PyObject* KX_MouseFocusSensor::PyGetRayTarget(PyObject* self, 
370                                                                                           PyObject* args, 
371                                                                                           PyObject* kwds) {
372         PyObject *retVal = PyList_New(3);
373
374         PyList_SetItem(retVal, 0, PyFloat_FromDouble(m_prevTargetPoint[0]));
375         PyList_SetItem(retVal, 1, PyFloat_FromDouble(m_prevTargetPoint[1]));
376         PyList_SetItem(retVal, 2, PyFloat_FromDouble(m_prevTargetPoint[2]));
377         
378         return retVal;
379 }
380
381 /*  getRayTarget                                                */
382 char KX_MouseFocusSensor::GetRaySource_doc[] = 
383 "getRaySource()\n"
384 "\tReturns the source of the ray that seeks the focus object,\n"
385 "\tin worldcoordinates.";
386 PyObject* KX_MouseFocusSensor::PyGetRaySource(PyObject* self, 
387                                                                                           PyObject* args, 
388                                                                                           PyObject* kwds) {
389         PyObject *retVal = PyList_New(3);
390
391         PyList_SetItem(retVal, 0, PyFloat_FromDouble(m_prevSourcePoint[0]));
392         PyList_SetItem(retVal, 1, PyFloat_FromDouble(m_prevSourcePoint[1]));
393         PyList_SetItem(retVal, 2, PyFloat_FromDouble(m_prevSourcePoint[2]));
394         
395         return retVal;
396 }
397
398 /* eof */
399