Merge branch 'master' into blender2.8
[blender.git] / source / blender / blenkernel / intern / camera.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/camera.c
29  *  \ingroup bke
30  */
31
32 #include <stdlib.h>
33 #include <stddef.h>
34
35 #include "DNA_camera_types.h"
36 #include "DNA_lamp_types.h"
37 #include "DNA_object_types.h"
38 #include "DNA_scene_types.h"
39 #include "DNA_view3d_types.h"
40 #include "DNA_ID.h"
41
42 #include "BLI_math.h"
43 #include "BLI_listbase.h"
44 #include "BLI_rect.h"
45 #include "BLI_string.h"
46 #include "BLI_utildefines.h"
47
48 #include "BKE_animsys.h"
49 #include "BKE_camera.h"
50 #include "BKE_object.h"
51 #include "BKE_global.h"
52 #include "BKE_layer.h"
53 #include "BKE_library.h"
54 #include "BKE_library_query.h"
55 #include "BKE_library_remap.h"
56 #include "BKE_main.h"
57 #include "BKE_scene.h"
58 #include "BKE_screen.h"
59
60 #include "DEG_depsgraph_query.h"
61
62 #include "MEM_guardedalloc.h"
63
64 #include "GPU_compositing.h"
65
66 /****************************** Camera Datablock *****************************/
67
68 void BKE_camera_init(Camera *cam)
69 {
70         BLI_assert(MEMCMP_STRUCT_OFS_IS_ZERO(cam, id));
71
72         cam->lens = 35.0f;
73         cam->sensor_x = DEFAULT_SENSOR_WIDTH;
74         cam->sensor_y = DEFAULT_SENSOR_HEIGHT;
75         cam->clipsta = 0.1f;
76         cam->clipend = 100.0f;
77         cam->drawsize = 0.5f;
78         cam->ortho_scale = 6.0;
79         cam->flag |= CAM_SHOWPASSEPARTOUT;
80         cam->passepartalpha = 0.5f;
81
82         GPU_fx_compositor_init_dof_settings(&cam->gpu_dof);
83
84         /* stereoscopy 3d */
85         cam->stereo.interocular_distance = 0.065f;
86         cam->stereo.convergence_distance = 30.f * 0.065f;
87         cam->stereo.pole_merge_angle_from = DEG2RADF(60.0f);
88         cam->stereo.pole_merge_angle_to = DEG2RADF(75.0f);
89 }
90
91 void *BKE_camera_add(Main *bmain, const char *name)
92 {
93         Camera *cam;
94
95         cam =  BKE_libblock_alloc(bmain, ID_CA, name, 0);
96
97         BKE_camera_init(cam);
98
99         return cam;
100 }
101
102 /**
103  * Only copy internal data of Camera ID from source to already allocated/initialized destination.
104  * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
105  *
106  * WARNING! This function will not handle ID user count!
107  *
108  * \param flag  Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
109  */
110 void BKE_camera_copy_data(Main *UNUSED(bmain), Camera *cam_dst, const Camera *cam_src, const int flag)
111 {
112         BLI_duplicatelist(&cam_dst->bg_images, &cam_src->bg_images);
113         if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
114                 for (CameraBGImage *bgpic = cam_dst->bg_images.first; bgpic; bgpic = bgpic->next) {
115                         if (bgpic->source == CAM_BGIMG_SOURCE_IMAGE) {
116                                 id_us_plus((ID *)bgpic->ima);
117                         }
118                         else if (bgpic->source == CAM_BGIMG_SOURCE_MOVIE) {
119                                 id_us_plus((ID *)bgpic->clip);
120                         }
121                 }
122         }
123 }
124
125 Camera *BKE_camera_copy(Main *bmain, const Camera *cam)
126 {
127         Camera *cam_copy;
128         BKE_id_copy_ex(bmain, &cam->id, (ID **)&cam_copy, 0, false);
129         return cam_copy;
130 }
131
132 void BKE_camera_make_local(Main *bmain, Camera *cam, const bool lib_local)
133 {
134         BKE_id_make_local_generic(bmain, &cam->id, true, lib_local);
135 }
136
137 /** Free (or release) any data used by this camera (does not free the camera itself). */
138 void BKE_camera_free(Camera *ca)
139 {
140         for (CameraBGImage *bgpic = ca->bg_images.first; bgpic; bgpic = bgpic->next) {
141                 if (bgpic->source == CAM_BGIMG_SOURCE_IMAGE) {
142                         id_us_min((ID *)bgpic->ima);
143                 }
144                 else if (bgpic->source == CAM_BGIMG_SOURCE_MOVIE) {
145                         id_us_min((ID *)bgpic->clip);
146                 }
147         }
148         BLI_freelistN(&ca->bg_images);
149
150         BKE_animdata_free((ID *)ca, false);
151 }
152
153 /******************************** Camera Usage *******************************/
154
155 void BKE_camera_object_mode(RenderData *rd, Object *cam_ob)
156 {
157         rd->mode &= ~(R_ORTHO | R_PANORAMA);
158
159         if (cam_ob && cam_ob->type == OB_CAMERA) {
160                 Camera *cam = cam_ob->data;
161                 if (cam->type == CAM_ORTHO) rd->mode |= R_ORTHO;
162                 if (cam->type == CAM_PANO) rd->mode |= R_PANORAMA;
163         }
164 }
165
166 /* get the camera's dof value, takes the dof object into account */
167 float BKE_camera_object_dof_distance(Object *ob)
168 {
169         Camera *cam = (Camera *)ob->data; 
170         if (ob->type != OB_CAMERA)
171                 return 0.0f;
172         if (cam->dof_ob) {
173 #if 0
174                 /* too simple, better to return the distance on the view axis only */
175                 return len_v3v3(ob->obmat[3], cam->dof_ob->obmat[3]);
176 #else
177                 float view_dir[3], dof_dir[3];
178                 normalize_v3_v3(view_dir, ob->obmat[2]);
179                 sub_v3_v3v3(dof_dir, ob->obmat[3], cam->dof_ob->obmat[3]);
180                 return fabsf(dot_v3v3(view_dir, dof_dir));
181 #endif
182         }
183         return cam->YF_dofdist;
184 }
185
186 float BKE_camera_sensor_size(int sensor_fit, float sensor_x, float sensor_y)
187 {
188         /* sensor size used to fit to. for auto, sensor_x is both x and y. */
189         if (sensor_fit == CAMERA_SENSOR_FIT_VERT)
190                 return sensor_y;
191
192         return sensor_x;
193 }
194
195 int BKE_camera_sensor_fit(int sensor_fit, float sizex, float sizey)
196 {
197         if (sensor_fit == CAMERA_SENSOR_FIT_AUTO) {
198                 if (sizex >= sizey)
199                         return CAMERA_SENSOR_FIT_HOR;
200                 else
201                         return CAMERA_SENSOR_FIT_VERT;
202         }
203
204         return sensor_fit;
205 }
206
207 /******************************** Camera Params *******************************/
208
209 void BKE_camera_params_init(CameraParams *params)
210 {
211         memset(params, 0, sizeof(CameraParams));
212
213         /* defaults */
214         params->sensor_x = DEFAULT_SENSOR_WIDTH;
215         params->sensor_y = DEFAULT_SENSOR_HEIGHT;
216         params->sensor_fit = CAMERA_SENSOR_FIT_AUTO;
217
218         params->zoom = 1.0f;
219
220         /* fallback for non camera objects */
221         params->clipsta = 0.1f;
222         params->clipend = 100.0f;
223 }
224
225 void BKE_camera_params_from_object(CameraParams *params, const Object *ob)
226 {
227         if (!ob)
228                 return;
229
230         if (ob->type == OB_CAMERA) {
231                 /* camera object */
232                 Camera *cam = ob->data;
233
234                 if (cam->type == CAM_ORTHO)
235                         params->is_ortho = true;
236                 params->lens = cam->lens;
237                 params->ortho_scale = cam->ortho_scale;
238
239                 params->shiftx = cam->shiftx;
240                 params->shifty = cam->shifty;
241
242                 params->sensor_x = cam->sensor_x;
243                 params->sensor_y = cam->sensor_y;
244                 params->sensor_fit = cam->sensor_fit;
245
246                 params->clipsta = cam->clipsta;
247                 params->clipend = cam->clipend;
248         }
249         else if (ob->type == OB_LAMP) {
250                 /* lamp object */
251                 Lamp *la = ob->data;
252                 float fac = cosf(la->spotsize * 0.5f);
253                 float phi = acosf(fac);
254
255                 params->lens = 16.0f * fac / sinf(phi);
256                 if (params->lens == 0.0f)
257                         params->lens = 35.0f;
258
259                 params->clipsta = la->clipsta;
260                 params->clipend = la->clipend;
261         }
262         else {
263                 params->lens = 35.0f;
264         }
265 }
266
267 void BKE_camera_params_from_view3d(CameraParams *params, const Depsgraph *depsgraph, const View3D *v3d, const RegionView3D *rv3d)
268 {
269         /* common */
270         params->lens = v3d->lens;
271         params->clipsta = v3d->near;
272         params->clipend = v3d->far;
273
274         if (rv3d->persp == RV3D_CAMOB) {
275                 /* camera view */
276                 Object *camera_object = DEG_get_evaluated_object(depsgraph, v3d->camera);
277                 BKE_camera_params_from_object(params, camera_object);
278
279                 params->zoom = BKE_screen_view3d_zoom_to_fac(rv3d->camzoom);
280
281                 params->offsetx = 2.0f * rv3d->camdx * params->zoom;
282                 params->offsety = 2.0f * rv3d->camdy * params->zoom;
283
284                 params->shiftx *= params->zoom;
285                 params->shifty *= params->zoom;
286
287                 params->zoom = CAMERA_PARAM_ZOOM_INIT_CAMOB / params->zoom;
288         }
289         else if (rv3d->persp == RV3D_ORTHO) {
290                 /* orthographic view */
291                 float sensor_size = BKE_camera_sensor_size(params->sensor_fit, params->sensor_x, params->sensor_y);
292                 params->clipend *= 0.5f;    // otherwise too extreme low zbuffer quality
293                 params->clipsta = -params->clipend;
294
295                 params->is_ortho = true;
296                 /* make sure any changes to this match ED_view3d_radius_to_dist_ortho() */
297                 params->ortho_scale = rv3d->dist * sensor_size / v3d->lens;
298                 params->zoom = CAMERA_PARAM_ZOOM_INIT_PERSP;
299         }
300         else {
301                 /* perspective view */
302                 params->zoom = CAMERA_PARAM_ZOOM_INIT_PERSP;
303         }
304 }
305
306 void BKE_camera_params_compute_viewplane(CameraParams *params, int winx, int winy, float xasp, float yasp)
307 {
308         rctf viewplane;
309         float pixsize, viewfac, sensor_size, dx, dy;
310         int sensor_fit;
311
312         /* fields rendering */
313         params->ycor = yasp / xasp;
314         if (params->use_fields)
315                 params->ycor *= 2.0f;
316
317         if (params->is_ortho) {
318                 /* orthographic camera */
319                 /* scale == 1.0 means exact 1 to 1 mapping */
320                 pixsize = params->ortho_scale;
321         }
322         else {
323                 /* perspective camera */
324                 sensor_size = BKE_camera_sensor_size(params->sensor_fit, params->sensor_x, params->sensor_y);
325                 pixsize = (sensor_size * params->clipsta) / params->lens;
326         }
327
328         /* determine sensor fit */
329         sensor_fit = BKE_camera_sensor_fit(params->sensor_fit, xasp * winx, yasp * winy);
330
331         if (sensor_fit == CAMERA_SENSOR_FIT_HOR)
332                 viewfac = winx;
333         else
334                 viewfac = params->ycor * winy;
335
336         pixsize /= viewfac;
337
338         /* extra zoom factor */
339         pixsize *= params->zoom;
340
341         /* compute view plane:
342          * fully centered, zbuffer fills in jittered between -.5 and +.5 */
343         viewplane.xmin = -0.5f * (float)winx;
344         viewplane.ymin = -0.5f * params->ycor * (float)winy;
345         viewplane.xmax =  0.5f * (float)winx;
346         viewplane.ymax =  0.5f * params->ycor * (float)winy;
347
348         /* lens shift and offset */
349         dx = params->shiftx * viewfac + winx * params->offsetx;
350         dy = params->shifty * viewfac + winy * params->offsety;
351
352         viewplane.xmin += dx;
353         viewplane.ymin += dy;
354         viewplane.xmax += dx;
355         viewplane.ymax += dy;
356
357         /* fields offset */
358         if (params->field_second) {
359                 if (params->field_odd) {
360                         viewplane.ymin -= 0.5f * params->ycor;
361                         viewplane.ymax -= 0.5f * params->ycor;
362                 }
363                 else {
364                         viewplane.ymin += 0.5f * params->ycor;
365                         viewplane.ymax += 0.5f * params->ycor;
366                 }
367         }
368
369         /* the window matrix is used for clipping, and not changed during OSA steps */
370         /* using an offset of +0.5 here would give clip errors on edges */
371         viewplane.xmin *= pixsize;
372         viewplane.xmax *= pixsize;
373         viewplane.ymin *= pixsize;
374         viewplane.ymax *= pixsize;
375
376         /* Used for rendering (offset by near-clip with perspective views), passed to RE_SetPixelSize.
377          * For viewport drawing 'RegionView3D.pixsize'. */
378         params->viewdx = pixsize;
379         params->viewdy = params->ycor * pixsize;
380         params->viewplane = viewplane;
381 }
382
383 /* viewplane is assumed to be already computed */
384 void BKE_camera_params_compute_matrix(CameraParams *params)
385 {
386         rctf viewplane = params->viewplane;
387
388         /* compute projection matrix */
389         if (params->is_ortho)
390                 orthographic_m4(params->winmat, viewplane.xmin, viewplane.xmax,
391                                 viewplane.ymin, viewplane.ymax, params->clipsta, params->clipend);
392         else
393                 perspective_m4(params->winmat, viewplane.xmin, viewplane.xmax,
394                                viewplane.ymin, viewplane.ymax, params->clipsta, params->clipend);
395 }
396
397 /***************************** Camera View Frame *****************************/
398
399 void BKE_camera_view_frame_ex(
400         const Scene *scene, const Camera *camera,
401         const float drawsize, const bool do_clip, const float scale[3],
402         float r_asp[2], float r_shift[2], float *r_drawsize, float r_vec[4][3])
403 {
404         float facx, facy;
405         float depth;
406
407         /* aspect correcton */
408         if (scene) {
409                 float aspx = (float) scene->r.xsch * scene->r.xasp;
410                 float aspy = (float) scene->r.ysch * scene->r.yasp;
411                 int sensor_fit = BKE_camera_sensor_fit(camera->sensor_fit, aspx, aspy);
412
413                 if (sensor_fit == CAMERA_SENSOR_FIT_HOR) {
414                         r_asp[0] = 1.0;
415                         r_asp[1] = aspy / aspx;
416                 }
417                 else {
418                         r_asp[0] = aspx / aspy;
419                         r_asp[1] = 1.0;
420                 }
421         }
422         else {
423                 r_asp[0] = 1.0f;
424                 r_asp[1] = 1.0f;
425         }
426
427         if (camera->type == CAM_ORTHO) {
428                 facx = 0.5f * camera->ortho_scale * r_asp[0] * scale[0];
429                 facy = 0.5f * camera->ortho_scale * r_asp[1] * scale[1];
430                 r_shift[0] = camera->shiftx * camera->ortho_scale * scale[0];
431                 r_shift[1] = camera->shifty * camera->ortho_scale * scale[1];
432                 depth = do_clip ? -((camera->clipsta * scale[2]) + 0.1f) : -drawsize * camera->ortho_scale * scale[2];
433
434                 *r_drawsize = 0.5f * camera->ortho_scale;
435         }
436         else {
437                 /* that way it's always visible - clipsta+0.1 */
438                 float fac, scale_x, scale_y;
439                 float half_sensor = 0.5f * ((camera->sensor_fit == CAMERA_SENSOR_FIT_VERT) ?
440                                             (camera->sensor_y) : (camera->sensor_x));
441
442
443                 if (do_clip) {
444                         /* fixed depth, variable size (avoids exceeding clipping range) */
445                         /* r_drawsize shouldn't be used in this case, set to dummy value */
446                         *r_drawsize = 1.0f;
447                         depth = -(camera->clipsta + 0.1f) * scale[2];
448                         fac = depth / (camera->lens / (-half_sensor));
449                         scale_x = scale[0] / scale[2];
450                         scale_y = scale[1] / scale[2];
451                 }
452                 else {
453                         /* fixed size, variable depth (stays a reasonable size in the 3D view) */
454                         *r_drawsize = drawsize / ((scale[0] + scale[1] + scale[2]) / 3.0f);
455                         depth = *r_drawsize * camera->lens / (-half_sensor) * scale[2];
456                         fac = *r_drawsize;
457                         scale_x = scale[0];
458                         scale_y = scale[1];
459                 }
460
461                 facx = fac * r_asp[0] * scale_x;
462                 facy = fac * r_asp[1] * scale_y;
463                 r_shift[0] = camera->shiftx * fac * 2.0f * scale_x;
464                 r_shift[1] = camera->shifty * fac * 2.0f * scale_y;
465         }
466
467         r_vec[0][0] = r_shift[0] + facx; r_vec[0][1] = r_shift[1] + facy; r_vec[0][2] = depth;
468         r_vec[1][0] = r_shift[0] + facx; r_vec[1][1] = r_shift[1] - facy; r_vec[1][2] = depth;
469         r_vec[2][0] = r_shift[0] - facx; r_vec[2][1] = r_shift[1] - facy; r_vec[2][2] = depth;
470         r_vec[3][0] = r_shift[0] - facx; r_vec[3][1] = r_shift[1] + facy; r_vec[3][2] = depth;
471 }
472
473 void BKE_camera_view_frame(const Scene *scene, const Camera *camera, float r_vec[4][3])
474 {
475         float dummy_asp[2];
476         float dummy_shift[2];
477         float dummy_drawsize;
478         const float dummy_scale[3] = {1.0f, 1.0f, 1.0f};
479
480         BKE_camera_view_frame_ex(scene, camera, 0.0, true, dummy_scale,
481                                  dummy_asp, dummy_shift, &dummy_drawsize, r_vec);
482 }
483
484 #define CAMERA_VIEWFRAME_NUM_PLANES 4
485
486 typedef struct CameraViewFrameData {
487         float plane_tx[CAMERA_VIEWFRAME_NUM_PLANES][4];  /* 4 planes */
488         float normal_tx[CAMERA_VIEWFRAME_NUM_PLANES][3];
489         float dist_vals_sq[CAMERA_VIEWFRAME_NUM_PLANES];  /* distance squared (signed) */
490         unsigned int tot;
491
492         /* Ortho camera only. */
493         bool is_ortho;
494         float camera_no[3];
495         float dist_to_cam;
496
497         /* Not used by callbacks... */
498         float camera_rotmat[3][3];
499 } CameraViewFrameData;
500
501 static void camera_to_frame_view_cb(const float co[3], void *user_data)
502 {
503         CameraViewFrameData *data = (CameraViewFrameData *)user_data;
504         unsigned int i;
505
506         for (i = 0; i < CAMERA_VIEWFRAME_NUM_PLANES; i++) {
507                 const float nd = dist_signed_squared_to_plane_v3(co, data->plane_tx[i]);
508                 CLAMP_MAX(data->dist_vals_sq[i], nd);
509         }
510
511         if (data->is_ortho) {
512                 const float d = dot_v3v3(data->camera_no, co);
513                 CLAMP_MAX(data->dist_to_cam, d);
514         }
515
516         data->tot++;
517 }
518
519 static void camera_frame_fit_data_init(
520         const Scene *scene, const Object *ob,
521         CameraParams *params, CameraViewFrameData *data)
522 {
523         float camera_rotmat_transposed_inversed[4][4];
524         unsigned int i;
525
526         /* setup parameters */
527         BKE_camera_params_init(params);
528         BKE_camera_params_from_object(params, ob);
529
530         /* compute matrix, viewplane, .. */
531         if (scene) {
532                 BKE_camera_params_compute_viewplane(params, scene->r.xsch, scene->r.ysch, scene->r.xasp, scene->r.yasp);
533         }
534         else {
535                 BKE_camera_params_compute_viewplane(params, 1, 1, 1.0f, 1.0f);
536         }
537         BKE_camera_params_compute_matrix(params);
538
539         /* initialize callback data */
540         copy_m3_m4(data->camera_rotmat, (float (*)[4])ob->obmat);
541         normalize_m3(data->camera_rotmat);
542         /* To transform a plane which is in its homogeneous representation (4d vector),
543          * we need the inverse of the transpose of the transform matrix... */
544         copy_m4_m3(camera_rotmat_transposed_inversed, data->camera_rotmat);
545         transpose_m4(camera_rotmat_transposed_inversed);
546         invert_m4(camera_rotmat_transposed_inversed);
547
548         /* Extract frustum planes from projection matrix. */
549         planes_from_projmat(params->winmat,
550                             /*   left              right                 top              bottom        near  far */
551                             data->plane_tx[2], data->plane_tx[0], data->plane_tx[3], data->plane_tx[1], NULL, NULL);
552
553         /* Rotate planes and get normals from them */
554         for (i = 0; i < CAMERA_VIEWFRAME_NUM_PLANES; i++) {
555                 mul_m4_v4(camera_rotmat_transposed_inversed, data->plane_tx[i]);
556                 normalize_v3_v3(data->normal_tx[i], data->plane_tx[i]);
557         }
558
559         copy_v4_fl(data->dist_vals_sq, FLT_MAX);
560         data->tot = 0;
561         data->is_ortho = params->is_ortho;
562         if (params->is_ortho) {
563                 /* we want (0, 0, -1) transformed by camera_rotmat, this is a quicker shortcut. */
564                 negate_v3_v3(data->camera_no, data->camera_rotmat[2]);
565                 data->dist_to_cam = FLT_MAX;
566         }
567 }
568
569 static bool camera_frame_fit_calc_from_data(
570         CameraParams *params, CameraViewFrameData *data, float r_co[3], float *r_scale)
571 {
572         float plane_tx[CAMERA_VIEWFRAME_NUM_PLANES][4];
573         unsigned int i;
574
575         if (data->tot <= 1) {
576                 return false;
577         }
578
579         if (params->is_ortho) {
580                 const float *cam_axis_x = data->camera_rotmat[0];
581                 const float *cam_axis_y = data->camera_rotmat[1];
582                 const float *cam_axis_z = data->camera_rotmat[2];
583                 float dists[CAMERA_VIEWFRAME_NUM_PLANES];
584                 float scale_diff;
585
586                 /* apply the dist-from-plane's to the transformed plane points */
587                 for (i = 0; i < CAMERA_VIEWFRAME_NUM_PLANES; i++) {
588                         dists[i] = sqrtf_signed(data->dist_vals_sq[i]);
589                 }
590
591                 if ((dists[0] + dists[2]) > (dists[1] + dists[3])) {
592                         scale_diff = (dists[1] + dists[3]) *
593                                      (BLI_rctf_size_x(&params->viewplane) / BLI_rctf_size_y(&params->viewplane));
594                 }
595                 else {
596                         scale_diff = (dists[0] + dists[2]) *
597                                      (BLI_rctf_size_y(&params->viewplane) / BLI_rctf_size_x(&params->viewplane));
598                 }
599                 *r_scale = params->ortho_scale - scale_diff;
600
601                 zero_v3(r_co);
602                 madd_v3_v3fl(r_co, cam_axis_x, (dists[2] - dists[0]) * 0.5f + params->shiftx * scale_diff);
603                 madd_v3_v3fl(r_co, cam_axis_y, (dists[1] - dists[3]) * 0.5f + params->shifty * scale_diff);
604                 madd_v3_v3fl(r_co, cam_axis_z, -(data->dist_to_cam - 1.0f - params->clipsta));
605
606                 return true;
607         }
608         else {
609                 float plane_isect_1[3], plane_isect_1_no[3], plane_isect_1_other[3];
610                 float plane_isect_2[3], plane_isect_2_no[3], plane_isect_2_other[3];
611
612                 float plane_isect_pt_1[3], plane_isect_pt_2[3];
613
614                 /* apply the dist-from-plane's to the transformed plane points */
615                 for (i = 0; i < CAMERA_VIEWFRAME_NUM_PLANES; i++) {
616                         float co[3];
617                         mul_v3_v3fl(co, data->normal_tx[i], sqrtf_signed(data->dist_vals_sq[i]));
618                         plane_from_point_normal_v3(plane_tx[i], co, data->normal_tx[i]);
619                 }
620
621                 if ((!isect_plane_plane_v3(plane_tx[0], plane_tx[2], plane_isect_1, plane_isect_1_no)) ||
622                     (!isect_plane_plane_v3(plane_tx[1], plane_tx[3], plane_isect_2, plane_isect_2_no)))
623                 {
624                         return false;
625                 }
626
627                 add_v3_v3v3(plane_isect_1_other, plane_isect_1, plane_isect_1_no);
628                 add_v3_v3v3(plane_isect_2_other, plane_isect_2, plane_isect_2_no);
629
630                 if (isect_line_line_v3(plane_isect_1, plane_isect_1_other,
631                                        plane_isect_2, plane_isect_2_other,
632                                        plane_isect_pt_1, plane_isect_pt_2) != 0)
633                 {
634                         float cam_plane_no[3];
635                         float plane_isect_delta[3];
636                         float plane_isect_delta_len;
637
638                         float shift_fac = BKE_camera_sensor_size(params->sensor_fit, params->sensor_x, params->sensor_y) /
639                                           params->lens;
640
641                         /* we want (0, 0, -1) transformed by camera_rotmat, this is a quicker shortcut. */
642                         negate_v3_v3(cam_plane_no, data->camera_rotmat[2]);
643
644                         sub_v3_v3v3(plane_isect_delta, plane_isect_pt_2, plane_isect_pt_1);
645                         plane_isect_delta_len = len_v3(plane_isect_delta);
646
647                         if (dot_v3v3(plane_isect_delta, cam_plane_no) > 0.0f) {
648                                 copy_v3_v3(r_co, plane_isect_pt_1);
649
650                                 /* offset shift */
651                                 normalize_v3(plane_isect_1_no);
652                                 madd_v3_v3fl(r_co, plane_isect_1_no, params->shifty * plane_isect_delta_len * shift_fac);
653                         }
654                         else {
655                                 copy_v3_v3(r_co, plane_isect_pt_2);
656
657                                 /* offset shift */
658                                 normalize_v3(plane_isect_2_no);
659                                 madd_v3_v3fl(r_co, plane_isect_2_no, params->shiftx * plane_isect_delta_len * shift_fac);
660                         }
661
662                         return true;
663                 }
664         }
665
666         return false;
667 }
668
669 /* don't move the camera, just yield the fit location */
670 /* r_scale only valid/useful for ortho cameras */
671 bool BKE_camera_view_frame_fit_to_scene(
672         Scene *scene, ViewLayer *view_layer, Object *camera_ob, float r_co[3], float *r_scale)
673 {
674         CameraParams params;
675         CameraViewFrameData data_cb;
676
677         /* just in case */
678         *r_scale = 1.0f;
679
680         camera_frame_fit_data_init(scene, camera_ob, &params, &data_cb);
681
682         /* run callback on all visible points */
683         BKE_scene_foreach_display_point(scene, view_layer, camera_to_frame_view_cb, &data_cb);
684
685         return camera_frame_fit_calc_from_data(&params, &data_cb, r_co, r_scale);
686 }
687
688 bool BKE_camera_view_frame_fit_to_coords(
689         const Scene *scene, const float (*cos)[3], int num_cos, const Object *camera_ob,
690         float r_co[3], float *r_scale)
691 {
692         CameraParams params;
693         CameraViewFrameData data_cb;
694
695         /* just in case */
696         *r_scale = 1.0f;
697
698         camera_frame_fit_data_init(scene, camera_ob, &params, &data_cb);
699
700         /* run callback on all given coordinates */
701         while (num_cos--) {
702                 camera_to_frame_view_cb(cos[num_cos], &data_cb);
703         }
704
705         return camera_frame_fit_calc_from_data(&params, &data_cb, r_co, r_scale);
706 }
707
708 /******************* multiview matrix functions ***********************/
709
710 static void camera_model_matrix(Object *camera, float r_modelmat[4][4])
711 {
712         copy_m4_m4(r_modelmat, camera->obmat);
713 }
714
715 static void camera_stereo3d_model_matrix(Object *camera, const bool is_left, float r_modelmat[4][4])
716 {
717         Camera *data = (Camera *)camera->data;
718         float interocular_distance, convergence_distance;
719         short convergence_mode, pivot;
720         float sizemat[4][4];
721
722         float fac = 1.0f;
723         float fac_signed;
724
725         interocular_distance = data->stereo.interocular_distance;
726         convergence_distance = data->stereo.convergence_distance;
727         convergence_mode = data->stereo.convergence_mode;
728         pivot = data->stereo.pivot;
729
730         if (((pivot == CAM_S3D_PIVOT_LEFT) && is_left) ||
731             ((pivot == CAM_S3D_PIVOT_RIGHT) && !is_left))
732         {
733                 camera_model_matrix(camera, r_modelmat);
734                 return;
735         }
736         else {
737                 float size[3];
738                 mat4_to_size(size, camera->obmat);
739                 size_to_mat4(sizemat, size);
740         }
741
742         if (pivot == CAM_S3D_PIVOT_CENTER)
743                 fac = 0.5f;
744
745         fac_signed = is_left ? fac : -fac;
746
747         /* rotation */
748         if (convergence_mode == CAM_S3D_TOE) {
749                 float angle;
750                 float angle_sin, angle_cos;
751                 float toeinmat[4][4];
752                 float rotmat[4][4];
753
754                 unit_m4(rotmat);
755
756                 if (pivot == CAM_S3D_PIVOT_CENTER) {
757                         fac = -fac;
758                         fac_signed = -fac_signed;
759                 }
760
761                 angle = atanf((interocular_distance * 0.5f) / convergence_distance) / fac;
762
763                 angle_cos = cosf(angle * fac_signed);
764                 angle_sin = sinf(angle * fac_signed);
765
766                 rotmat[0][0] =  angle_cos;
767                 rotmat[2][0] = -angle_sin;
768                 rotmat[0][2] =  angle_sin;
769                 rotmat[2][2] =  angle_cos;
770
771                 if (pivot == CAM_S3D_PIVOT_CENTER) {
772                         /* set the rotation */
773                         copy_m4_m4(toeinmat, rotmat);
774                         /* set the translation */
775                         toeinmat[3][0] = interocular_distance * fac_signed;
776
777                         /* transform */
778                         normalize_m4_m4(r_modelmat, camera->obmat);
779                         mul_m4_m4m4(r_modelmat, r_modelmat, toeinmat);
780
781                         /* scale back to the original size */
782                         mul_m4_m4m4(r_modelmat, r_modelmat, sizemat);
783                 }
784                 else { /* CAM_S3D_PIVOT_LEFT, CAM_S3D_PIVOT_RIGHT */
785                         /* rotate perpendicular to the interocular line */
786                         normalize_m4_m4(r_modelmat, camera->obmat);
787                         mul_m4_m4m4(r_modelmat, r_modelmat, rotmat);
788
789                         /* translate along the interocular line */
790                         unit_m4(toeinmat);
791                         toeinmat[3][0] = -interocular_distance * fac_signed;
792                         mul_m4_m4m4(r_modelmat, r_modelmat, toeinmat);
793
794                         /* rotate to toe-in angle */
795                         mul_m4_m4m4(r_modelmat, r_modelmat, rotmat);
796
797                         /* scale back to the original size */
798                         mul_m4_m4m4(r_modelmat, r_modelmat, sizemat);
799                 }
800         }
801         else {
802                 normalize_m4_m4(r_modelmat, camera->obmat);
803
804                 /* translate - no rotation in CAM_S3D_OFFAXIS, CAM_S3D_PARALLEL */
805                 translate_m4(r_modelmat, -interocular_distance * fac_signed, 0.0f, 0.0f);
806
807                 /* scale back to the original size */
808                 mul_m4_m4m4(r_modelmat, r_modelmat, sizemat);
809         }
810 }
811
812 /* the view matrix is used by the viewport drawing, it is basically the inverted model matrix */
813 void BKE_camera_multiview_view_matrix(RenderData *rd, Object *camera, const bool is_left, float r_viewmat[4][4])
814 {
815         BKE_camera_multiview_model_matrix(rd, camera, is_left ? STEREO_LEFT_NAME : STEREO_RIGHT_NAME, r_viewmat);
816         invert_m4(r_viewmat);
817 }
818
819 /* left is the default */
820 static bool camera_is_left(const char *viewname)
821 {
822         if (viewname && viewname[0] != '\0') {
823                 return !STREQ(viewname, STEREO_RIGHT_NAME);
824         }
825         return true;
826 }
827
828 void BKE_camera_multiview_model_matrix(RenderData *rd, Object *camera, const char *viewname, float r_modelmat[4][4])
829 {
830         const bool is_multiview = (rd && rd->scemode & R_MULTIVIEW) != 0;
831
832         if (!is_multiview) {
833                 camera_model_matrix(camera, r_modelmat);
834         }
835         else if (rd->views_format == SCE_VIEWS_FORMAT_MULTIVIEW) {
836                 camera_model_matrix(camera, r_modelmat);
837         }
838         else { /* SCE_VIEWS_SETUP_BASIC */
839                 const bool is_left = camera_is_left(viewname);
840                 camera_stereo3d_model_matrix(camera, is_left, r_modelmat);
841         }
842         normalize_m4(r_modelmat);
843 }
844
845 bool BKE_camera_multiview_spherical_stereo(RenderData *rd, Object *camera)
846 {
847         Camera *cam;
848         const bool is_multiview = (rd && rd->scemode & R_MULTIVIEW) != 0;
849
850         if (!is_multiview)
851                 return false;
852
853         if (camera->type != OB_CAMERA)
854                 return false;
855         else
856                 cam = camera->data;
857
858         if ((rd->views_format == SCE_VIEWS_FORMAT_STEREO_3D) &&
859             ELEM(cam->type, CAM_PANO, CAM_PERSP) &&
860             ((cam->stereo.flag & CAM_S3D_SPHERICAL) != 0))
861         {
862                 return true;
863         }
864
865         return false;
866 }
867
868 static Object *camera_multiview_advanced(Scene *scene, Object *camera, const char *suffix)
869 {
870         SceneRenderView *srv;
871         char name[MAX_NAME];
872         const char *camera_name = camera->id.name + 2;
873         const int len_name = strlen(camera_name);
874         int len_suffix_max = -1;
875
876         name[0] = '\0';
877
878         /* we need to take the better match, thus the len_suffix_max test */
879         for (srv = scene->r.views.first; srv; srv = srv->next) {
880                 const int len_suffix = strlen(srv->suffix);
881
882                 if ((len_suffix < len_suffix_max) || (len_name < len_suffix))
883                         continue;
884
885                 if (STREQ(camera_name + (len_name - len_suffix), srv->suffix)) {
886                         BLI_snprintf(name, sizeof(name), "%.*s%s", (len_name - len_suffix), camera_name, suffix);
887                         len_suffix_max = len_suffix;
888                 }
889         }
890
891         if (name[0] != '\0') {
892                 Object *ob = BKE_scene_object_find_by_name(scene, name);
893                 if (ob != NULL) {
894                         return ob;
895                 }
896         }
897
898         return camera;
899 }
900
901 /* returns the camera to be used for render */
902 Object *BKE_camera_multiview_render(Scene *scene, Object *camera, const char *viewname)
903 {
904         const bool is_multiview = (camera != NULL) &&  (scene->r.scemode & R_MULTIVIEW) != 0;
905
906         if (!is_multiview) {
907                 return camera;
908         }
909         else if (scene->r.views_format == SCE_VIEWS_FORMAT_STEREO_3D) {
910                 return camera;
911         }
912         else { /* SCE_VIEWS_FORMAT_MULTIVIEW */
913                 const char *suffix = BKE_scene_multiview_view_suffix_get(&scene->r, viewname);
914                 return camera_multiview_advanced(scene, camera, suffix);
915         }
916 }
917
918 static float camera_stereo3d_shift_x(Object *camera, const char *viewname)
919 {
920         Camera *data = camera->data;
921         float shift = data->shiftx;
922         float interocular_distance, convergence_distance;
923         short convergence_mode, pivot;
924         bool is_left = true;
925
926         float fac = 1.0f;
927         float fac_signed;
928
929         if (viewname && viewname[0]) {
930                 is_left = STREQ(viewname, STEREO_LEFT_NAME);
931         }
932
933         interocular_distance = data->stereo.interocular_distance;
934         convergence_distance = data->stereo.convergence_distance;
935         convergence_mode = data->stereo.convergence_mode;
936         pivot = data->stereo.pivot;
937
938         if (convergence_mode != CAM_S3D_OFFAXIS)
939                 return shift;
940
941         if (((pivot == CAM_S3D_PIVOT_LEFT) && is_left) ||
942             ((pivot == CAM_S3D_PIVOT_RIGHT) && !is_left))
943         {
944                 return shift;
945         }
946
947         if (pivot == CAM_S3D_PIVOT_CENTER)
948                 fac = 0.5f;
949
950         fac_signed = is_left ? fac : -fac;
951         shift += ((interocular_distance / data->sensor_x) * (data->lens / convergence_distance)) * fac_signed;
952
953         return shift;
954 }
955
956 float BKE_camera_multiview_shift_x(RenderData *rd, Object *camera, const char *viewname)
957 {
958         const bool is_multiview = (rd && rd->scemode & R_MULTIVIEW) != 0;
959         Camera *data = camera->data;
960
961         BLI_assert(camera->type == OB_CAMERA);
962
963         if (!is_multiview) {
964                 return data->shiftx;
965         }
966         else if (rd->views_format == SCE_VIEWS_FORMAT_MULTIVIEW) {
967                 return data->shiftx;
968         }
969         else { /* SCE_VIEWS_SETUP_BASIC */
970                 return camera_stereo3d_shift_x(camera, viewname);
971         }
972 }
973
974 void BKE_camera_multiview_params(RenderData *rd, CameraParams *params, Object *camera, const char *viewname)
975 {
976         if (camera->type == OB_CAMERA) {
977                 params->shiftx = BKE_camera_multiview_shift_x(rd, camera, viewname);
978         }
979 }
980
981 void BKE_camera_to_gpu_dof(struct Object *camera, struct GPUFXSettings *r_fx_settings)
982 {
983         if (camera->type == OB_CAMERA) {
984                 Camera *cam = camera->data;
985                 r_fx_settings->dof = &cam->gpu_dof;
986                 r_fx_settings->dof->focal_length = cam->lens;
987                 r_fx_settings->dof->sensor = BKE_camera_sensor_size(cam->sensor_fit, cam->sensor_x, cam->sensor_y);
988                 r_fx_settings->dof->focus_distance = BKE_camera_object_dof_distance(camera);
989         }
990 }
991
992 CameraBGImage *BKE_camera_background_image_new(Camera *cam)
993 {
994         CameraBGImage *bgpic = MEM_callocN(sizeof(CameraBGImage), "Background Image");
995
996         bgpic->scale = 1.0f;
997         bgpic->alpha = 0.5f;
998         bgpic->iuser.fie_ima = 2;
999         bgpic->iuser.ok = 1;
1000         bgpic->flag |= CAM_BGIMG_FLAG_EXPANDED;
1001
1002         BLI_addtail(&cam->bg_images, bgpic);
1003
1004         return bgpic;
1005 }
1006
1007 void BKE_camera_background_image_remove(Camera *cam, CameraBGImage *bgpic)
1008 {
1009         BLI_remlink(&cam->bg_images, bgpic);
1010
1011         MEM_freeN(bgpic);
1012 }
1013
1014 void BKE_camera_background_image_clear(Camera *cam)
1015 {
1016         CameraBGImage *bgpic = cam->bg_images.first;
1017
1018         while (bgpic) {
1019                 CameraBGImage *next_bgpic = bgpic->next;
1020
1021                 BKE_camera_background_image_remove(cam, bgpic);
1022
1023                 bgpic = next_bgpic;
1024         }
1025 }