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