Make whole ID copying code use const source pointer.
[blender.git] / source / blender / blenkernel / intern / colortools.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) 2005 Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL/BL DUAL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/colortools.c
29  *  \ingroup bke
30  */
31
32
33 #include <string.h>
34 #include <math.h>
35 #include <stdlib.h>
36 #include <float.h>
37
38 #include "MEM_guardedalloc.h"
39
40 #include "DNA_color_types.h"
41 #include "DNA_curve_types.h"
42
43 #include "BLI_blenlib.h"
44 #include "BLI_math.h"
45 #include "BLI_utildefines.h"
46 #include "BLI_task.h"
47 #include "BLI_threads.h"
48
49 #include "BKE_colortools.h"
50 #include "BKE_curve.h"
51 #include "BKE_fcurve.h"
52
53
54 #include "IMB_colormanagement.h"
55 #include "IMB_imbuf_types.h"
56
57 /* ********************************* color curve ********************* */
58
59 /* ***************** operations on full struct ************* */
60
61 void curvemapping_set_defaults(CurveMapping *cumap, int tot, float minx, float miny, float maxx, float maxy)
62 {
63         int a;
64         float clipminx, clipminy, clipmaxx, clipmaxy;
65         
66         cumap->flag = CUMA_DO_CLIP;
67         if (tot == 4) cumap->cur = 3;   /* rhms, hack for 'col' curve? */
68         
69         clipminx = min_ff(minx, maxx);
70         clipminy = min_ff(miny, maxy);
71         clipmaxx = max_ff(minx, maxx);
72         clipmaxy = max_ff(miny, maxy);
73         
74         BLI_rctf_init(&cumap->curr, clipminx, clipmaxx, clipminy, clipmaxy);
75         cumap->clipr = cumap->curr;
76         
77         cumap->white[0] = cumap->white[1] = cumap->white[2] = 1.0f;
78         cumap->bwmul[0] = cumap->bwmul[1] = cumap->bwmul[2] = 1.0f;
79         
80         for (a = 0; a < tot; a++) {
81                 cumap->cm[a].flag = CUMA_EXTEND_EXTRAPOLATE;
82                 cumap->cm[a].totpoint = 2;
83                 cumap->cm[a].curve = MEM_callocN(2 * sizeof(CurveMapPoint), "curve points");
84
85                 cumap->cm[a].curve[0].x = minx;
86                 cumap->cm[a].curve[0].y = miny;
87                 cumap->cm[a].curve[1].x = maxx;
88                 cumap->cm[a].curve[1].y = maxy;
89         }
90
91         cumap->changed_timestamp = 0;
92 }
93
94 CurveMapping *curvemapping_add(int tot, float minx, float miny, float maxx, float maxy)
95 {
96         CurveMapping *cumap;
97
98         cumap = MEM_callocN(sizeof(CurveMapping), "new curvemap");
99
100         curvemapping_set_defaults(cumap, tot, minx, miny, maxx, maxy);
101
102         return cumap;
103 }
104
105 void curvemapping_free_data(CurveMapping *cumap)
106 {
107         int a;
108
109         for (a = 0; a < CM_TOT; a++) {
110                 if (cumap->cm[a].curve) {
111                         MEM_freeN(cumap->cm[a].curve);
112                         cumap->cm[a].curve = NULL;
113                 }
114                 if (cumap->cm[a].table) {
115                         MEM_freeN(cumap->cm[a].table);
116                         cumap->cm[a].table = NULL;
117                 }
118                 if (cumap->cm[a].premultable) {
119                         MEM_freeN(cumap->cm[a].premultable);
120                         cumap->cm[a].premultable = NULL;
121                 }
122         }
123 }
124
125 void curvemapping_free(CurveMapping *cumap)
126 {
127         if (cumap) {
128                 curvemapping_free_data(cumap);
129                 MEM_freeN(cumap);
130         }
131 }
132
133 void curvemapping_copy_data(CurveMapping *target, const CurveMapping *cumap)
134 {
135         int a;
136
137         *target = *cumap;
138
139         for (a = 0; a < CM_TOT; a++) {
140                 if (cumap->cm[a].curve)
141                         target->cm[a].curve = MEM_dupallocN(cumap->cm[a].curve);
142                 if (cumap->cm[a].table)
143                         target->cm[a].table = MEM_dupallocN(cumap->cm[a].table);
144                 if (cumap->cm[a].premultable)
145                         target->cm[a].premultable = MEM_dupallocN(cumap->cm[a].premultable);
146         }
147 }
148
149 CurveMapping *curvemapping_copy(const CurveMapping *cumap)
150 {
151         if (cumap) {
152                 CurveMapping *cumapn = MEM_dupallocN(cumap);
153                 curvemapping_copy_data(cumapn, cumap);
154                 return cumapn;
155         }
156         return NULL;
157 }
158
159 void curvemapping_set_black_white_ex(const float black[3], const float white[3], float r_bwmul[3])
160 {
161         int a;
162
163         for (a = 0; a < 3; a++) {
164                 const float delta = max_ff(white[a] - black[a], 1e-5f);
165                 r_bwmul[a] = 1.0f / delta;
166         }
167 }
168
169 void curvemapping_set_black_white(CurveMapping *cumap, const float black[3], const float white[3])
170 {
171         if (white) {
172                 copy_v3_v3(cumap->white, white);
173         }
174         if (black) {
175                 copy_v3_v3(cumap->black, black);
176         }
177
178         curvemapping_set_black_white_ex(cumap->black, cumap->white, cumap->bwmul);
179         cumap->changed_timestamp++;
180 }
181
182 /* ***************** operations on single curve ************* */
183 /* ********** NOTE: requires curvemapping_changed() call after ******** */
184
185 /* remove specified point */
186 bool curvemap_remove_point(CurveMap *cuma, CurveMapPoint *point)
187 {
188         CurveMapPoint *cmp;
189         int a, b, removed = 0;
190         
191         /* must have 2 points minimum */
192         if (cuma->totpoint <= 2)
193                 return false;
194
195         cmp = MEM_mallocN((cuma->totpoint) * sizeof(CurveMapPoint), "curve points");
196
197         /* well, lets keep the two outer points! */
198         for (a = 0, b = 0; a < cuma->totpoint; a++) {
199                 if (&cuma->curve[a] != point) {
200                         cmp[b] = cuma->curve[a];
201                         b++;
202                 }
203                 else {
204                         removed++;
205                 }
206         }
207         
208         MEM_freeN(cuma->curve);
209         cuma->curve = cmp;
210         cuma->totpoint -= removed;
211         return (removed != 0);
212 }
213
214 /* removes with flag set */
215 void curvemap_remove(CurveMap *cuma, const short flag)
216 {
217         CurveMapPoint *cmp = MEM_mallocN((cuma->totpoint) * sizeof(CurveMapPoint), "curve points");
218         int a, b, removed = 0;
219         
220         /* well, lets keep the two outer points! */
221         cmp[0] = cuma->curve[0];
222         for (a = 1, b = 1; a < cuma->totpoint - 1; a++) {
223                 if (!(cuma->curve[a].flag & flag)) {
224                         cmp[b] = cuma->curve[a];
225                         b++;
226                 }
227                 else {
228                         removed++;
229                 }
230         }
231         cmp[b] = cuma->curve[a];
232         
233         MEM_freeN(cuma->curve);
234         cuma->curve = cmp;
235         cuma->totpoint -= removed;
236 }
237
238 CurveMapPoint *curvemap_insert(CurveMap *cuma, float x, float y)
239 {
240         CurveMapPoint *cmp = MEM_callocN((cuma->totpoint + 1) * sizeof(CurveMapPoint), "curve points");
241         CurveMapPoint *newcmp = NULL;
242         int a, b;
243         bool foundloc = false;
244
245         /* insert fragments of the old one and the new point to the new curve */
246         cuma->totpoint++;
247         for (a = 0, b = 0; a < cuma->totpoint; a++) {
248                 if ((foundloc == false) && ((a + 1 == cuma->totpoint) || (x < cuma->curve[a].x))) {
249                         cmp[a].x = x;
250                         cmp[a].y = y;
251                         cmp[a].flag = CUMA_SELECT;
252                         foundloc = true;
253                         newcmp = &cmp[a];
254                 }
255                 else {
256                         cmp[a].x = cuma->curve[b].x;
257                         cmp[a].y = cuma->curve[b].y;
258                         /* make sure old points don't remain selected */
259                         cmp[a].flag = cuma->curve[b].flag & ~CUMA_SELECT;
260                         cmp[a].shorty = cuma->curve[b].shorty;
261                         b++;
262                 }
263         }
264
265         /* free old curve and replace it with new one */
266         MEM_freeN(cuma->curve);
267         cuma->curve = cmp;
268
269         return newcmp;
270 }
271
272 void curvemap_reset(CurveMap *cuma, const rctf *clipr, int preset, int slope)
273 {
274         if (cuma->curve)
275                 MEM_freeN(cuma->curve);
276
277         switch (preset) {
278                 case CURVE_PRESET_LINE: cuma->totpoint = 2; break;
279                 case CURVE_PRESET_SHARP: cuma->totpoint = 4; break;
280                 case CURVE_PRESET_SMOOTH: cuma->totpoint = 4; break;
281                 case CURVE_PRESET_MAX: cuma->totpoint = 2; break;
282                 case CURVE_PRESET_MID9: cuma->totpoint = 9; break;
283                 case CURVE_PRESET_ROUND: cuma->totpoint = 4; break;
284                 case CURVE_PRESET_ROOT: cuma->totpoint = 4; break;
285         }
286
287         cuma->curve = MEM_callocN(cuma->totpoint * sizeof(CurveMapPoint), "curve points");
288
289         switch (preset) {
290                 case CURVE_PRESET_LINE:
291                         cuma->curve[0].x = clipr->xmin;
292                         cuma->curve[0].y = clipr->ymax;
293                         cuma->curve[1].x = clipr->xmax;
294                         cuma->curve[1].y = clipr->ymin;
295                         if (slope == CURVEMAP_SLOPE_POS_NEG) {
296                                 cuma->curve[0].flag |= CUMA_HANDLE_VECTOR;
297                                 cuma->curve[1].flag |= CUMA_HANDLE_VECTOR;
298                         }
299                         break;
300                 case CURVE_PRESET_SHARP:
301                         cuma->curve[0].x = 0;
302                         cuma->curve[0].y = 1;
303                         cuma->curve[1].x = 0.25;
304                         cuma->curve[1].y = 0.50;
305                         cuma->curve[2].x = 0.75;
306                         cuma->curve[2].y = 0.04;
307                         cuma->curve[3].x = 1;
308                         cuma->curve[3].y = 0;
309                         break;
310                 case CURVE_PRESET_SMOOTH:
311                         cuma->curve[0].x = 0;
312                         cuma->curve[0].y = 1;
313                         cuma->curve[1].x = 0.25;
314                         cuma->curve[1].y = 0.94;
315                         cuma->curve[2].x = 0.75;
316                         cuma->curve[2].y = 0.06;
317                         cuma->curve[3].x = 1;
318                         cuma->curve[3].y = 0;
319                         break;
320                 case CURVE_PRESET_MAX:
321                         cuma->curve[0].x = 0;
322                         cuma->curve[0].y = 1;
323                         cuma->curve[1].x = 1;
324                         cuma->curve[1].y = 1;
325                         break;
326                 case CURVE_PRESET_MID9:
327                 {
328                         int i;
329                         for (i = 0; i < cuma->totpoint; i++) {
330                                 cuma->curve[i].x = i / ((float)cuma->totpoint - 1);
331                                 cuma->curve[i].y = 0.5;
332                         }
333                         break;
334                 }
335                 case CURVE_PRESET_ROUND:
336                         cuma->curve[0].x = 0;
337                         cuma->curve[0].y = 1;
338                         cuma->curve[1].x = 0.5;
339                         cuma->curve[1].y = 0.90;
340                         cuma->curve[2].x = 0.86;
341                         cuma->curve[2].y = 0.5;
342                         cuma->curve[3].x = 1;
343                         cuma->curve[3].y = 0;
344                         break;
345                 case CURVE_PRESET_ROOT:
346                         cuma->curve[0].x = 0;
347                         cuma->curve[0].y = 1;
348                         cuma->curve[1].x = 0.25;
349                         cuma->curve[1].y = 0.95;
350                         cuma->curve[2].x = 0.75;
351                         cuma->curve[2].y = 0.44;
352                         cuma->curve[3].x = 1;
353                         cuma->curve[3].y = 0;
354                         break;
355         }
356
357         /* mirror curve in x direction to have positive slope
358          * rather than default negative slope */
359         if (slope == CURVEMAP_SLOPE_POSITIVE) {
360                 int i, last = cuma->totpoint - 1;
361                 CurveMapPoint *newpoints = MEM_dupallocN(cuma->curve);
362                 
363                 for (i = 0; i < cuma->totpoint; i++) {
364                         newpoints[i].y = cuma->curve[last - i].y;
365                 }
366                 
367                 MEM_freeN(cuma->curve);
368                 cuma->curve = newpoints;
369         }
370         else if (slope == CURVEMAP_SLOPE_POS_NEG) {
371                 const int num_points = cuma->totpoint * 2 - 1;
372                 CurveMapPoint *new_points = MEM_mallocN(num_points * sizeof(CurveMapPoint),
373                                                        "curve symmetric points");
374                 int i;
375                 for (i = 0; i < cuma->totpoint; i++) {
376                         const int src_last_point = cuma->totpoint - i - 1;
377                         const int dst_last_point = num_points - i - 1;
378                         new_points[i] = cuma->curve[src_last_point];
379                         new_points[i].x = (1.0f - cuma->curve[src_last_point].x) * 0.5f;
380                         new_points[dst_last_point] = new_points[i];
381                         new_points[dst_last_point].x = 0.5f + cuma->curve[src_last_point].x * 0.5f;
382                 }
383                 cuma->totpoint = num_points;
384                 MEM_freeN(cuma->curve);
385                 cuma->curve = new_points;
386         }
387
388         if (cuma->table) {
389                 MEM_freeN(cuma->table);
390                 cuma->table = NULL;
391         }
392 }
393
394 /**
395  * \param type: eBezTriple_Handle
396  */
397 void curvemap_handle_set(CurveMap *cuma, int type)
398 {
399         int a;
400         
401         for (a = 0; a < cuma->totpoint; a++) {
402                 if (cuma->curve[a].flag & CUMA_SELECT) {
403                         cuma->curve[a].flag &= ~(CUMA_HANDLE_VECTOR | CUMA_HANDLE_AUTO_ANIM);
404                         if (type == HD_VECT) {
405                                 cuma->curve[a].flag |= CUMA_HANDLE_VECTOR;
406                         }
407                         else if (type == HD_AUTO_ANIM) {
408                                 cuma->curve[a].flag |= CUMA_HANDLE_AUTO_ANIM;
409                         }
410                         else {
411                                 /* pass */
412                         }
413                 }
414         }
415 }
416
417 /* *********************** Making the tables and display ************** */
418
419 /**
420  * reduced copy of #calchandleNurb_intern code in curve.c
421  */
422 static void calchandle_curvemap(
423         BezTriple *bezt, const BezTriple *prev, const BezTriple *next)
424 {
425         /* defines to avoid confusion */
426 #define p2_h1 ((p2) - 3)
427 #define p2_h2 ((p2) + 3)
428
429         const float *p1, *p3;
430         float *p2;
431         float pt[3];
432         float len, len_a, len_b;
433         float dvec_a[2], dvec_b[2];
434
435         if (bezt->h1 == 0 && bezt->h2 == 0) {
436                 return;
437         }
438         
439         p2 = bezt->vec[1];
440         
441         if (prev == NULL) {
442                 p3 = next->vec[1];
443                 pt[0] = 2.0f * p2[0] - p3[0];
444                 pt[1] = 2.0f * p2[1] - p3[1];
445                 p1 = pt;
446         }
447         else {
448                 p1 = prev->vec[1];
449         }
450         
451         if (next == NULL) {
452                 p1 = prev->vec[1];
453                 pt[0] = 2.0f * p2[0] - p1[0];
454                 pt[1] = 2.0f * p2[1] - p1[1];
455                 p3 = pt;
456         }
457         else {
458                 p3 = next->vec[1];
459         }
460
461         sub_v2_v2v2(dvec_a, p2, p1);
462         sub_v2_v2v2(dvec_b, p3, p2);
463
464         len_a = len_v2(dvec_a);
465         len_b = len_v2(dvec_b);
466
467         if (len_a == 0.0f) len_a = 1.0f;
468         if (len_b == 0.0f) len_b = 1.0f;
469
470         if (ELEM(bezt->h1, HD_AUTO, HD_AUTO_ANIM) || ELEM(bezt->h2, HD_AUTO, HD_AUTO_ANIM)) {    /* auto */
471                 float tvec[2];
472                 tvec[0] = dvec_b[0] / len_b + dvec_a[0] / len_a;
473                 tvec[1] = dvec_b[1] / len_b + dvec_a[1] / len_a;
474
475                 len = len_v2(tvec) * 2.5614f;
476                 if (len != 0.0f) {
477                         
478                         if (ELEM(bezt->h1, HD_AUTO, HD_AUTO_ANIM)) {
479                                 len_a /= len;
480                                 madd_v2_v2v2fl(p2_h1, p2, tvec, -len_a);
481
482                                 if ((bezt->h1 == HD_AUTO_ANIM) && next && prev) { /* keep horizontal if extrema */
483                                         const float ydiff1 = prev->vec[1][1] - bezt->vec[1][1];
484                                         const float ydiff2 = next->vec[1][1] - bezt->vec[1][1];
485                                         if ((ydiff1 <= 0.0f && ydiff2 <= 0.0f) ||
486                                             (ydiff1 >= 0.0f && ydiff2 >= 0.0f))
487                                         {
488                                                 bezt->vec[0][1] = bezt->vec[1][1];
489                                         }
490                                         else { /* handles should not be beyond y coord of two others */
491                                                 if (ydiff1 <= 0.0f) {
492                                                         if (prev->vec[1][1] > bezt->vec[0][1]) {
493                                                                 bezt->vec[0][1] = prev->vec[1][1];
494                                                         }
495                                                 }
496                                                 else {
497                                                         if (prev->vec[1][1] < bezt->vec[0][1]) {
498                                                                 bezt->vec[0][1] = prev->vec[1][1];
499                                                         }
500                                                 }
501                                         }
502                                 }
503                         }
504                         if (ELEM(bezt->h2, HD_AUTO, HD_AUTO_ANIM)) {
505                                 len_b /= len;
506                                 madd_v2_v2v2fl(p2_h2, p2, tvec,  len_b);
507
508                                 if ((bezt->h2 == HD_AUTO_ANIM) && next && prev) { /* keep horizontal if extrema */
509                                         const float ydiff1 = prev->vec[1][1] - bezt->vec[1][1];
510                                         const float ydiff2 = next->vec[1][1] - bezt->vec[1][1];
511                                         if ((ydiff1 <= 0.0f && ydiff2 <= 0.0f) ||
512                                             (ydiff1 >= 0.0f && ydiff2 >= 0.0f))
513                                         {
514                                                 bezt->vec[2][1] = bezt->vec[1][1];
515                                         }
516                                         else { /* handles should not be beyond y coord of two others */
517                                                 if (ydiff1 <= 0.0f) {
518                                                         if (next->vec[1][1] < bezt->vec[2][1]) {
519                                                                 bezt->vec[2][1] = next->vec[1][1];
520                                                         }
521                                                 }
522                                                 else {
523                                                         if (next->vec[1][1] > bezt->vec[2][1]) {
524                                                                 bezt->vec[2][1] = next->vec[1][1];
525                                                         }
526                                                 }
527                                         }
528                                 }
529                         }
530                 }
531         }
532
533         if (bezt->h1 == HD_VECT) {    /* vector */
534                 madd_v2_v2v2fl(p2_h1, p2, dvec_a, -1.0f / 3.0f);
535         }
536         if (bezt->h2 == HD_VECT) {
537                 madd_v2_v2v2fl(p2_h2, p2, dvec_b,  1.0f / 3.0f);
538         }
539
540 #undef p2_h1
541 #undef p2_h2
542 }
543
544 /* in X, out Y. 
545  * X is presumed to be outside first or last */
546 static float curvemap_calc_extend(const CurveMap *cuma, float x, const float first[2], const float last[2])
547 {
548         if (x <= first[0]) {
549                 if ((cuma->flag & CUMA_EXTEND_EXTRAPOLATE) == 0) {
550                         /* no extrapolate */
551                         return first[1];
552                 }
553                 else {
554                         if (cuma->ext_in[0] == 0.0f)
555                                 return first[1] + cuma->ext_in[1] * 10000.0f;
556                         else
557                                 return first[1] + cuma->ext_in[1] * (x - first[0]) / cuma->ext_in[0];
558                 }
559         }
560         else if (x >= last[0]) {
561                 if ((cuma->flag & CUMA_EXTEND_EXTRAPOLATE) == 0) {
562                         /* no extrapolate */
563                         return last[1];
564                 }
565                 else {
566                         if (cuma->ext_out[0] == 0.0f)
567                                 return last[1] - cuma->ext_out[1] * 10000.0f;
568                         else
569                                 return last[1] + cuma->ext_out[1] * (x - last[0]) / cuma->ext_out[0];
570                 }
571         }
572         return 0.0f;
573 }
574
575 /* only creates a table for a single channel in CurveMapping */
576 static void curvemap_make_table(CurveMap *cuma, const rctf *clipr)
577 {
578         CurveMapPoint *cmp = cuma->curve;
579         BezTriple *bezt;
580         float *fp, *allpoints, *lastpoint, curf, range;
581         int a, totpoint;
582         
583         if (cuma->curve == NULL) return;
584         
585         /* default rect also is table range */
586         cuma->mintable = clipr->xmin;
587         cuma->maxtable = clipr->xmax;
588         
589         /* hrmf... we now rely on blender ipo beziers, these are more advanced */
590         bezt = MEM_callocN(cuma->totpoint * sizeof(BezTriple), "beztarr");
591         
592         for (a = 0; a < cuma->totpoint; a++) {
593                 cuma->mintable = min_ff(cuma->mintable, cmp[a].x);
594                 cuma->maxtable = max_ff(cuma->maxtable, cmp[a].x);
595                 bezt[a].vec[1][0] = cmp[a].x;
596                 bezt[a].vec[1][1] = cmp[a].y;
597                 if (cmp[a].flag & CUMA_HANDLE_VECTOR) {
598                         bezt[a].h1 = bezt[a].h2 = HD_VECT;
599                 }
600                 else if (cmp[a].flag & CUMA_HANDLE_AUTO_ANIM) {
601                         bezt[a].h1 = bezt[a].h2 = HD_AUTO_ANIM;
602                 }
603                 else {
604                         bezt[a].h1 = bezt[a].h2 = HD_AUTO;
605                 }
606         }
607         
608         const BezTriple *bezt_prev = NULL;
609         for (a = 0; a < cuma->totpoint; a++) {
610                 const BezTriple *bezt_next = (a != cuma->totpoint - 1) ? &bezt[a + 1] : NULL;
611                 calchandle_curvemap(&bezt[a], bezt_prev, bezt_next);
612                 bezt_prev = &bezt[a];
613         }
614         
615         /* first and last handle need correction, instead of pointing to center of next/prev, 
616          * we let it point to the closest handle */
617         if (cuma->totpoint > 2) {
618                 float hlen, nlen, vec[3];
619                 
620                 if (bezt[0].h2 == HD_AUTO) {
621                         
622                         hlen = len_v3v3(bezt[0].vec[1], bezt[0].vec[2]); /* original handle length */
623                         /* clip handle point */
624                         copy_v3_v3(vec, bezt[1].vec[0]);
625                         if (vec[0] < bezt[0].vec[1][0])
626                                 vec[0] = bezt[0].vec[1][0];
627                         
628                         sub_v3_v3(vec, bezt[0].vec[1]);
629                         nlen = len_v3(vec);
630                         if (nlen > FLT_EPSILON) {
631                                 mul_v3_fl(vec, hlen / nlen);
632                                 add_v3_v3v3(bezt[0].vec[2], vec, bezt[0].vec[1]);
633                                 sub_v3_v3v3(bezt[0].vec[0], bezt[0].vec[1], vec);
634                         }
635                 }
636                 a = cuma->totpoint - 1;
637                 if (bezt[a].h2 == HD_AUTO) {
638                         
639                         hlen = len_v3v3(bezt[a].vec[1], bezt[a].vec[0]); /* original handle length */
640                         /* clip handle point */
641                         copy_v3_v3(vec, bezt[a - 1].vec[2]);
642                         if (vec[0] > bezt[a].vec[1][0])
643                                 vec[0] = bezt[a].vec[1][0];
644                         
645                         sub_v3_v3(vec, bezt[a].vec[1]);
646                         nlen = len_v3(vec);
647                         if (nlen > FLT_EPSILON) {
648                                 mul_v3_fl(vec, hlen / nlen);
649                                 add_v3_v3v3(bezt[a].vec[0], vec, bezt[a].vec[1]);
650                                 sub_v3_v3v3(bezt[a].vec[2], bezt[a].vec[1], vec);
651                         }
652                 }
653         }
654         /* make the bezier curve */
655         if (cuma->table)
656                 MEM_freeN(cuma->table);
657         totpoint = (cuma->totpoint - 1) * CM_RESOL;
658         fp = allpoints = MEM_callocN(totpoint * 2 * sizeof(float), "table");
659         
660         for (a = 0; a < cuma->totpoint - 1; a++, fp += 2 * CM_RESOL) {
661                 correct_bezpart(bezt[a].vec[1], bezt[a].vec[2], bezt[a + 1].vec[0], bezt[a + 1].vec[1]);
662                 BKE_curve_forward_diff_bezier(bezt[a].vec[1][0], bezt[a].vec[2][0], bezt[a + 1].vec[0][0], bezt[a + 1].vec[1][0], fp, CM_RESOL - 1, 2 * sizeof(float));
663                 BKE_curve_forward_diff_bezier(bezt[a].vec[1][1], bezt[a].vec[2][1], bezt[a + 1].vec[0][1], bezt[a + 1].vec[1][1], fp + 1, CM_RESOL - 1, 2 * sizeof(float));
664         }
665         
666         /* store first and last handle for extrapolation, unit length */
667         cuma->ext_in[0] = bezt[0].vec[0][0] - bezt[0].vec[1][0];
668         cuma->ext_in[1] = bezt[0].vec[0][1] - bezt[0].vec[1][1];
669         range = sqrtf(cuma->ext_in[0] * cuma->ext_in[0] + cuma->ext_in[1] * cuma->ext_in[1]);
670         cuma->ext_in[0] /= range;
671         cuma->ext_in[1] /= range;
672
673         a = cuma->totpoint - 1;
674         cuma->ext_out[0] = bezt[a].vec[1][0] - bezt[a].vec[2][0];
675         cuma->ext_out[1] = bezt[a].vec[1][1] - bezt[a].vec[2][1];
676         range = sqrtf(cuma->ext_out[0] * cuma->ext_out[0] + cuma->ext_out[1] * cuma->ext_out[1]);
677         cuma->ext_out[0] /= range;
678         cuma->ext_out[1] /= range;
679         
680         /* cleanup */
681         MEM_freeN(bezt);
682
683         range = CM_TABLEDIV * (cuma->maxtable - cuma->mintable);
684         cuma->range = 1.0f / range;
685         
686         /* now make a table with CM_TABLE equal x distances */
687         fp = allpoints;
688         lastpoint = allpoints + 2 * (totpoint - 1);
689         cmp = MEM_callocN((CM_TABLE + 1) * sizeof(CurveMapPoint), "dist table");
690
691         for (a = 0; a <= CM_TABLE; a++) {
692                 curf = cuma->mintable + range * (float)a;
693                 cmp[a].x = curf;
694                 
695                 /* get the first x coordinate larger than curf */
696                 while (curf >= fp[0] && fp != lastpoint) {
697                         fp += 2;
698                 }
699                 if (fp == allpoints || (curf >= fp[0] && fp == lastpoint))
700                         cmp[a].y = curvemap_calc_extend(cuma, curf, allpoints, lastpoint);
701                 else {
702                         float fac1 = fp[0] - fp[-2];
703                         float fac2 = fp[0] - curf;
704                         if (fac1 > FLT_EPSILON)
705                                 fac1 = fac2 / fac1;
706                         else
707                                 fac1 = 0.0f;
708                         cmp[a].y = fac1 * fp[-1] + (1.0f - fac1) * fp[1];
709                 }
710         }
711         
712         MEM_freeN(allpoints);
713         cuma->table = cmp;
714 }
715
716 /* call when you do images etc, needs restore too. also verifies tables */
717 /* it uses a flag to prevent premul or free to happen twice */
718 void curvemapping_premultiply(CurveMapping *cumap, int restore)
719 {
720         int a;
721         
722         if (restore) {
723                 if (cumap->flag & CUMA_PREMULLED) {
724                         for (a = 0; a < 3; a++) {
725                                 MEM_freeN(cumap->cm[a].table);
726                                 cumap->cm[a].table = cumap->cm[a].premultable;
727                                 cumap->cm[a].premultable = NULL;
728
729                                 copy_v2_v2(cumap->cm[a].ext_in, cumap->cm[a].premul_ext_in);
730                                 copy_v2_v2(cumap->cm[a].ext_out, cumap->cm[a].premul_ext_out);
731                                 zero_v2(cumap->cm[a].premul_ext_in);
732                                 zero_v2(cumap->cm[a].premul_ext_out);
733                         }
734                         
735                         cumap->flag &= ~CUMA_PREMULLED;
736                 }
737         }
738         else {
739                 if ((cumap->flag & CUMA_PREMULLED) == 0) {
740                         /* verify and copy */
741                         for (a = 0; a < 3; a++) {
742                                 if (cumap->cm[a].table == NULL)
743                                         curvemap_make_table(cumap->cm + a, &cumap->clipr);
744                                 cumap->cm[a].premultable = cumap->cm[a].table;
745                                 cumap->cm[a].table = MEM_mallocN((CM_TABLE + 1) * sizeof(CurveMapPoint), "premul table");
746                                 memcpy(cumap->cm[a].table, cumap->cm[a].premultable, (CM_TABLE + 1) * sizeof(CurveMapPoint));
747                         }
748                         
749                         if (cumap->cm[3].table == NULL)
750                                 curvemap_make_table(cumap->cm + 3, &cumap->clipr);
751                 
752                         /* premul */
753                         for (a = 0; a < 3; a++) {
754                                 int b;
755                                 for (b = 0; b <= CM_TABLE; b++) {
756                                         cumap->cm[a].table[b].y = curvemap_evaluateF(cumap->cm + 3, cumap->cm[a].table[b].y);
757                                 }
758
759                                 copy_v2_v2(cumap->cm[a].premul_ext_in, cumap->cm[a].ext_in);
760                                 copy_v2_v2(cumap->cm[a].premul_ext_out, cumap->cm[a].ext_out);
761                                 mul_v2_v2(cumap->cm[a].ext_in, cumap->cm[3].ext_in);
762                                 mul_v2_v2(cumap->cm[a].ext_out, cumap->cm[3].ext_out);
763                         }
764                         
765                         cumap->flag |= CUMA_PREMULLED;
766                 }
767         }
768 }
769
770 static int sort_curvepoints(const void *a1, const void *a2)
771 {
772         const struct CurveMapPoint *x1 = a1, *x2 = a2;
773         
774         if (x1->x > x2->x) return 1;
775         else if (x1->x < x2->x) return -1;
776         return 0;
777 }
778
779 /* ************************ more CurveMapping calls *************** */
780
781 /* note; only does current curvemap! */
782 void curvemapping_changed(CurveMapping *cumap, const bool rem_doubles)
783 {
784         CurveMap *cuma = cumap->cm + cumap->cur;
785         CurveMapPoint *cmp = cuma->curve;
786         rctf *clipr = &cumap->clipr;
787         float thresh = 0.01f * BLI_rctf_size_x(clipr);
788         float dx = 0.0f, dy = 0.0f;
789         int a;
790
791         cumap->changed_timestamp++;
792
793         /* clamp with clip */
794         if (cumap->flag & CUMA_DO_CLIP) {
795                 for (a = 0; a < cuma->totpoint; a++) {
796                         if (cmp[a].flag & CUMA_SELECT) {
797                                 if (cmp[a].x < clipr->xmin)
798                                         dx = min_ff(dx, cmp[a].x - clipr->xmin);
799                                 else if (cmp[a].x > clipr->xmax)
800                                         dx = max_ff(dx, cmp[a].x - clipr->xmax);
801                                 if (cmp[a].y < clipr->ymin)
802                                         dy = min_ff(dy, cmp[a].y - clipr->ymin);
803                                 else if (cmp[a].y > clipr->ymax)
804                                         dy = max_ff(dy, cmp[a].y - clipr->ymax);
805                         }
806                 }
807                 for (a = 0; a < cuma->totpoint; a++) {
808                         if (cmp[a].flag & CUMA_SELECT) {
809                                 cmp[a].x -= dx;
810                                 cmp[a].y -= dy;
811                         }
812                 }
813
814                 /* ensure zoom-level respects clipping */
815                 if (BLI_rctf_size_x(&cumap->curr) > BLI_rctf_size_x(&cumap->clipr)) {
816                         cumap->curr.xmin = cumap->clipr.xmin;
817                         cumap->curr.xmax = cumap->clipr.xmax;
818                 }
819                 if (BLI_rctf_size_y(&cumap->curr) > BLI_rctf_size_y(&cumap->clipr)) {
820                         cumap->curr.ymin = cumap->clipr.ymin;
821                         cumap->curr.ymax = cumap->clipr.ymax;
822                 }
823         }
824         
825         
826         qsort(cmp, cuma->totpoint, sizeof(CurveMapPoint), sort_curvepoints);
827         
828         /* remove doubles, threshold set on 1% of default range */
829         if (rem_doubles && cuma->totpoint > 2) {
830                 for (a = 0; a < cuma->totpoint - 1; a++) {
831                         dx = cmp[a].x - cmp[a + 1].x;
832                         dy = cmp[a].y - cmp[a + 1].y;
833                         if (sqrtf(dx * dx + dy * dy) < thresh) {
834                                 if (a == 0) {
835                                         cmp[a + 1].flag |= CUMA_HANDLE_VECTOR;
836                                         if (cmp[a + 1].flag & CUMA_SELECT)
837                                                 cmp[a].flag |= CUMA_SELECT;
838                                 }
839                                 else {
840                                         cmp[a].flag |= CUMA_HANDLE_VECTOR;
841                                         if (cmp[a].flag & CUMA_SELECT)
842                                                 cmp[a + 1].flag |= CUMA_SELECT;
843                                 }
844                                 break;  /* we assume 1 deletion per edit is ok */
845                         }
846                 }
847                 if (a != cuma->totpoint - 1)
848                         curvemap_remove(cuma, 2);
849         }
850         curvemap_make_table(cuma, clipr);
851 }
852
853 void curvemapping_changed_all(CurveMapping *cumap)
854 {
855         int a, cur = cumap->cur;
856
857         for (a = 0; a < CM_TOT; a++) {
858                 if (cumap->cm[a].curve) {
859                         cumap->cur = a;
860                         curvemapping_changed(cumap, false);
861                 }
862         }
863
864         cumap->cur = cur;
865 }
866
867 /* table should be verified */
868 float curvemap_evaluateF(const CurveMap *cuma, float value)
869 {
870         float fi;
871         int i;
872
873         /* index in table */
874         fi = (value - cuma->mintable) * cuma->range;
875         i = (int)fi;
876         
877         /* fi is table float index and should check against table range i.e. [0.0 CM_TABLE] */
878         if (fi < 0.0f || fi > CM_TABLE)
879                 return curvemap_calc_extend(cuma, value, &cuma->table[0].x, &cuma->table[CM_TABLE].x);
880         else {
881                 if (i < 0) return cuma->table[0].y;
882                 if (i >= CM_TABLE) return cuma->table[CM_TABLE].y;
883                 
884                 fi = fi - (float)i;
885                 return (1.0f - fi) * cuma->table[i].y + (fi) * cuma->table[i + 1].y;
886         }
887 }
888
889 /* works with curve 'cur' */
890 float curvemapping_evaluateF(const CurveMapping *cumap, int cur, float value)
891 {
892         const CurveMap *cuma = cumap->cm + cur;
893         float val = curvemap_evaluateF(cuma, value);
894
895         /* account for clipping */
896         if (cumap->flag & CUMA_DO_CLIP) {
897                 if (val < cumap->curr.ymin)
898                         val = cumap->curr.ymin;
899                 else if (val > cumap->curr.ymax)
900                         val = cumap->curr.ymax;
901         }
902
903         return val;
904 }
905
906 /* vector case */
907 void curvemapping_evaluate3F(const CurveMapping *cumap, float vecout[3], const float vecin[3])
908 {
909         vecout[0] = curvemap_evaluateF(&cumap->cm[0], vecin[0]);
910         vecout[1] = curvemap_evaluateF(&cumap->cm[1], vecin[1]);
911         vecout[2] = curvemap_evaluateF(&cumap->cm[2], vecin[2]);
912 }
913
914 /* RGB case, no black/white points, no premult */
915 void curvemapping_evaluateRGBF(const CurveMapping *cumap, float vecout[3], const float vecin[3])
916 {
917         vecout[0] = curvemap_evaluateF(&cumap->cm[0], curvemap_evaluateF(&cumap->cm[3], vecin[0]));
918         vecout[1] = curvemap_evaluateF(&cumap->cm[1], curvemap_evaluateF(&cumap->cm[3], vecin[1]));
919         vecout[2] = curvemap_evaluateF(&cumap->cm[2], curvemap_evaluateF(&cumap->cm[3], vecin[2]));
920 }
921
922 /** same as #curvemapping_evaluate_premulRGBF
923  * but black/bwmul are passed as args for the compositor
924  * where they can change per pixel.
925  *
926  * Use in conjunction with #curvemapping_set_black_white_ex
927  *
928  * \param black Use instead of cumap->black
929  * \param bwmul Use instead of cumap->bwmul
930  */
931 void curvemapping_evaluate_premulRGBF_ex(const CurveMapping *cumap, float vecout[3], const float vecin[3],
932                                          const float black[3], const float bwmul[3])
933 {
934         vecout[0] = curvemap_evaluateF(&cumap->cm[0], (vecin[0] - black[0]) * bwmul[0]);
935         vecout[1] = curvemap_evaluateF(&cumap->cm[1], (vecin[1] - black[1]) * bwmul[1]);
936         vecout[2] = curvemap_evaluateF(&cumap->cm[2], (vecin[2] - black[2]) * bwmul[2]);
937 }
938
939 /* RGB with black/white points and premult. tables are checked */
940 void curvemapping_evaluate_premulRGBF(const CurveMapping *cumap, float vecout[3], const float vecin[3])
941 {
942         vecout[0] = curvemap_evaluateF(&cumap->cm[0], (vecin[0] - cumap->black[0]) * cumap->bwmul[0]);
943         vecout[1] = curvemap_evaluateF(&cumap->cm[1], (vecin[1] - cumap->black[1]) * cumap->bwmul[1]);
944         vecout[2] = curvemap_evaluateF(&cumap->cm[2], (vecin[2] - cumap->black[2]) * cumap->bwmul[2]);
945 }
946
947 /* same as above, byte version */
948 void curvemapping_evaluate_premulRGB(const CurveMapping *cumap, unsigned char vecout_byte[3], const unsigned char vecin_byte[3])
949 {
950         float vecin[3], vecout[3];
951
952         vecin[0] = (float) vecin_byte[0] / 255.0f;
953         vecin[1] = (float) vecin_byte[1] / 255.0f;
954         vecin[2] = (float) vecin_byte[2] / 255.0f;
955
956         curvemapping_evaluate_premulRGBF(cumap, vecout, vecin);
957
958         vecout_byte[0] = FTOCHAR(vecout[0]);
959         vecout_byte[1] = FTOCHAR(vecout[1]);
960         vecout_byte[2] = FTOCHAR(vecout[2]);
961 }
962
963 int curvemapping_RGBA_does_something(const CurveMapping *cumap)
964 {
965         int a;
966         
967         if (cumap->black[0] != 0.0f) return 1;
968         if (cumap->black[1] != 0.0f) return 1;
969         if (cumap->black[2] != 0.0f) return 1;
970         if (cumap->white[0] != 1.0f) return 1;
971         if (cumap->white[1] != 1.0f) return 1;
972         if (cumap->white[2] != 1.0f) return 1;
973         
974         for (a = 0; a < CM_TOT; a++) {
975                 if (cumap->cm[a].curve) {
976                         if (cumap->cm[a].totpoint != 2) return 1;
977                         
978                         if (cumap->cm[a].curve[0].x != 0.0f) return 1;
979                         if (cumap->cm[a].curve[0].y != 0.0f) return 1;
980                         if (cumap->cm[a].curve[1].x != 1.0f) return 1;
981                         if (cumap->cm[a].curve[1].y != 1.0f) return 1;
982                 }
983         }
984         return 0;
985 }
986
987 void curvemapping_initialize(CurveMapping *cumap)
988 {
989         int a;
990         
991         if (cumap == NULL) return;
992         
993         for (a = 0; a < CM_TOT; a++) {
994                 if (cumap->cm[a].table == NULL)
995                         curvemap_make_table(cumap->cm + a, &cumap->clipr);
996         }
997 }
998
999 void curvemapping_table_RGBA(const CurveMapping *cumap, float **array, int *size)
1000 {
1001         int a;
1002         
1003         *size = CM_TABLE + 1;
1004         *array = MEM_callocN(sizeof(float) * (*size) * 4, "CurveMapping");
1005
1006         for (a = 0; a < *size; a++) {
1007                 if (cumap->cm[0].table)
1008                         (*array)[a * 4 + 0] = cumap->cm[0].table[a].y;
1009                 if (cumap->cm[1].table)
1010                         (*array)[a * 4 + 1] = cumap->cm[1].table[a].y;
1011                 if (cumap->cm[2].table)
1012                         (*array)[a * 4 + 2] = cumap->cm[2].table[a].y;
1013                 if (cumap->cm[3].table)
1014                         (*array)[a * 4 + 3] = cumap->cm[3].table[a].y;
1015         }
1016 }
1017
1018 /* ***************** Histogram **************** */
1019
1020 #define INV_255     (1.f / 255.f)
1021
1022 BLI_INLINE int get_bin_float(float f)
1023 {
1024         int bin = (int)((f * 255.0f) + 0.5f);  /* 0.5 to prevent quantisation differences */
1025
1026         /* note: clamp integer instead of float to avoid problems with NaN */
1027         CLAMP(bin, 0, 255);
1028
1029         return bin;
1030 }
1031
1032 static void save_sample_line(Scopes *scopes, const int idx, const float fx, const float rgb[3], const float ycc[3])
1033 {
1034         float yuv[3];
1035
1036         /* vectorscope*/
1037         rgb_to_yuv(rgb[0], rgb[1], rgb[2], &yuv[0], &yuv[1], &yuv[2]);
1038         scopes->vecscope[idx + 0] = yuv[1];
1039         scopes->vecscope[idx + 1] = yuv[2];
1040
1041         /* waveform */
1042         switch (scopes->wavefrm_mode) {
1043                 case SCOPES_WAVEFRM_RGB:
1044                 case SCOPES_WAVEFRM_RGB_PARADE:
1045                         scopes->waveform_1[idx + 0] = fx;
1046                         scopes->waveform_1[idx + 1] = rgb[0];
1047                         scopes->waveform_2[idx + 0] = fx;
1048                         scopes->waveform_2[idx + 1] = rgb[1];
1049                         scopes->waveform_3[idx + 0] = fx;
1050                         scopes->waveform_3[idx + 1] = rgb[2];
1051                         break;
1052                 case SCOPES_WAVEFRM_LUMA:
1053                         scopes->waveform_1[idx + 0] = fx;
1054                         scopes->waveform_1[idx + 1] = ycc[0];
1055                         break;
1056                 case SCOPES_WAVEFRM_YCC_JPEG:
1057                 case SCOPES_WAVEFRM_YCC_709:
1058                 case SCOPES_WAVEFRM_YCC_601:
1059                         scopes->waveform_1[idx + 0] = fx;
1060                         scopes->waveform_1[idx + 1] = ycc[0];
1061                         scopes->waveform_2[idx + 0] = fx;
1062                         scopes->waveform_2[idx + 1] = ycc[1];
1063                         scopes->waveform_3[idx + 0] = fx;
1064                         scopes->waveform_3[idx + 1] = ycc[2];
1065                         break;
1066         }
1067 }
1068
1069 void BKE_histogram_update_sample_line(Histogram *hist, ImBuf *ibuf, const ColorManagedViewSettings *view_settings,
1070                                       const ColorManagedDisplaySettings *display_settings)
1071 {
1072         int i, x, y;
1073         const float *fp;
1074         unsigned char *cp;
1075
1076         int x1 = 0.5f + hist->co[0][0] * ibuf->x;
1077         int x2 = 0.5f + hist->co[1][0] * ibuf->x;
1078         int y1 = 0.5f + hist->co[0][1] * ibuf->y;
1079         int y2 = 0.5f + hist->co[1][1] * ibuf->y;
1080
1081         struct ColormanageProcessor *cm_processor = NULL;
1082
1083         hist->channels = 3;
1084         hist->x_resolution = 256;
1085         hist->xmax = 1.0f;
1086         /* hist->ymax = 1.0f; */ /* now do this on the operator _only_ */
1087
1088         if (ibuf->rect == NULL && ibuf->rect_float == NULL) return;
1089
1090         if (ibuf->rect_float)
1091                 cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings);
1092
1093         for (i = 0; i < 256; i++) {
1094                 x = (int)(0.5f + x1 + (float)i * (x2 - x1) / 255.0f);
1095                 y = (int)(0.5f + y1 + (float)i * (y2 - y1) / 255.0f);
1096
1097                 if (x < 0 || y < 0 || x >= ibuf->x || y >= ibuf->y) {
1098                         hist->data_luma[i] = hist->data_r[i] = hist->data_g[i] = hist->data_b[i] = hist->data_a[i] = 0.0f;
1099                 }
1100                 else {
1101                         if (ibuf->rect_float) {
1102                                 float rgba[4];
1103                                 fp = (ibuf->rect_float + (ibuf->channels) * (y * ibuf->x + x));
1104
1105                                 switch (ibuf->channels) {
1106                                         case 4:
1107                                                 copy_v4_v4(rgba, fp);
1108                                                 IMB_colormanagement_processor_apply_v4(cm_processor, rgba);
1109                                                 break;
1110                                         case 3:
1111                                                 copy_v3_v3(rgba, fp);
1112                                                 IMB_colormanagement_processor_apply_v3(cm_processor, rgba);
1113                                                 rgba[3] = 1.0f;
1114                                                 break;
1115                                         case 2:
1116                                                 copy_v3_fl(rgba, fp[0]);
1117                                                 rgba[3] = fp[1];
1118                                                 break;
1119                                         case 1:
1120                                                 copy_v3_fl(rgba, fp[0]);
1121                                                 rgba[3] = 1.0f;
1122                                                 break;
1123                                         default:
1124                                                 BLI_assert(0);
1125                                 }
1126
1127                                 hist->data_luma[i]  = IMB_colormanagement_get_luminance(rgba);
1128                                 hist->data_r[i]     = rgba[0];
1129                                 hist->data_g[i]     = rgba[1];
1130                                 hist->data_b[i]     = rgba[2];
1131                                 hist->data_a[i]     = rgba[3];
1132                         }
1133                         else if (ibuf->rect) {
1134                                 cp = (unsigned char *)(ibuf->rect + y * ibuf->x + x);
1135                                 hist->data_luma[i]  = (float)IMB_colormanagement_get_luminance_byte(cp) / 255.0f;
1136                                 hist->data_r[i]     = (float)cp[0] / 255.0f;
1137                                 hist->data_g[i]     = (float)cp[1] / 255.0f;
1138                                 hist->data_b[i]     = (float)cp[2] / 255.0f;
1139                                 hist->data_a[i]     = (float)cp[3] / 255.0f;
1140                         }
1141                 }
1142         }
1143
1144         if (cm_processor)
1145                 IMB_colormanagement_processor_free(cm_processor);
1146 }
1147
1148 /* if view_settings, it also applies this to byte buffers */
1149 typedef struct ScopesUpdateData {
1150         Scopes *scopes;
1151         const ImBuf *ibuf;
1152         struct ColormanageProcessor *cm_processor;
1153         const unsigned char *display_buffer;
1154         const int ycc_mode;
1155
1156         unsigned int *bin_lum, *bin_r, *bin_g, *bin_b, *bin_a;
1157 } ScopesUpdateData;
1158
1159 typedef struct ScopesUpdateDataChunk {
1160         unsigned int bin_lum[256];
1161         unsigned int bin_r[256];
1162         unsigned int bin_g[256];
1163         unsigned int bin_b[256];
1164         unsigned int bin_a[256];
1165         float min[3], max[3];
1166 } ScopesUpdateDataChunk;
1167
1168 static void scopes_update_cb(void *userdata, void *userdata_chunk, const int y, const int UNUSED(threadid))
1169 {
1170         const ScopesUpdateData *data = userdata;
1171
1172         Scopes *scopes = data->scopes;
1173         const ImBuf *ibuf = data->ibuf;
1174         struct ColormanageProcessor *cm_processor = data->cm_processor;
1175         const unsigned char *display_buffer = data->display_buffer;
1176         const int ycc_mode = data->ycc_mode;
1177
1178         ScopesUpdateDataChunk *data_chunk = userdata_chunk;
1179         unsigned int *bin_lum = data_chunk->bin_lum;
1180         unsigned int *bin_r = data_chunk->bin_r;
1181         unsigned int *bin_g = data_chunk->bin_g;
1182         unsigned int *bin_b = data_chunk->bin_b;
1183         unsigned int *bin_a = data_chunk->bin_a;
1184         float *min = data_chunk->min;
1185         float *max = data_chunk->max;
1186
1187         const float *rf = NULL;
1188         const unsigned char *rc = NULL;
1189         const int rows_per_sample_line = ibuf->y / scopes->sample_lines;
1190         const int savedlines = y / rows_per_sample_line;
1191         const bool do_sample_line = (savedlines < scopes->sample_lines) && (y % rows_per_sample_line) == 0;
1192         const bool is_float = (ibuf->rect_float != NULL);
1193
1194         if (is_float)
1195                 rf = ibuf->rect_float + ((size_t)y) * ibuf->x * ibuf->channels;
1196         else {
1197                 rc = display_buffer + ((size_t)y) * ibuf->x * ibuf->channels;
1198         }
1199
1200         for (int x = 0; x < ibuf->x; x++) {
1201                 float rgba[4], ycc[3], luma;
1202
1203                 if (is_float) {
1204                         switch (ibuf->channels) {
1205                                 case 4:
1206                                         copy_v4_v4(rgba, rf);
1207                                         IMB_colormanagement_processor_apply_v4(cm_processor, rgba);
1208                                         break;
1209                                 case 3:
1210                                         copy_v3_v3(rgba, rf);
1211                                         IMB_colormanagement_processor_apply_v3(cm_processor, rgba);
1212                                         rgba[3] = 1.0f;
1213                                         break;
1214                                 case 2:
1215                                         copy_v3_fl(rgba, rf[0]);
1216                                         rgba[3] = rf[1];
1217                                         break;
1218                                 case 1:
1219                                         copy_v3_fl(rgba, rf[0]);
1220                                         rgba[3] = 1.0f;
1221                                         break;
1222                                 default:
1223                                         BLI_assert(0);
1224                         }
1225                 }
1226                 else {
1227                         for (int c = 4; c--;)
1228                                 rgba[c] = rc[c] * INV_255;
1229                 }
1230
1231                 /* we still need luma for histogram */
1232                 luma = IMB_colormanagement_get_luminance(rgba);
1233
1234                 /* check for min max */
1235                 if (ycc_mode == -1) {
1236                         minmax_v3v3_v3(min, max, rgba);
1237                 }
1238                 else {
1239                         rgb_to_ycc(rgba[0], rgba[1], rgba[2], &ycc[0], &ycc[1], &ycc[2], ycc_mode);
1240                         mul_v3_fl(ycc, INV_255);
1241                         minmax_v3v3_v3(min, max, ycc);
1242                 }
1243                 /* increment count for histo*/
1244                 bin_lum[get_bin_float(luma)]++;
1245                 bin_r[get_bin_float(rgba[0])]++;
1246                 bin_g[get_bin_float(rgba[1])]++;
1247                 bin_b[get_bin_float(rgba[2])]++;
1248                 bin_a[get_bin_float(rgba[3])]++;
1249
1250                 /* save sample if needed */
1251                 if (do_sample_line) {
1252                         const float fx = (float)x / (float)ibuf->x;
1253                         const int idx = 2 * (ibuf->x * savedlines + x);
1254                         save_sample_line(scopes, idx, fx, rgba, ycc);
1255                 }
1256
1257                 rf += ibuf->channels;
1258                 rc += ibuf->channels;
1259         }
1260 }
1261
1262 static void scopes_update_finalize(void *userdata, void *userdata_chunk)
1263 {
1264         const ScopesUpdateData *data = userdata;
1265         const ScopesUpdateDataChunk *data_chunk = userdata_chunk;
1266
1267         unsigned int *bin_lum = data->bin_lum;
1268         unsigned int *bin_r = data->bin_r;
1269         unsigned int *bin_g = data->bin_g;
1270         unsigned int *bin_b = data->bin_b;
1271         unsigned int *bin_a = data->bin_a;
1272         const unsigned int *bin_lum_c = data_chunk->bin_lum;
1273         const unsigned int *bin_r_c = data_chunk->bin_r;
1274         const unsigned int *bin_g_c = data_chunk->bin_g;
1275         const unsigned int *bin_b_c = data_chunk->bin_b;
1276         const unsigned int *bin_a_c = data_chunk->bin_a;
1277
1278         float (*minmax)[2] = data->scopes->minmax;
1279         const float *min = data_chunk->min;
1280         const float *max = data_chunk->max;
1281
1282         for (int b = 256; b--;) {
1283                 bin_lum[b] += bin_lum_c[b];
1284                 bin_r[b] += bin_r_c[b];
1285                 bin_g[b] += bin_g_c[b];
1286                 bin_b[b] += bin_b_c[b];
1287                 bin_a[b] += bin_a_c[b];
1288         }
1289
1290         for (int c = 3; c--;) {
1291                 if (min[c] < minmax[c][0])
1292                         minmax[c][0] = min[c];
1293                 if (max[c] > minmax[c][1])
1294                         minmax[c][1] = max[c];
1295         }
1296 }
1297
1298 void scopes_update(Scopes *scopes, ImBuf *ibuf, const ColorManagedViewSettings *view_settings,
1299                    const ColorManagedDisplaySettings *display_settings)
1300 {
1301         int a;
1302         unsigned int nl, na, nr, ng, nb;
1303         double divl, diva, divr, divg, divb;
1304         const unsigned char *display_buffer = NULL;
1305         unsigned int bin_lum[256] = {0},
1306                      bin_r[256] = {0},
1307                      bin_g[256] = {0},
1308                      bin_b[256] = {0},
1309                      bin_a[256] = {0};
1310         int ycc_mode = -1;
1311         void *cache_handle = NULL;
1312         struct ColormanageProcessor *cm_processor = NULL;
1313
1314         if (ibuf->rect == NULL && ibuf->rect_float == NULL) return;
1315
1316         if (scopes->ok == 1) return;
1317
1318         if (scopes->hist.ymax == 0.f) scopes->hist.ymax = 1.f;
1319
1320         /* hmmmm */
1321         if (!(ELEM(ibuf->channels, 3, 4))) return;
1322
1323         scopes->hist.channels = 3;
1324         scopes->hist.x_resolution = 256;
1325
1326         switch (scopes->wavefrm_mode) {
1327                 case SCOPES_WAVEFRM_RGB:
1328                         /* fall-through */
1329                 case SCOPES_WAVEFRM_RGB_PARADE:
1330                         ycc_mode = -1;
1331                         break;
1332                 case SCOPES_WAVEFRM_LUMA:
1333                 case SCOPES_WAVEFRM_YCC_JPEG:
1334                         ycc_mode = BLI_YCC_JFIF_0_255;
1335                         break;
1336                 case SCOPES_WAVEFRM_YCC_601:
1337                         ycc_mode = BLI_YCC_ITU_BT601;
1338                         break;
1339                 case SCOPES_WAVEFRM_YCC_709:
1340                         ycc_mode = BLI_YCC_ITU_BT709;
1341                         break;
1342         }
1343
1344         /* convert to number of lines with logarithmic scale */
1345         scopes->sample_lines = (scopes->accuracy * 0.01f) * (scopes->accuracy * 0.01f) * ibuf->y;
1346         CLAMP_MIN(scopes->sample_lines, 1);
1347         
1348         if (scopes->sample_full)
1349                 scopes->sample_lines = ibuf->y;
1350
1351         /* scan the image */
1352         for (a = 0; a < 3; a++) {
1353                 scopes->minmax[a][0] = 25500.0f;
1354                 scopes->minmax[a][1] = -25500.0f;
1355         }
1356         
1357         scopes->waveform_tot = ibuf->x * scopes->sample_lines;
1358         
1359         if (scopes->waveform_1)
1360                 MEM_freeN(scopes->waveform_1);
1361         if (scopes->waveform_2)
1362                 MEM_freeN(scopes->waveform_2);
1363         if (scopes->waveform_3)
1364                 MEM_freeN(scopes->waveform_3);
1365         if (scopes->vecscope)
1366                 MEM_freeN(scopes->vecscope);
1367         
1368         scopes->waveform_1 = MEM_callocN(scopes->waveform_tot * 2 * sizeof(float), "waveform point channel 1");
1369         scopes->waveform_2 = MEM_callocN(scopes->waveform_tot * 2 * sizeof(float), "waveform point channel 2");
1370         scopes->waveform_3 = MEM_callocN(scopes->waveform_tot * 2 * sizeof(float), "waveform point channel 3");
1371         scopes->vecscope = MEM_callocN(scopes->waveform_tot * 2 * sizeof(float), "vectorscope point channel");
1372         
1373         if (ibuf->rect_float) {
1374                 cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings);
1375         }
1376         else {
1377                 display_buffer = (const unsigned char *)IMB_display_buffer_acquire(
1378                                                             ibuf, view_settings, display_settings, &cache_handle);
1379         }
1380
1381         /* Keep number of threads in sync with the merge parts below. */
1382         ScopesUpdateData data = {
1383                 .scopes = scopes, . ibuf = ibuf,
1384                 .cm_processor = cm_processor, .display_buffer = display_buffer, .ycc_mode = ycc_mode,
1385                 .bin_lum = bin_lum, .bin_r = bin_r, .bin_g = bin_g, .bin_b = bin_b, .bin_a = bin_a,
1386         };
1387         ScopesUpdateDataChunk data_chunk = {{0}};
1388         INIT_MINMAX(data_chunk.min, data_chunk.max);
1389
1390         BLI_task_parallel_range_finalize(0, ibuf->y, &data, &data_chunk, sizeof(data_chunk),
1391                                          scopes_update_cb, scopes_update_finalize, ibuf->y > 256, false);
1392
1393         /* test for nicer distribution even - non standard, leave it out for a while */
1394 #if 0
1395         for (a = 0; a < 256; a++) {
1396                 bin_lum[a] = sqrt (bin_lum[a]);
1397                 bin_r[a] = sqrt(bin_r[a]);
1398                 bin_g[a] = sqrt(bin_g[a]);
1399                 bin_b[a] = sqrt(bin_b[a]);
1400                 bin_a[a] = sqrt(bin_a[a]);
1401         }
1402 #endif
1403         
1404         /* convert hist data to float (proportional to max count) */
1405         nl = na = nr = nb = ng = 0;
1406         for (a = 0; a < 256; a++) {
1407                 if (bin_lum[a] > nl) nl = bin_lum[a];
1408                 if (bin_r[a]   > nr) nr = bin_r[a];
1409                 if (bin_g[a]   > ng) ng = bin_g[a];
1410                 if (bin_b[a]   > nb) nb = bin_b[a];
1411                 if (bin_a[a]   > na) na = bin_a[a];
1412         }
1413         divl = nl ? 1.0 / (double)nl : 1.0;
1414         diva = na ? 1.0 / (double)na : 1.0;
1415         divr = nr ? 1.0 / (double)nr : 1.0;
1416         divg = ng ? 1.0 / (double)ng : 1.0;
1417         divb = nb ? 1.0 / (double)nb : 1.0;
1418         
1419         for (a = 0; a < 256; a++) {
1420                 scopes->hist.data_luma[a] = bin_lum[a] * divl;
1421                 scopes->hist.data_r[a] = bin_r[a] * divr;
1422                 scopes->hist.data_g[a] = bin_g[a] * divg;
1423                 scopes->hist.data_b[a] = bin_b[a] * divb;
1424                 scopes->hist.data_a[a] = bin_a[a] * diva;
1425         }
1426
1427         if (cm_processor)
1428                 IMB_colormanagement_processor_free(cm_processor);
1429         if (cache_handle)
1430                 IMB_display_buffer_release(cache_handle);
1431         
1432         scopes->ok = 1;
1433 }
1434
1435 void scopes_free(Scopes *scopes)
1436 {
1437         if (scopes->waveform_1) {
1438                 MEM_freeN(scopes->waveform_1);
1439                 scopes->waveform_1 = NULL;
1440         }
1441         if (scopes->waveform_2) {
1442                 MEM_freeN(scopes->waveform_2);
1443                 scopes->waveform_2 = NULL;
1444         }
1445         if (scopes->waveform_3) {
1446                 MEM_freeN(scopes->waveform_3);
1447                 scopes->waveform_3 = NULL;
1448         }
1449         if (scopes->vecscope) {
1450                 MEM_freeN(scopes->vecscope);
1451                 scopes->vecscope = NULL;
1452         }
1453 }
1454
1455 void scopes_new(Scopes *scopes)
1456 {
1457         scopes->accuracy = 30.0;
1458         scopes->hist.mode = HISTO_MODE_RGB;
1459         scopes->wavefrm_alpha = 0.3;
1460         scopes->vecscope_alpha = 0.3;
1461         scopes->wavefrm_height = 100;
1462         scopes->vecscope_height = 100;
1463         scopes->hist.height = 100;
1464         scopes->ok = 0;
1465         scopes->waveform_1 = NULL;
1466         scopes->waveform_2 = NULL;
1467         scopes->waveform_3 = NULL;
1468         scopes->vecscope = NULL;
1469 }
1470
1471 void BKE_color_managed_display_settings_init(ColorManagedDisplaySettings *settings)
1472 {
1473         const char *display_name = IMB_colormanagement_display_get_default_name();
1474
1475         BLI_strncpy(settings->display_device, display_name, sizeof(settings->display_device));
1476 }
1477
1478 void BKE_color_managed_display_settings_copy(ColorManagedDisplaySettings *new_settings,
1479                                              const ColorManagedDisplaySettings *settings)
1480 {
1481         BLI_strncpy(new_settings->display_device, settings->display_device, sizeof(new_settings->display_device));
1482 }
1483
1484 void BKE_color_managed_view_settings_init(ColorManagedViewSettings *settings)
1485 {
1486         /* OCIO_TODO: use default view transform here when OCIO is completely integrated
1487          *            and proper versioning stuff is added.
1488          *            for now use NONE to be compatible with all current files
1489          */
1490         BLI_strncpy(settings->view_transform, "Default", sizeof(settings->view_transform));
1491         BLI_strncpy(settings->look, "None", sizeof(settings->look));
1492
1493         settings->gamma = 1.0f;
1494         settings->exposure = 0.0f;
1495 }
1496
1497 void BKE_color_managed_view_settings_copy(ColorManagedViewSettings *new_settings,
1498                                           const ColorManagedViewSettings *settings)
1499 {
1500         BLI_strncpy(new_settings->look, settings->look, sizeof(new_settings->look));
1501         BLI_strncpy(new_settings->view_transform, settings->view_transform, sizeof(new_settings->view_transform));
1502
1503         new_settings->flag = settings->flag;
1504         new_settings->exposure = settings->exposure;
1505         new_settings->gamma = settings->gamma;
1506
1507         if (settings->curve_mapping)
1508                 new_settings->curve_mapping = curvemapping_copy(settings->curve_mapping);
1509         else
1510                 new_settings->curve_mapping = NULL;
1511 }
1512
1513 void BKE_color_managed_view_settings_free(ColorManagedViewSettings *settings)
1514 {
1515         if (settings->curve_mapping)
1516                 curvemapping_free(settings->curve_mapping);
1517 }
1518
1519 void BKE_color_managed_colorspace_settings_init(ColorManagedColorspaceSettings *colorspace_settings)
1520 {
1521         BLI_strncpy(colorspace_settings->name, "", sizeof(colorspace_settings->name));
1522 }
1523
1524 void BKE_color_managed_colorspace_settings_copy(ColorManagedColorspaceSettings *colorspace_settings,
1525                                                 const ColorManagedColorspaceSettings *settings)
1526 {
1527         BLI_strncpy(colorspace_settings->name, settings->name, sizeof(colorspace_settings->name));
1528 }
1529
1530 bool BKE_color_managed_colorspace_settings_equals(const ColorManagedColorspaceSettings *settings1,
1531                                                   const ColorManagedColorspaceSettings *settings2)
1532 {
1533         return STREQ(settings1->name, settings2->name);
1534 }