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