Depsgraph: Move evaluation debug prints to depsgraph
[blender.git] / source / blender / blenkernel / intern / curve.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/curve.c
29  *  \ingroup bke
30  */
31
32
33 #include <math.h>  // floor
34 #include <string.h>
35 #include <stdlib.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include "BLI_blenlib.h"
40 #include "BLI_math.h"
41 #include "BLI_utildefines.h"
42 #include "BLI_ghash.h"
43
44 #include "DNA_anim_types.h"
45 #include "DNA_curve_types.h"
46 #include "DNA_material_types.h"
47
48 /* for dereferencing pointers */
49 #include "DNA_key_types.h"
50 #include "DNA_scene_types.h"
51 #include "DNA_vfont_types.h"
52 #include "DNA_object_types.h"
53
54 #include "BKE_animsys.h"
55 #include "BKE_curve.h"
56 #include "BKE_depsgraph.h"
57 #include "BKE_displist.h"
58 #include "BKE_font.h"
59 #include "BKE_global.h"
60 #include "BKE_key.h"
61 #include "BKE_library.h"
62 #include "BKE_library_query.h"
63 #include "BKE_library_remap.h"
64 #include "BKE_main.h"
65 #include "BKE_object.h"
66 #include "BKE_material.h"
67
68 #include "DEG_depsgraph.h"
69
70 /* globals */
71
72 /* local */
73 static int cu_isectLL(const float v1[3], const float v2[3], const float v3[3], const float v4[3],
74                       short cox, short coy,
75                       float *lambda, float *mu, float vec[3]);
76
77 /* frees editcurve entirely */
78 void BKE_curve_editfont_free(Curve *cu)
79 {
80         if (cu->editfont) {
81                 EditFont *ef = cu->editfont;
82
83                 if (ef->textbuf)
84                         MEM_freeN(ef->textbuf);
85                 if (ef->textbufinfo)
86                         MEM_freeN(ef->textbufinfo);
87                 if (ef->selboxes)
88                         MEM_freeN(ef->selboxes);
89
90                 MEM_freeN(ef);
91                 cu->editfont = NULL;
92         }
93 }
94
95 static void curve_editNurb_keyIndex_cv_free_cb(void *val)
96 {
97         CVKeyIndex *index = val;
98         MEM_freeN(index->orig_cv);
99         MEM_freeN(val);
100 }
101
102 void BKE_curve_editNurb_keyIndex_delCV(GHash *keyindex, const void *cv)
103 {
104         BLI_assert(keyindex != NULL);
105         BLI_ghash_remove(keyindex, cv, NULL, curve_editNurb_keyIndex_cv_free_cb);
106 }
107
108 void BKE_curve_editNurb_keyIndex_free(GHash **keyindex)
109 {
110         if (!(*keyindex)) {
111                 return;
112         }
113         BLI_ghash_free(*keyindex, NULL, curve_editNurb_keyIndex_cv_free_cb);
114         *keyindex = NULL;
115 }
116
117 void BKE_curve_editNurb_free(Curve *cu)
118 {
119         if (cu->editnurb) {
120                 BKE_nurbList_free(&cu->editnurb->nurbs);
121                 BKE_curve_editNurb_keyIndex_free(&cu->editnurb->keyindex);
122                 MEM_freeN(cu->editnurb);
123                 cu->editnurb = NULL;
124         }
125 }
126
127 /** Free (or release) any data used by this curve (does not free the curve itself). */
128 void BKE_curve_free(Curve *cu)
129 {
130         BKE_animdata_free((ID *)cu, false);
131
132         BKE_nurbList_free(&cu->nurb);
133         BKE_curve_editfont_free(cu);
134
135         BKE_curve_editNurb_free(cu);
136
137         MEM_SAFE_FREE(cu->mat);
138         MEM_SAFE_FREE(cu->str);
139         MEM_SAFE_FREE(cu->strinfo);
140         MEM_SAFE_FREE(cu->bb);
141         MEM_SAFE_FREE(cu->tb);
142 }
143
144 void BKE_curve_init(Curve *cu)
145 {
146         /* BLI_assert(MEMCMP_STRUCT_OFS_IS_ZERO(cu, id)); */  /* cu->type is already initialized... */
147
148         copy_v3_fl(cu->size, 1.0f);
149         cu->flag = CU_FRONT | CU_BACK | CU_DEFORM_BOUNDS_OFF | CU_PATH_RADIUS;
150         cu->pathlen = 100;
151         cu->resolu = cu->resolv = (cu->type == OB_SURF) ? 4 : 12;
152         cu->width = 1.0;
153         cu->wordspace = 1.0;
154         cu->spacing = cu->linedist = 1.0;
155         cu->fsize = 1.0;
156         cu->ulheight = 0.05;
157         cu->texflag = CU_AUTOSPACE;
158         cu->smallcaps_scale = 0.75f;
159         /* XXX: this one seems to be the best one in most cases, at least for curve deform... */
160         cu->twist_mode = CU_TWIST_MINIMUM;
161         cu->bevfac1 = 0.0f;
162         cu->bevfac2 = 1.0f;
163         cu->bevfac1_mapping = CU_BEVFAC_MAP_RESOLU;
164         cu->bevfac2_mapping = CU_BEVFAC_MAP_RESOLU;
165
166         cu->bb = BKE_boundbox_alloc_unit();
167
168         if (cu->type == OB_FONT) {
169                 cu->vfont = cu->vfontb = cu->vfonti = cu->vfontbi = BKE_vfont_builtin_get();
170                 cu->vfont->id.us += 4;
171                 cu->str = MEM_malloc_arrayN(12, sizeof(unsigned char), "str");
172                 BLI_strncpy(cu->str, "Text", 12);
173                 cu->len = cu->len_wchar = cu->pos = 4;
174                 cu->strinfo = MEM_calloc_arrayN(12, sizeof(CharInfo), "strinfo new");
175                 cu->totbox = cu->actbox = 1;
176                 cu->tb = MEM_calloc_arrayN(MAXTEXTBOX, sizeof(TextBox), "textbox");
177                 cu->tb[0].w = cu->tb[0].h = 0.0;
178         }
179 }
180
181 Curve *BKE_curve_add(Main *bmain, const char *name, int type)
182 {
183         Curve *cu;
184
185         cu = BKE_libblock_alloc(bmain, ID_CU, name, 0);
186         cu->type = type;
187
188         BKE_curve_init(cu);
189
190         return cu;
191 }
192
193 /**
194  * Only copy internal data of Curve ID from source to already allocated/initialized destination.
195  * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
196  *
197  * WARNING! This function will not handle ID user count!
198  *
199  * \param flag  Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
200  */
201 void BKE_curve_copy_data(Main *bmain, Curve *cu_dst, const Curve *cu_src, const int flag)
202 {
203         BLI_listbase_clear(&cu_dst->nurb);
204         BKE_nurbList_duplicate(&(cu_dst->nurb), &(cu_src->nurb));
205
206         cu_dst->mat = MEM_dupallocN(cu_src->mat);
207
208         cu_dst->str = MEM_dupallocN(cu_src->str);
209         cu_dst->strinfo = MEM_dupallocN(cu_src->strinfo);
210         cu_dst->tb = MEM_dupallocN(cu_src->tb);
211         cu_dst->bb = MEM_dupallocN(cu_src->bb);
212
213         if (cu_src->key) {
214                 BKE_id_copy_ex(bmain, &cu_src->key->id, (ID **)&cu_dst->key, flag, false);
215         }
216
217         cu_dst->editnurb = NULL;
218         cu_dst->editfont = NULL;
219 }
220
221 Curve *BKE_curve_copy(Main *bmain, const Curve *cu)
222 {
223         Curve *cu_copy;
224         BKE_id_copy_ex(bmain, &cu->id, (ID **)&cu_copy, 0, false);
225         return cu_copy;
226 }
227
228 void BKE_curve_make_local(Main *bmain, Curve *cu, const bool lib_local)
229 {
230         BKE_id_make_local_generic(bmain, &cu->id, true, lib_local);
231 }
232
233 /* Get list of nurbs from editnurbs structure */
234 ListBase *BKE_curve_editNurbs_get(Curve *cu)
235 {
236         if (cu->editnurb) {
237                 return &cu->editnurb->nurbs;
238         }
239
240         return NULL;
241 }
242
243 short BKE_curve_type_get(Curve *cu)
244 {
245         Nurb *nu;
246         int type = cu->type;
247
248         if (cu->vfont) {
249                 return OB_FONT;
250         }
251
252         if (!cu->type) {
253                 type = OB_CURVE;
254
255                 for (nu = cu->nurb.first; nu; nu = nu->next) {
256                         if (nu->pntsv > 1) {
257                                 type = OB_SURF;
258                         }
259                 }
260         }
261
262         return type;
263 }
264
265 void BKE_curve_curve_dimension_update(Curve *cu)
266 {
267         ListBase *nurbs = BKE_curve_nurbs_get(cu);
268         Nurb *nu = nurbs->first;
269
270         if (cu->flag & CU_3D) {
271                 for (; nu; nu = nu->next) {
272                         nu->flag &= ~CU_2D;
273                 }
274         }
275         else {
276                 for (; nu; nu = nu->next) {
277                         nu->flag |= CU_2D;
278                         BKE_nurb_test2D(nu);
279
280                         /* since the handles are moved they need to be auto-located again */
281                         if (nu->type == CU_BEZIER)
282                                 BKE_nurb_handles_calc(nu);
283                 }
284         }
285 }
286
287 void BKE_curve_type_test(Object *ob)
288 {
289         ob->type = BKE_curve_type_get(ob->data);
290
291         if (ob->type == OB_CURVE)
292                 BKE_curve_curve_dimension_update((Curve *)ob->data);
293 }
294
295 void BKE_curve_boundbox_calc(Curve *cu, float r_loc[3], float r_size[3])
296 {
297         BoundBox *bb;
298         float min[3], max[3];
299         float mloc[3], msize[3];
300
301         if (cu->bb == NULL) cu->bb = MEM_callocN(sizeof(BoundBox), "boundbox");
302         bb = cu->bb;
303
304         if (!r_loc) r_loc = mloc;
305         if (!r_size) r_size = msize;
306
307         INIT_MINMAX(min, max);
308         if (!BKE_curve_minmax(cu, true, min, max)) {
309                 min[0] = min[1] = min[2] = -1.0f;
310                 max[0] = max[1] = max[2] = 1.0f;
311         }
312
313         mid_v3_v3v3(r_loc, min, max);
314
315         r_size[0] = (max[0] - min[0]) / 2.0f;
316         r_size[1] = (max[1] - min[1]) / 2.0f;
317         r_size[2] = (max[2] - min[2]) / 2.0f;
318
319         BKE_boundbox_init_from_minmax(bb, min, max);
320
321         bb->flag &= ~BOUNDBOX_DIRTY;
322 }
323
324 BoundBox *BKE_curve_boundbox_get(Object *ob)
325 {
326         Curve *cu = ob->data;
327
328         if (ob->bb)
329                 return ob->bb;
330
331         if (cu->bb == NULL || (cu->bb->flag & BOUNDBOX_DIRTY)) {
332                 BKE_curve_texspace_calc(cu);
333         }
334
335         return cu->bb;
336 }
337
338 void BKE_curve_texspace_calc(Curve *cu)
339 {
340         float loc[3], size[3];
341         int a;
342
343         BKE_curve_boundbox_calc(cu, loc, size);
344
345         if (cu->texflag & CU_AUTOSPACE) {
346                 for (a = 0; a < 3; a++) {
347                         if (size[a] == 0.0f) size[a] = 1.0f;
348                         else if (size[a] > 0.0f && size[a] < 0.00001f) size[a] = 0.00001f;
349                         else if (size[a] < 0.0f && size[a] > -0.00001f) size[a] = -0.00001f;
350                 }
351
352                 copy_v3_v3(cu->loc, loc);
353                 copy_v3_v3(cu->size, size);
354                 zero_v3(cu->rot);
355         }
356 }
357
358 void BKE_curve_texspace_get(Curve *cu, float r_loc[3], float r_rot[3], float r_size[3])
359 {
360         if (cu->bb == NULL || (cu->bb->flag & BOUNDBOX_DIRTY)) {
361                 BKE_curve_texspace_calc(cu);
362         }
363
364         if (r_loc) copy_v3_v3(r_loc,  cu->loc);
365         if (r_rot) copy_v3_v3(r_rot,  cu->rot);
366         if (r_size) copy_v3_v3(r_size, cu->size);
367 }
368
369 bool BKE_nurbList_index_get_co(ListBase *nurb, const int index, float r_co[3])
370 {
371         Nurb *nu;
372         int tot = 0;
373
374         for (nu = nurb->first; nu; nu = nu->next) {
375                 int tot_nu;
376                 if (nu->type == CU_BEZIER) {
377                         tot_nu = nu->pntsu;
378                         if (index - tot < tot_nu) {
379                                 copy_v3_v3(r_co, nu->bezt[index - tot].vec[1]);
380                                 return true;
381                         }
382                 }
383                 else {
384                         tot_nu = nu->pntsu * nu->pntsv;
385                         if (index - tot < tot_nu) {
386                                 copy_v3_v3(r_co, nu->bp[index - tot].vec);
387                                 return true;
388                         }
389                 }
390                 tot += tot_nu;
391         }
392
393         return false;
394 }
395
396 int BKE_nurbList_verts_count(ListBase *nurb)
397 {
398         Nurb *nu;
399         int tot = 0;
400
401         nu = nurb->first;
402         while (nu) {
403                 if (nu->bezt)
404                         tot += 3 * nu->pntsu;
405                 else if (nu->bp)
406                         tot += nu->pntsu * nu->pntsv;
407
408                 nu = nu->next;
409         }
410         return tot;
411 }
412
413 int BKE_nurbList_verts_count_without_handles(ListBase *nurb)
414 {
415         Nurb *nu;
416         int tot = 0;
417
418         nu = nurb->first;
419         while (nu) {
420                 if (nu->bezt)
421                         tot += nu->pntsu;
422                 else if (nu->bp)
423                         tot += nu->pntsu * nu->pntsv;
424
425                 nu = nu->next;
426         }
427         return tot;
428 }
429
430 /* **************** NURBS ROUTINES ******************** */
431
432 void BKE_nurb_free(Nurb *nu)
433 {
434
435         if (nu == NULL) return;
436
437         if (nu->bezt)
438                 MEM_freeN(nu->bezt);
439         nu->bezt = NULL;
440         if (nu->bp)
441                 MEM_freeN(nu->bp);
442         nu->bp = NULL;
443         if (nu->knotsu)
444                 MEM_freeN(nu->knotsu);
445         nu->knotsu = NULL;
446         if (nu->knotsv)
447                 MEM_freeN(nu->knotsv);
448         nu->knotsv = NULL;
449         /* if (nu->trim.first) freeNurblist(&(nu->trim)); */
450
451         MEM_freeN(nu);
452
453 }
454
455
456 void BKE_nurbList_free(ListBase *lb)
457 {
458         Nurb *nu, *next;
459
460         if (lb == NULL) return;
461
462         nu = lb->first;
463         while (nu) {
464                 next = nu->next;
465                 BKE_nurb_free(nu);
466                 nu = next;
467         }
468         BLI_listbase_clear(lb);
469 }
470
471 Nurb *BKE_nurb_duplicate(const Nurb *nu)
472 {
473         Nurb *newnu;
474         int len;
475
476         newnu = (Nurb *)MEM_mallocN(sizeof(Nurb), "duplicateNurb");
477         if (newnu == NULL) return NULL;
478         memcpy(newnu, nu, sizeof(Nurb));
479
480         if (nu->bezt) {
481                 newnu->bezt =
482                     (BezTriple *)MEM_malloc_arrayN(nu->pntsu, sizeof(BezTriple), "duplicateNurb2");
483                 memcpy(newnu->bezt, nu->bezt, nu->pntsu * sizeof(BezTriple));
484         }
485         else {
486                 len = nu->pntsu * nu->pntsv;
487                 newnu->bp =
488                     (BPoint *)MEM_malloc_arrayN(len, sizeof(BPoint), "duplicateNurb3");
489                 memcpy(newnu->bp, nu->bp, len * sizeof(BPoint));
490
491                 newnu->knotsu = newnu->knotsv = NULL;
492
493                 if (nu->knotsu) {
494                         len = KNOTSU(nu);
495                         if (len) {
496                                 newnu->knotsu = MEM_malloc_arrayN(len, sizeof(float), "duplicateNurb4");
497                                 memcpy(newnu->knotsu, nu->knotsu, sizeof(float) * len);
498                         }
499                 }
500                 if (nu->pntsv > 1 && nu->knotsv) {
501                         len = KNOTSV(nu);
502                         if (len) {
503                                 newnu->knotsv = MEM_malloc_arrayN(len, sizeof(float), "duplicateNurb5");
504                                 memcpy(newnu->knotsv, nu->knotsv, sizeof(float) * len);
505                         }
506                 }
507         }
508         return newnu;
509 }
510
511 /* copy the nurb but allow for different number of points (to be copied after this) */
512 Nurb *BKE_nurb_copy(Nurb *src, int pntsu, int pntsv)
513 {
514         Nurb *newnu = (Nurb *)MEM_mallocN(sizeof(Nurb), "copyNurb");
515         memcpy(newnu, src, sizeof(Nurb));
516
517         if (pntsu == 1) SWAP(int, pntsu, pntsv);
518         newnu->pntsu = pntsu;
519         newnu->pntsv = pntsv;
520
521         /* caller can manually handle these arrays */
522         newnu->knotsu = NULL;
523         newnu->knotsv = NULL;
524
525         if (src->bezt) {
526                 newnu->bezt = (BezTriple *)MEM_malloc_arrayN(pntsu * pntsv, sizeof(BezTriple), "copyNurb2");
527         }
528         else {
529                 newnu->bp = (BPoint *)MEM_malloc_arrayN(pntsu * pntsv, sizeof(BPoint), "copyNurb3");
530         }
531
532         return newnu;
533 }
534
535 void BKE_nurbList_duplicate(ListBase *lb1, const ListBase *lb2)
536 {
537         Nurb *nu, *nun;
538
539         BKE_nurbList_free(lb1);
540
541         nu = lb2->first;
542         while (nu) {
543                 nun = BKE_nurb_duplicate(nu);
544                 BLI_addtail(lb1, nun);
545
546                 nu = nu->next;
547         }
548 }
549
550 void BKE_nurb_test2D(Nurb *nu)
551 {
552         BezTriple *bezt;
553         BPoint *bp;
554         int a;
555
556         if ((nu->flag & CU_2D) == 0)
557                 return;
558
559         if (nu->type == CU_BEZIER) {
560                 a = nu->pntsu;
561                 bezt = nu->bezt;
562                 while (a--) {
563                         bezt->vec[0][2] = 0.0;
564                         bezt->vec[1][2] = 0.0;
565                         bezt->vec[2][2] = 0.0;
566                         bezt++;
567                 }
568         }
569         else {
570                 a = nu->pntsu * nu->pntsv;
571                 bp = nu->bp;
572                 while (a--) {
573                         bp->vec[2] = 0.0;
574                         bp++;
575                 }
576         }
577 }
578
579 /**
580  * if use_radius is truth, minmax will take points' radius into account,
581  * which will make boundbox closer to beveled curve.
582  */
583 void BKE_nurb_minmax(Nurb *nu, bool use_radius, float min[3], float max[3])
584 {
585         BezTriple *bezt;
586         BPoint *bp;
587         int a;
588         float point[3];
589
590         if (nu->type == CU_BEZIER) {
591                 a = nu->pntsu;
592                 bezt = nu->bezt;
593                 while (a--) {
594                         if (use_radius) {
595                                 float radius_vector[3];
596                                 radius_vector[0] = radius_vector[1] = radius_vector[2] = bezt->radius;
597
598                                 add_v3_v3v3(point, bezt->vec[1], radius_vector);
599                                 minmax_v3v3_v3(min, max, point);
600
601                                 sub_v3_v3v3(point, bezt->vec[1], radius_vector);
602                                 minmax_v3v3_v3(min, max, point);
603                         }
604                         else {
605                                 minmax_v3v3_v3(min, max, bezt->vec[1]);
606                         }
607                         minmax_v3v3_v3(min, max, bezt->vec[0]);
608                         minmax_v3v3_v3(min, max, bezt->vec[2]);
609                         bezt++;
610                 }
611         }
612         else {
613                 a = nu->pntsu * nu->pntsv;
614                 bp = nu->bp;
615                 while (a--) {
616                         if (nu->pntsv == 1 && use_radius) {
617                                 float radius_vector[3];
618                                 radius_vector[0] = radius_vector[1] = radius_vector[2] = bp->radius;
619
620                                 add_v3_v3v3(point, bp->vec, radius_vector);
621                                 minmax_v3v3_v3(min, max, point);
622
623                                 sub_v3_v3v3(point, bp->vec, radius_vector);
624                                 minmax_v3v3_v3(min, max, point);
625                         }
626                         else {
627                                 /* Surfaces doesn't use bevel, so no need to take radius into account. */
628                                 minmax_v3v3_v3(min, max, bp->vec);
629                         }
630                         bp++;
631                 }
632         }
633 }
634
635 /* be sure to call makeknots after this */
636 void BKE_nurb_points_add(Nurb *nu, int number)
637 {
638         BPoint *bp;
639         int i;
640
641         nu->bp = MEM_recallocN(nu->bp, (nu->pntsu + number) * sizeof(BPoint));
642
643         for (i = 0, bp = &nu->bp[nu->pntsu]; i < number; i++, bp++) {
644                 bp->radius = 1.0f;
645         }
646
647         nu->pntsu += number;
648 }
649
650 void BKE_nurb_bezierPoints_add(Nurb *nu, int number)
651 {
652         BezTriple *bezt;
653         int i;
654
655         nu->bezt = MEM_recallocN(nu->bezt, (nu->pntsu + number) * sizeof(BezTriple));
656
657         for (i = 0, bezt = &nu->bezt[nu->pntsu]; i < number; i++, bezt++) {
658                 bezt->radius = 1.0f;
659         }
660
661         nu->pntsu += number;
662 }
663
664
665 int BKE_nurb_index_from_uv(
666         Nurb *nu,
667         int u, int v)
668 {
669         const int totu = nu->pntsu;
670         const int totv = nu->pntsv;
671
672         if (nu->flagu & CU_NURB_CYCLIC) {
673                 u = mod_i(u, totu);
674         }
675         else if (u < 0 || u >= totu) {
676                 return -1;
677         }
678
679         if (nu->flagv & CU_NURB_CYCLIC) {
680                 v = mod_i(v, totv);
681         }
682         else if (v < 0 || v >= totv) {
683                 return -1;
684         }
685
686         return (v * totu) + u;
687 }
688
689 void BKE_nurb_index_to_uv(
690         Nurb *nu, int index,
691         int *r_u, int *r_v)
692 {
693         const int totu = nu->pntsu;
694         const int totv = nu->pntsv;
695         BLI_assert(index >= 0 && index < (nu->pntsu * nu->pntsv));
696         *r_u = (index % totu);
697         *r_v = (index / totu) % totv;
698 }
699
700 BezTriple *BKE_nurb_bezt_get_next(Nurb *nu, BezTriple *bezt)
701 {
702         BezTriple *bezt_next;
703
704         BLI_assert(ARRAY_HAS_ITEM(bezt, nu->bezt, nu->pntsu));
705
706         if (bezt == &nu->bezt[nu->pntsu - 1]) {
707                 if (nu->flagu & CU_NURB_CYCLIC) {
708                         bezt_next = nu->bezt;
709                 }
710                 else {
711                         bezt_next = NULL;
712                 }
713         }
714         else {
715                 bezt_next = bezt + 1;
716         }
717
718         return bezt_next;
719 }
720
721 BPoint *BKE_nurb_bpoint_get_next(Nurb *nu, BPoint *bp)
722 {
723         BPoint *bp_next;
724
725         BLI_assert(ARRAY_HAS_ITEM(bp, nu->bp, nu->pntsu));
726
727         if (bp == &nu->bp[nu->pntsu - 1]) {
728                 if (nu->flagu & CU_NURB_CYCLIC) {
729                         bp_next = nu->bp;
730                 }
731                 else {
732                         bp_next = NULL;
733                 }
734         }
735         else {
736                 bp_next = bp + 1;
737         }
738
739         return bp_next;
740 }
741
742 BezTriple *BKE_nurb_bezt_get_prev(Nurb *nu, BezTriple *bezt)
743 {
744         BezTriple *bezt_prev;
745
746         BLI_assert(ARRAY_HAS_ITEM(bezt, nu->bezt, nu->pntsu));
747         BLI_assert(nu->pntsv <= 1);
748
749         if (bezt == nu->bezt) {
750                 if (nu->flagu & CU_NURB_CYCLIC) {
751                         bezt_prev = &nu->bezt[nu->pntsu - 1];
752                 }
753                 else {
754                         bezt_prev = NULL;
755                 }
756         }
757         else {
758                 bezt_prev = bezt - 1;
759         }
760
761         return bezt_prev;
762 }
763
764 BPoint *BKE_nurb_bpoint_get_prev(Nurb *nu, BPoint *bp)
765 {
766         BPoint *bp_prev;
767
768         BLI_assert(ARRAY_HAS_ITEM(bp, nu->bp, nu->pntsu));
769         BLI_assert(nu->pntsv == 1);
770
771         if (bp == nu->bp) {
772                 if (nu->flagu & CU_NURB_CYCLIC) {
773                         bp_prev = &nu->bp[nu->pntsu - 1];
774                 }
775                 else {
776                         bp_prev = NULL;
777                 }
778         }
779         else {
780                 bp_prev = bp - 1;
781         }
782
783         return bp_prev;
784 }
785
786 void BKE_nurb_bezt_calc_normal(struct Nurb *UNUSED(nu), BezTriple *bezt, float r_normal[3])
787 {
788         /* calculate the axis matrix from the spline */
789         float dir_prev[3], dir_next[3];
790
791         sub_v3_v3v3(dir_prev, bezt->vec[0], bezt->vec[1]);
792         sub_v3_v3v3(dir_next, bezt->vec[1], bezt->vec[2]);
793
794         normalize_v3(dir_prev);
795         normalize_v3(dir_next);
796
797         add_v3_v3v3(r_normal, dir_prev, dir_next);
798         normalize_v3(r_normal);
799 }
800
801 void BKE_nurb_bezt_calc_plane(struct Nurb *nu, BezTriple *bezt, float r_plane[3])
802 {
803         float dir_prev[3], dir_next[3];
804
805         sub_v3_v3v3(dir_prev, bezt->vec[0], bezt->vec[1]);
806         sub_v3_v3v3(dir_next, bezt->vec[1], bezt->vec[2]);
807
808         normalize_v3(dir_prev);
809         normalize_v3(dir_next);
810
811         cross_v3_v3v3(r_plane, dir_prev, dir_next);
812         if (normalize_v3(r_plane) < FLT_EPSILON) {
813                 BezTriple *bezt_prev = BKE_nurb_bezt_get_prev(nu, bezt);
814                 BezTriple *bezt_next = BKE_nurb_bezt_get_next(nu, bezt);
815
816                 if (bezt_prev) {
817                         sub_v3_v3v3(dir_prev, bezt_prev->vec[1], bezt->vec[1]);
818                         normalize_v3(dir_prev);
819                 }
820                 if (bezt_next) {
821                         sub_v3_v3v3(dir_next, bezt->vec[1], bezt_next->vec[1]);
822                         normalize_v3(dir_next);
823                 }
824                 cross_v3_v3v3(r_plane, dir_prev, dir_next);
825         }
826
827         /* matches with bones more closely */
828         {
829                 float dir_mid[3], tvec[3];
830                 add_v3_v3v3(dir_mid, dir_prev, dir_next);
831                 cross_v3_v3v3(tvec, r_plane, dir_mid);
832                 copy_v3_v3(r_plane, tvec);
833         }
834
835         normalize_v3(r_plane);
836 }
837
838 void BKE_nurb_bpoint_calc_normal(struct Nurb *nu, BPoint *bp, float r_normal[3])
839 {
840         BPoint *bp_prev = BKE_nurb_bpoint_get_prev(nu, bp);
841         BPoint *bp_next = BKE_nurb_bpoint_get_next(nu, bp);
842
843         zero_v3(r_normal);
844
845         if (bp_prev) {
846                 float dir_prev[3];
847                 sub_v3_v3v3(dir_prev, bp_prev->vec, bp->vec);
848                 normalize_v3(dir_prev);
849                 add_v3_v3(r_normal, dir_prev);
850         }
851         if (bp_next) {
852                 float dir_next[3];
853                 sub_v3_v3v3(dir_next, bp->vec, bp_next->vec);
854                 normalize_v3(dir_next);
855                 add_v3_v3(r_normal, dir_next);
856         }
857
858         normalize_v3(r_normal);
859 }
860
861 void BKE_nurb_bpoint_calc_plane(struct Nurb *nu, BPoint *bp, float r_plane[3])
862 {
863         BPoint *bp_prev = BKE_nurb_bpoint_get_prev(nu, bp);
864         BPoint *bp_next = BKE_nurb_bpoint_get_next(nu, bp);
865
866         float dir_prev[3] = {0.0f}, dir_next[3] = {0.0f};
867
868         if (bp_prev) {
869                 sub_v3_v3v3(dir_prev, bp_prev->vec, bp->vec);
870                 normalize_v3(dir_prev);
871         }
872         if (bp_next) {
873                 sub_v3_v3v3(dir_next, bp->vec, bp_next->vec);
874                 normalize_v3(dir_next);
875         }
876         cross_v3_v3v3(r_plane, dir_prev, dir_next);
877
878         /* matches with bones more closely */
879         {
880                 float dir_mid[3], tvec[3];
881                 add_v3_v3v3(dir_mid, dir_prev, dir_next);
882                 cross_v3_v3v3(tvec, r_plane, dir_mid);
883                 copy_v3_v3(r_plane, tvec);
884         }
885
886         normalize_v3(r_plane);
887 }
888
889 /* ~~~~~~~~~~~~~~~~~~~~Non Uniform Rational B Spline calculations ~~~~~~~~~~~ */
890
891
892 static void calcknots(float *knots, const int pnts, const short order, const short flag)
893 {
894         /* knots: number of pnts NOT corrected for cyclic */
895         const int pnts_order = pnts + order;
896         float k;
897         int a;
898
899         switch (flag & (CU_NURB_ENDPOINT | CU_NURB_BEZIER)) {
900                 case CU_NURB_ENDPOINT:
901                         k = 0.0;
902                         for (a = 1; a <= pnts_order; a++) {
903                                 knots[a - 1] = k;
904                                 if (a >= order && a <= pnts)
905                                         k += 1.0f;
906                         }
907                         break;
908                 case CU_NURB_BEZIER:
909                         /* Warning, the order MUST be 2 or 4,
910                          * if this is not enforced, the displist will be corrupt */
911                         if (order == 4) {
912                                 k = 0.34;
913                                 for (a = 0; a < pnts_order; a++) {
914                                         knots[a] = floorf(k);
915                                         k += (1.0f / 3.0f);
916                                 }
917                         }
918                         else if (order == 3) {
919                                 k = 0.6f;
920                                 for (a = 0; a < pnts_order; a++) {
921                                         if (a >= order && a <= pnts)
922                                                 k += 0.5f;
923                                         knots[a] = floorf(k);
924                                 }
925                         }
926                         else {
927                                 printf("bez nurb curve order is not 3 or 4, should never happen\n");
928                         }
929                         break;
930                 default:
931                         for (a = 0; a < pnts_order; a++) {
932                                 knots[a] = (float)a;
933                         }
934                         break;
935         }
936 }
937
938 static void makecyclicknots(float *knots, int pnts, short order)
939 /* pnts, order: number of pnts NOT corrected for cyclic */
940 {
941         int a, b, order2, c;
942
943         if (knots == NULL)
944                 return;
945
946         order2 = order - 1;
947
948         /* do first long rows (order -1), remove identical knots at endpoints */
949         if (order > 2) {
950                 b = pnts + order2;
951                 for (a = 1; a < order2; a++) {
952                         if (knots[b] != knots[b - a])
953                                 break;
954                 }
955                 if (a == order2)
956                         knots[pnts + order - 2] += 1.0f;
957         }
958
959         b = order;
960         c = pnts + order + order2;
961         for (a = pnts + order2; a < c; a++) {
962                 knots[a] = knots[a - 1] + (knots[b] - knots[b - 1]);
963                 b--;
964         }
965 }
966
967
968
969 static void makeknots(Nurb *nu, short uv)
970 {
971         if (nu->type == CU_NURBS) {
972                 if (uv == 1) {
973                         if (nu->knotsu)
974                                 MEM_freeN(nu->knotsu);
975                         if (BKE_nurb_check_valid_u(nu)) {
976                                 nu->knotsu = MEM_calloc_arrayN(KNOTSU(nu) + 1, sizeof(float), "makeknots");
977                                 if (nu->flagu & CU_NURB_CYCLIC) {
978                                         calcknots(nu->knotsu, nu->pntsu, nu->orderu, 0);  /* cyclic should be uniform */
979                                         makecyclicknots(nu->knotsu, nu->pntsu, nu->orderu);
980                                 }
981                                 else {
982                                         calcknots(nu->knotsu, nu->pntsu, nu->orderu, nu->flagu);
983                                 }
984                         }
985                         else
986                                 nu->knotsu = NULL;
987                 }
988                 else if (uv == 2) {
989                         if (nu->knotsv)
990                                 MEM_freeN(nu->knotsv);
991                         if (BKE_nurb_check_valid_v(nu)) {
992                                 nu->knotsv = MEM_calloc_arrayN(KNOTSV(nu) + 1, sizeof(float), "makeknots");
993                                 if (nu->flagv & CU_NURB_CYCLIC) {
994                                         calcknots(nu->knotsv, nu->pntsv, nu->orderv, 0);  /* cyclic should be uniform */
995                                         makecyclicknots(nu->knotsv, nu->pntsv, nu->orderv);
996                                 }
997                                 else {
998                                         calcknots(nu->knotsv, nu->pntsv, nu->orderv, nu->flagv);
999                                 }
1000                         }
1001                         else {
1002                                 nu->knotsv = NULL;
1003                         }
1004                 }
1005         }
1006 }
1007
1008 void BKE_nurb_knot_calc_u(Nurb *nu)
1009 {
1010         makeknots(nu, 1);
1011 }
1012
1013 void BKE_nurb_knot_calc_v(Nurb *nu)
1014 {
1015         makeknots(nu, 2);
1016 }
1017
1018 static void basisNurb(float t, short order, int pnts, float *knots, float *basis, int *start, int *end)
1019 {
1020         float d, e;
1021         int i, i1 = 0, i2 = 0, j, orderpluspnts, opp2, o2;
1022
1023         orderpluspnts = order + pnts;
1024         opp2 = orderpluspnts - 1;
1025
1026         /* this is for float inaccuracy */
1027         if (t < knots[0])
1028                 t = knots[0];
1029         else if (t > knots[opp2]) 
1030                 t = knots[opp2];
1031
1032         /* this part is order '1' */
1033         o2 = order + 1;
1034         for (i = 0; i < opp2; i++) {
1035                 if (knots[i] != knots[i + 1] && t >= knots[i] && t <= knots[i + 1]) {
1036                         basis[i] = 1.0;
1037                         i1 = i - o2;
1038                         if (i1 < 0) i1 = 0;
1039                         i2 = i;
1040                         i++;
1041                         while (i < opp2) {
1042                                 basis[i] = 0.0;
1043                                 i++;
1044                         }
1045                         break;
1046                 }
1047                 else
1048                         basis[i] = 0.0;
1049         }
1050         basis[i] = 0.0;
1051
1052         /* this is order 2, 3, ... */
1053         for (j = 2; j <= order; j++) {
1054
1055                 if (i2 + j >= orderpluspnts) i2 = opp2 - j;
1056
1057                 for (i = i1; i <= i2; i++) {
1058                         if (basis[i] != 0.0f)
1059                                 d = ((t - knots[i]) * basis[i]) / (knots[i + j - 1] - knots[i]);
1060                         else
1061                                 d = 0.0f;
1062
1063                         if (basis[i + 1] != 0.0f)
1064                                 e = ((knots[i + j] - t) * basis[i + 1]) / (knots[i + j] - knots[i + 1]);
1065                         else
1066                                 e = 0.0;
1067
1068                         basis[i] = d + e;
1069                 }
1070         }
1071
1072         *start = 1000;
1073         *end = 0;
1074
1075         for (i = i1; i <= i2; i++) {
1076                 if (basis[i] > 0.0f) {
1077                         *end = i;
1078                         if (*start == 1000) *start = i;
1079                 }
1080         }
1081 }
1082
1083
1084 void BKE_nurb_makeFaces(Nurb *nu, float *coord_array, int rowstride, int resolu, int resolv)
1085 /* coord_array  has to be (3 * 4 * resolu * resolv) in size, and zero-ed */
1086 {
1087         BPoint *bp;
1088         float *basisu, *basis, *basisv, *sum, *fp, *in;
1089         float u, v, ustart, uend, ustep, vstart, vend, vstep, sumdiv;
1090         int i, j, iofs, jofs, cycl, len, curu, curv;
1091         int istart, iend, jsta, jen, *jstart, *jend, ratcomp;
1092
1093         int totu = nu->pntsu * resolu, totv = nu->pntsv * resolv;
1094
1095         if (nu->knotsu == NULL || nu->knotsv == NULL)
1096                 return;
1097         if (nu->orderu > nu->pntsu)
1098                 return;
1099         if (nu->orderv > nu->pntsv)
1100                 return;
1101         if (coord_array == NULL)
1102                 return;
1103
1104         /* allocate and initialize */
1105         len = totu * totv;
1106         if (len == 0)
1107                 return;
1108
1109         sum = (float *)MEM_calloc_arrayN(len, sizeof(float), "makeNurbfaces1");
1110
1111         bp = nu->bp;
1112         i = nu->pntsu * nu->pntsv;
1113         ratcomp = 0;
1114         while (i--) {
1115                 if (bp->vec[3] != 1.0f) {
1116                         ratcomp = 1;
1117                         break;
1118                 }
1119                 bp++;
1120         }
1121
1122         fp = nu->knotsu;
1123         ustart = fp[nu->orderu - 1];
1124         if (nu->flagu & CU_NURB_CYCLIC)
1125                 uend = fp[nu->pntsu + nu->orderu - 1];
1126         else
1127                 uend = fp[nu->pntsu];
1128         ustep = (uend - ustart) / ((nu->flagu & CU_NURB_CYCLIC) ? totu : totu - 1);
1129
1130         basisu = (float *)MEM_malloc_arrayN(KNOTSU(nu), sizeof(float), "makeNurbfaces3");
1131
1132         fp = nu->knotsv;
1133         vstart = fp[nu->orderv - 1];
1134
1135         if (nu->flagv & CU_NURB_CYCLIC)
1136                 vend = fp[nu->pntsv + nu->orderv - 1];
1137         else
1138                 vend = fp[nu->pntsv];
1139         vstep = (vend - vstart) / ((nu->flagv & CU_NURB_CYCLIC) ? totv : totv - 1);
1140
1141         len = KNOTSV(nu);
1142         basisv = (float *)MEM_malloc_arrayN(len * totv, sizeof(float), "makeNurbfaces3");
1143         jstart = (int *)MEM_malloc_arrayN(totv, sizeof(float), "makeNurbfaces4");
1144         jend = (int *)MEM_malloc_arrayN(totv, sizeof(float), "makeNurbfaces5");
1145
1146         /* precalculation of basisv and jstart, jend */
1147         if (nu->flagv & CU_NURB_CYCLIC)
1148                 cycl = nu->orderv - 1;
1149         else cycl = 0;
1150         v = vstart;
1151         basis = basisv;
1152         curv = totv;
1153         while (curv--) {
1154                 basisNurb(v, nu->orderv, nu->pntsv + cycl, nu->knotsv, basis, jstart + curv, jend + curv);
1155                 basis += KNOTSV(nu);
1156                 v += vstep;
1157         }
1158
1159         if (nu->flagu & CU_NURB_CYCLIC)
1160                 cycl = nu->orderu - 1;
1161         else
1162                 cycl = 0;
1163         in = coord_array;
1164         u = ustart;
1165         curu = totu;
1166         while (curu--) {
1167                 basisNurb(u, nu->orderu, nu->pntsu + cycl, nu->knotsu, basisu, &istart, &iend);
1168
1169                 basis = basisv;
1170                 curv = totv;
1171                 while (curv--) {
1172                         jsta = jstart[curv];
1173                         jen = jend[curv];
1174
1175                         /* calculate sum */
1176                         sumdiv = 0.0;
1177                         fp = sum;
1178
1179                         for (j = jsta; j <= jen; j++) {
1180
1181                                 if (j >= nu->pntsv)
1182                                         jofs = (j - nu->pntsv);
1183                                 else
1184                                         jofs = j;
1185                                 bp = nu->bp + nu->pntsu * jofs + istart - 1;
1186
1187                                 for (i = istart; i <= iend; i++, fp++) {
1188                                         if (i >= nu->pntsu) {
1189                                                 iofs = i - nu->pntsu;
1190                                                 bp = nu->bp + nu->pntsu * jofs + iofs;
1191                                         }
1192                                         else
1193                                                 bp++;
1194
1195                                         if (ratcomp) {
1196                                                 *fp = basisu[i] * basis[j] * bp->vec[3];
1197                                                 sumdiv += *fp;
1198                                         }
1199                                         else
1200                                                 *fp = basisu[i] * basis[j];
1201                                 }
1202                         }
1203
1204                         if (ratcomp) {
1205                                 fp = sum;
1206                                 for (j = jsta; j <= jen; j++) {
1207                                         for (i = istart; i <= iend; i++, fp++) {
1208                                                 *fp /= sumdiv;
1209                                         }
1210                                 }
1211                         }
1212
1213                         zero_v3(in);
1214
1215                         /* one! (1.0) real point now */
1216                         fp = sum;
1217                         for (j = jsta; j <= jen; j++) {
1218
1219                                 if (j >= nu->pntsv)
1220                                         jofs = (j - nu->pntsv);
1221                                 else
1222                                         jofs = j;
1223                                 bp = nu->bp + nu->pntsu * jofs + istart - 1;
1224
1225                                 for (i = istart; i <= iend; i++, fp++) {
1226                                         if (i >= nu->pntsu) {
1227                                                 iofs = i - nu->pntsu;
1228                                                 bp = nu->bp + nu->pntsu * jofs + iofs;
1229                                         }
1230                                         else
1231                                                 bp++;
1232
1233                                         if (*fp != 0.0f) {
1234                                                 madd_v3_v3fl(in, bp->vec, *fp);
1235                                         }
1236                                 }
1237                         }
1238
1239                         in += 3;
1240                         basis += KNOTSV(nu);
1241                 }
1242                 u += ustep;
1243                 if (rowstride != 0) {
1244                         in = (float *)(((unsigned char *)in) + (rowstride - 3 * totv * sizeof(*in)));
1245                 }
1246         }
1247
1248         /* free */
1249         MEM_freeN(sum);
1250         MEM_freeN(basisu);
1251         MEM_freeN(basisv);
1252         MEM_freeN(jstart);
1253         MEM_freeN(jend);
1254 }
1255
1256 /**
1257  * \param coord_array Has to be 3 * 4 * pntsu * resolu in size and zero-ed
1258  * \param tilt_array   set when non-NULL
1259  * \param radius_array set when non-NULL
1260  */
1261 void BKE_nurb_makeCurve(Nurb *nu, float *coord_array, float *tilt_array, float *radius_array, float *weight_array,
1262                         int resolu, int stride)
1263 {
1264         const float eps = 1e-6f;
1265         BPoint *bp;
1266         float u, ustart, uend, ustep, sumdiv;
1267         float *basisu, *sum, *fp;
1268         float *coord_fp = coord_array, *tilt_fp = tilt_array, *radius_fp = radius_array, *weight_fp = weight_array;
1269         int i, len, istart, iend, cycl;
1270
1271         if (nu->knotsu == NULL)
1272                 return;
1273         if (nu->orderu > nu->pntsu)
1274                 return;
1275         if (coord_array == NULL)
1276                 return;
1277
1278         /* allocate and initialize */
1279         len = nu->pntsu;
1280         if (len == 0)
1281                 return;
1282         sum = (float *)MEM_calloc_arrayN(len, sizeof(float), "makeNurbcurve1");
1283
1284         resolu = (resolu * SEGMENTSU(nu));
1285
1286         if (resolu == 0) {
1287                 MEM_freeN(sum);
1288                 return;
1289         }
1290
1291         fp = nu->knotsu;
1292         ustart = fp[nu->orderu - 1];
1293         if (nu->flagu & CU_NURB_CYCLIC)
1294                 uend = fp[nu->pntsu + nu->orderu - 1];
1295         else
1296                 uend = fp[nu->pntsu];
1297         ustep = (uend - ustart) / (resolu - ((nu->flagu & CU_NURB_CYCLIC) ? 0 : 1));
1298
1299         basisu = (float *)MEM_malloc_arrayN(KNOTSU(nu), sizeof(float), "makeNurbcurve3");
1300
1301         if (nu->flagu & CU_NURB_CYCLIC)
1302                 cycl = nu->orderu - 1;
1303         else
1304                 cycl = 0;
1305
1306         u = ustart;
1307         while (resolu--) {
1308                 basisNurb(u, nu->orderu, nu->pntsu + cycl, nu->knotsu, basisu, &istart, &iend);
1309
1310                 /* calc sum */
1311                 sumdiv = 0.0;
1312                 fp = sum;
1313                 bp = nu->bp + istart - 1;
1314                 for (i = istart; i <= iend; i++, fp++) {
1315                         if (i >= nu->pntsu)
1316                                 bp = nu->bp + (i - nu->pntsu);
1317                         else
1318                                 bp++;
1319
1320                         *fp = basisu[i] * bp->vec[3];
1321                         sumdiv += *fp;
1322                 }
1323                 if ((sumdiv != 0.0f) && (sumdiv < 1.0f - eps || sumdiv > 1.0f + eps)) {
1324                         /* is normalizing needed? */
1325                         fp = sum;
1326                         for (i = istart; i <= iend; i++, fp++) {
1327                                 *fp /= sumdiv;
1328                         }
1329                 }
1330
1331                 zero_v3(coord_fp);
1332
1333                 /* one! (1.0) real point */
1334                 fp = sum;
1335                 bp = nu->bp + istart - 1;
1336                 for (i = istart; i <= iend; i++, fp++) {
1337                         if (i >= nu->pntsu)
1338                                 bp = nu->bp + (i - nu->pntsu);
1339                         else
1340                                 bp++;
1341
1342                         if (*fp != 0.0f) {
1343                                 madd_v3_v3fl(coord_fp, bp->vec, *fp);
1344
1345                                 if (tilt_fp)
1346                                         (*tilt_fp) += (*fp) * bp->alfa;
1347
1348                                 if (radius_fp)
1349                                         (*radius_fp) += (*fp) * bp->radius;
1350
1351                                 if (weight_fp)
1352                                         (*weight_fp) += (*fp) * bp->weight;
1353                         }
1354                 }
1355
1356                 coord_fp = POINTER_OFFSET(coord_fp, stride);
1357
1358                 if (tilt_fp)
1359                         tilt_fp = POINTER_OFFSET(tilt_fp, stride);
1360                 if (radius_fp)
1361                         radius_fp = POINTER_OFFSET(radius_fp, stride);
1362                 if (weight_fp)
1363                         weight_fp = POINTER_OFFSET(weight_fp, stride);
1364
1365                 u += ustep;
1366         }
1367
1368         /* free */
1369         MEM_freeN(sum);
1370         MEM_freeN(basisu);
1371 }
1372
1373 /**
1374  * Calculate the length for arrays filled in by #BKE_curve_calc_coords_axis.
1375  */
1376 unsigned int BKE_curve_calc_coords_axis_len(
1377         const unsigned int bezt_array_len, const unsigned int resolu,
1378         const bool is_cyclic, const bool use_cyclic_duplicate_endpoint)
1379 {
1380         const unsigned int segments = bezt_array_len - (is_cyclic ?  0 : 1);
1381         const unsigned int points_len = (segments * resolu) + (is_cyclic ? (use_cyclic_duplicate_endpoint) : 1);
1382         return points_len;
1383 }
1384
1385 /**
1386  * Calculate an array for the entire curve (cyclic or non-cyclic).
1387  * \note Call for each axis.
1388  *
1389  * \param use_cyclic_duplicate_endpoint: Duplicate values at the beginning & end of the array.
1390  */
1391 void BKE_curve_calc_coords_axis(
1392         const BezTriple *bezt_array, const unsigned int bezt_array_len, const unsigned int resolu,
1393         const bool is_cyclic, const bool use_cyclic_duplicate_endpoint,
1394         /* array params */
1395         const unsigned int axis, const unsigned int stride,
1396         float *r_points)
1397 {
1398         const unsigned int points_len = BKE_curve_calc_coords_axis_len(
1399                 bezt_array_len, resolu, is_cyclic, use_cyclic_duplicate_endpoint);
1400         float *r_points_offset = r_points;
1401
1402         const unsigned int resolu_stride = resolu * stride;
1403         const unsigned int bezt_array_last = bezt_array_len - 1;
1404
1405         for (unsigned int i = 0; i < bezt_array_last; i++) {
1406                 const BezTriple *bezt_curr = &bezt_array[i];
1407                 const BezTriple *bezt_next = &bezt_array[i + 1];
1408                 BKE_curve_forward_diff_bezier(
1409                         bezt_curr->vec[1][axis], bezt_curr->vec[2][axis],
1410                         bezt_next->vec[0][axis], bezt_next->vec[1][axis],
1411                         r_points_offset, (int)resolu, stride);
1412                 r_points_offset = POINTER_OFFSET(r_points_offset, resolu_stride);
1413         }
1414
1415         if (is_cyclic) {
1416                 const BezTriple *bezt_curr = &bezt_array[bezt_array_last];
1417                 const BezTriple *bezt_next = &bezt_array[0];
1418                 BKE_curve_forward_diff_bezier(
1419                         bezt_curr->vec[1][axis], bezt_curr->vec[2][axis],
1420                         bezt_next->vec[0][axis], bezt_next->vec[1][axis],
1421                         r_points_offset, (int)resolu, stride);
1422                 r_points_offset = POINTER_OFFSET(r_points_offset, resolu_stride);
1423                 if (use_cyclic_duplicate_endpoint) {
1424                         *r_points_offset = *r_points;
1425                         r_points_offset = POINTER_OFFSET(r_points_offset, stride);
1426                 }
1427         }
1428         else {
1429                 float *r_points_last = POINTER_OFFSET(r_points, bezt_array_last * resolu_stride);
1430                 *r_points_last = bezt_array[bezt_array_last].vec[1][axis];
1431                 r_points_offset = POINTER_OFFSET(r_points_offset, stride);
1432         }
1433
1434         BLI_assert(POINTER_OFFSET(r_points, points_len * stride) == r_points_offset);
1435         UNUSED_VARS_NDEBUG(points_len);
1436 }
1437
1438 /* forward differencing method for bezier curve */
1439 void BKE_curve_forward_diff_bezier(float q0, float q1, float q2, float q3, float *p, int it, int stride)
1440 {
1441         float rt0, rt1, rt2, rt3, f;
1442         int a;
1443
1444         f = (float)it;
1445         rt0 = q0;
1446         rt1 = 3.0f * (q1 - q0) / f;
1447         f *= f;
1448         rt2 = 3.0f * (q0 - 2.0f * q1 + q2) / f;
1449         f *= it;
1450         rt3 = (q3 - q0 + 3.0f * (q1 - q2)) / f;
1451
1452         q0 = rt0;
1453         q1 = rt1 + rt2 + rt3;
1454         q2 = 2 * rt2 + 6 * rt3;
1455         q3 = 6 * rt3;
1456
1457         for (a = 0; a <= it; a++) {
1458                 *p = q0;
1459                 p = POINTER_OFFSET(p, stride);
1460                 q0 += q1;
1461                 q1 += q2;
1462                 q2 += q3;
1463         }
1464 }
1465
1466 /* forward differencing method for first derivative of cubic bezier curve */
1467 void BKE_curve_forward_diff_tangent_bezier(float q0, float q1, float q2, float q3, float *p, int it, int stride)
1468 {
1469         float rt0, rt1, rt2, f;
1470         int a;
1471
1472         f = 1.0f / (float)it;
1473
1474         rt0 = 3.0f * (q1 - q0);
1475         rt1 = f * (3.0f * (q3 - q0) + 9.0f * (q1 - q2));
1476         rt2 = 6.0f * (q0 + q2) - 12.0f * q1;
1477
1478         q0 = rt0;
1479         q1 = f * (rt1 + rt2);
1480         q2 = 2.0f * f * rt1;
1481
1482         for (a = 0; a <= it; a++) {
1483                 *p = q0;
1484                 p = POINTER_OFFSET(p, stride);
1485                 q0 += q1;
1486                 q1 += q2;
1487         }
1488 }
1489
1490 static void forward_diff_bezier_cotangent(const float p0[3], const float p1[3], const float p2[3], const float p3[3],
1491                                           float p[3], int it, int stride)
1492 {
1493         /* note that these are not perpendicular to the curve
1494          * they need to be rotated for this,
1495          *
1496          * This could also be optimized like BKE_curve_forward_diff_bezier */
1497         int a;
1498         for (a = 0; a <= it; a++) {
1499                 float t = (float)a / (float)it;
1500
1501                 int i;
1502                 for (i = 0; i < 3; i++) {
1503                         p[i] = (-6.0f  * t +  6.0f) * p0[i] +
1504                                ( 18.0f * t - 12.0f) * p1[i] +
1505                                (-18.0f * t +  6.0f) * p2[i] +
1506                                ( 6.0f  * t)         * p3[i];
1507                 }
1508                 normalize_v3(p);
1509                 p = POINTER_OFFSET(p, stride);
1510         }
1511 }
1512
1513 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
1514
1515 float *BKE_curve_surf_make_orco(Object *ob)
1516 {
1517         /* Note: this function is used in convertblender only atm, so
1518          * suppose nonzero curve's render resolution should always be used */
1519         Curve *cu = ob->data;
1520         Nurb *nu;
1521         int a, b, tot = 0;
1522         int sizeu, sizev;
1523         int resolu, resolv;
1524         float *fp, *coord_array;
1525
1526         /* first calculate the size of the datablock */
1527         nu = cu->nurb.first;
1528         while (nu) {
1529                 /* as we want to avoid the seam in a cyclic nurbs
1530                  * texture wrapping, reserve extra orco data space to save these extra needed
1531                  * vertex based UV coordinates for the meridian vertices.
1532                  * Vertices on the 0/2pi boundary are not duplicated inside the displist but later in
1533                  * the renderface/vert construction.
1534                  *
1535                  * See also convertblender.c: init_render_surf()
1536                  */
1537
1538                 resolu = cu->resolu_ren ? cu->resolu_ren : nu->resolu;
1539                 resolv = cu->resolv_ren ? cu->resolv_ren : nu->resolv;
1540
1541                 sizeu = nu->pntsu * resolu;
1542                 sizev = nu->pntsv * resolv;
1543                 if (nu->flagu & CU_NURB_CYCLIC) sizeu++;
1544                 if (nu->flagv & CU_NURB_CYCLIC) sizev++;
1545                 if (nu->pntsv > 1) tot += sizeu * sizev;
1546
1547                 nu = nu->next;
1548         }
1549         /* makeNurbfaces wants zeros */
1550         fp = coord_array = MEM_calloc_arrayN(tot, 3 * sizeof(float), "make_orco");
1551
1552         nu = cu->nurb.first;
1553         while (nu) {
1554                 resolu = cu->resolu_ren ? cu->resolu_ren : nu->resolu;
1555                 resolv = cu->resolv_ren ? cu->resolv_ren : nu->resolv;
1556
1557                 if (nu->pntsv > 1) {
1558                         sizeu = nu->pntsu * resolu;
1559                         sizev = nu->pntsv * resolv;
1560
1561                         if (nu->flagu & CU_NURB_CYCLIC)
1562                                 sizeu++;
1563                         if (nu->flagv & CU_NURB_CYCLIC)
1564                                 sizev++;
1565
1566                         if (cu->flag & CU_UV_ORCO) {
1567                                 for (b = 0; b < sizeu; b++) {
1568                                         for (a = 0; a < sizev; a++) {
1569
1570                                                 if (sizev < 2)
1571                                                         fp[0] = 0.0f;
1572                                                 else
1573                                                         fp[0] = -1.0f + 2.0f * ((float)a) / (sizev - 1);
1574
1575                                                 if (sizeu < 2)
1576                                                         fp[1] = 0.0f;
1577                                                 else
1578                                                         fp[1] = -1.0f + 2.0f * ((float)b) / (sizeu - 1);
1579
1580                                                 fp[2] = 0.0;
1581
1582                                                 fp += 3;
1583                                         }
1584                                 }
1585                         }
1586                         else {
1587                                 int size = (nu->pntsu * resolu) * (nu->pntsv * resolv) * 3 * sizeof(float);
1588                                 float *_tdata = MEM_mallocN(size, "temp data");
1589                                 float *tdata = _tdata;
1590
1591                                 BKE_nurb_makeFaces(nu, tdata, 0, resolu, resolv);
1592
1593                                 for (b = 0; b < sizeu; b++) {
1594                                         int use_b = b;
1595                                         if (b == sizeu - 1 && (nu->flagu & CU_NURB_CYCLIC))
1596                                                 use_b = false;
1597
1598                                         for (a = 0; a < sizev; a++) {
1599                                                 int use_a = a;
1600                                                 if (a == sizev - 1 && (nu->flagv & CU_NURB_CYCLIC))
1601                                                         use_a = false;
1602
1603                                                 tdata = _tdata + 3 * (use_b * (nu->pntsv * resolv) + use_a);
1604
1605                                                 fp[0] = (tdata[0] - cu->loc[0]) / cu->size[0];
1606                                                 fp[1] = (tdata[1] - cu->loc[1]) / cu->size[1];
1607                                                 fp[2] = (tdata[2] - cu->loc[2]) / cu->size[2];
1608                                                 fp += 3;
1609                                         }
1610                                 }
1611
1612                                 MEM_freeN(_tdata);
1613                         }
1614                 }
1615                 nu = nu->next;
1616         }
1617
1618         return coord_array;
1619 }
1620
1621
1622 /* NOTE: This routine is tied to the order of vertex
1623  * built by displist and as passed to the renderer.
1624  */
1625 float *BKE_curve_make_orco(Scene *scene, Object *ob, int *r_numVerts)
1626 {
1627         Curve *cu = ob->data;
1628         DispList *dl;
1629         int u, v, numVerts;
1630         float *fp, *coord_array;
1631         ListBase disp = {NULL, NULL};
1632
1633         BKE_displist_make_curveTypes_forOrco(scene, ob, &disp);
1634
1635         numVerts = 0;
1636         for (dl = disp.first; dl; dl = dl->next) {
1637                 if (dl->type == DL_INDEX3) {
1638                         numVerts += dl->nr;
1639                 }
1640                 else if (dl->type == DL_SURF) {
1641                         /* convertblender.c uses the Surface code for creating renderfaces when cyclic U only
1642                          * (closed circle beveling)
1643                          */
1644                         if (dl->flag & DL_CYCL_U) {
1645                                 if (dl->flag & DL_CYCL_V)
1646                                         numVerts += (dl->parts + 1) * (dl->nr + 1);
1647                                 else
1648                                         numVerts += dl->parts * (dl->nr + 1);
1649                         }
1650                         else if (dl->flag & DL_CYCL_V) {
1651                                 numVerts += (dl->parts + 1) * dl->nr;
1652                         }
1653                         else
1654                                 numVerts += dl->parts * dl->nr;
1655                 }
1656         }
1657
1658         if (r_numVerts)
1659                 *r_numVerts = numVerts;
1660
1661         fp = coord_array = MEM_malloc_arrayN(numVerts, 3 * sizeof(float), "cu_orco");
1662         for (dl = disp.first; dl; dl = dl->next) {
1663                 if (dl->type == DL_INDEX3) {
1664                         for (u = 0; u < dl->nr; u++, fp += 3) {
1665                                 if (cu->flag & CU_UV_ORCO) {
1666                                         fp[0] = 2.0f * u / (dl->nr - 1) - 1.0f;
1667                                         fp[1] = 0.0;
1668                                         fp[2] = 0.0;
1669                                 }
1670                                 else {
1671                                         copy_v3_v3(fp, &dl->verts[u * 3]);
1672
1673                                         fp[0] = (fp[0] - cu->loc[0]) / cu->size[0];
1674                                         fp[1] = (fp[1] - cu->loc[1]) / cu->size[1];
1675                                         fp[2] = (fp[2] - cu->loc[2]) / cu->size[2];
1676                                 }
1677                         }
1678                 }
1679                 else if (dl->type == DL_SURF) {
1680                         int sizeu = dl->nr, sizev = dl->parts;
1681
1682                         /* exception as handled in convertblender.c too */
1683                         if (dl->flag & DL_CYCL_U) {
1684                                 sizeu++;
1685                                 if (dl->flag & DL_CYCL_V)
1686                                         sizev++;
1687                         }
1688                         else if (dl->flag & DL_CYCL_V) {
1689                                 sizev++;
1690                         }
1691
1692                         for (u = 0; u < sizev; u++) {
1693                                 for (v = 0; v < sizeu; v++, fp += 3) {
1694                                         if (cu->flag & CU_UV_ORCO) {
1695                                                 fp[0] = 2.0f * u / (sizev - 1) - 1.0f;
1696                                                 fp[1] = 2.0f * v / (sizeu - 1) - 1.0f;
1697                                                 fp[2] = 0.0;
1698                                         }
1699                                         else {
1700                                                 const float *vert;
1701                                                 int realv = v % dl->nr;
1702                                                 int realu = u % dl->parts;
1703
1704                                                 vert = dl->verts + 3 * (dl->nr * realu + realv);
1705                                                 copy_v3_v3(fp, vert);
1706
1707                                                 fp[0] = (fp[0] - cu->loc[0]) / cu->size[0];
1708                                                 fp[1] = (fp[1] - cu->loc[1]) / cu->size[1];
1709                                                 fp[2] = (fp[2] - cu->loc[2]) / cu->size[2];
1710                                         }
1711                                 }
1712                         }
1713                 }
1714         }
1715
1716         BKE_displist_free(&disp);
1717
1718         return coord_array;
1719 }
1720
1721
1722 /* ***************** BEVEL ****************** */
1723
1724 void BKE_curve_bevel_make(Scene *scene, Object *ob, ListBase *disp,
1725                           const bool for_render, const bool use_render_resolution)
1726 {
1727         DispList *dl, *dlnew;
1728         Curve *bevcu, *cu;
1729         float *fp, facx, facy, angle, dangle;
1730         int nr, a;
1731
1732         cu = ob->data;
1733         BLI_listbase_clear(disp);
1734
1735         /* if a font object is being edited, then do nothing */
1736 // XXX  if ( ob == obedit && ob->type == OB_FONT ) return;
1737
1738         if (cu->bevobj) {
1739                 if (cu->bevobj->type != OB_CURVE)
1740                         return;
1741
1742                 bevcu = cu->bevobj->data;
1743                 if (bevcu->ext1 == 0.0f && bevcu->ext2 == 0.0f) {
1744                         ListBase bevdisp = {NULL, NULL};
1745                         facx = cu->bevobj->size[0];
1746                         facy = cu->bevobj->size[1];
1747
1748                         if (for_render) {
1749                                 BKE_displist_make_curveTypes_forRender(scene, cu->bevobj, &bevdisp, NULL, false, use_render_resolution);
1750                                 dl = bevdisp.first;
1751                         }
1752                         else if (cu->bevobj->curve_cache) {
1753                                 dl = cu->bevobj->curve_cache->disp.first;
1754                         }
1755                         else {
1756                                 BLI_assert(cu->bevobj->curve_cache != NULL);
1757                                 dl = NULL;
1758                         }
1759
1760                         while (dl) {
1761                                 if (ELEM(dl->type, DL_POLY, DL_SEGM)) {
1762                                         dlnew = MEM_mallocN(sizeof(DispList), "makebevelcurve1");
1763                                         *dlnew = *dl;
1764                                         dlnew->verts = MEM_malloc_arrayN(dl->parts * dl->nr, 3 * sizeof(float), "makebevelcurve1");
1765                                         memcpy(dlnew->verts, dl->verts, 3 * sizeof(float) * dl->parts * dl->nr);
1766
1767                                         if (dlnew->type == DL_SEGM)
1768                                                 dlnew->flag |= (DL_FRONT_CURVE | DL_BACK_CURVE);
1769
1770                                         BLI_addtail(disp, dlnew);
1771                                         fp = dlnew->verts;
1772                                         nr = dlnew->parts * dlnew->nr;
1773                                         while (nr--) {
1774                                                 fp[2] = fp[1] * facy;
1775                                                 fp[1] = -fp[0] * facx;
1776                                                 fp[0] = 0.0;
1777                                                 fp += 3;
1778                                         }
1779                                 }
1780                                 dl = dl->next;
1781                         }
1782
1783                         BKE_displist_free(&bevdisp);
1784                 }
1785         }
1786         else if (cu->ext1 == 0.0f && cu->ext2 == 0.0f) {
1787                 /* pass */
1788         }
1789         else if (cu->ext2 == 0.0f) {
1790                 dl = MEM_callocN(sizeof(DispList), "makebevelcurve2");
1791                 dl->verts = MEM_malloc_arrayN(2, sizeof(float[3]), "makebevelcurve2");
1792                 BLI_addtail(disp, dl);
1793                 dl->type = DL_SEGM;
1794                 dl->parts = 1;
1795                 dl->flag = DL_FRONT_CURVE | DL_BACK_CURVE;
1796                 dl->nr = 2;
1797
1798                 fp = dl->verts;
1799                 fp[0] = fp[1] = 0.0;
1800                 fp[2] = -cu->ext1;
1801                 fp[3] = fp[4] = 0.0;
1802                 fp[5] = cu->ext1;
1803         }
1804         else if ((cu->flag & (CU_FRONT | CU_BACK)) == 0 && cu->ext1 == 0.0f) {  /* we make a full round bevel in that case */
1805                 nr = 4 + 2 * cu->bevresol;
1806
1807                 dl = MEM_callocN(sizeof(DispList), "makebevelcurve p1");
1808                 dl->verts = MEM_malloc_arrayN(nr, sizeof(float[3]), "makebevelcurve p1");
1809                 BLI_addtail(disp, dl);
1810                 dl->type = DL_POLY;
1811                 dl->parts = 1;
1812                 dl->flag = DL_BACK_CURVE;
1813                 dl->nr = nr;
1814
1815                 /* a circle */
1816                 fp = dl->verts;
1817                 dangle = (2.0f * (float)M_PI / (nr));
1818                 angle = -(nr - 1) * dangle;
1819
1820                 for (a = 0; a < nr; a++) {
1821                         fp[0] = 0.0;
1822                         fp[1] = (cosf(angle) * (cu->ext2));
1823                         fp[2] = (sinf(angle) * (cu->ext2)) - cu->ext1;
1824                         angle += dangle;
1825                         fp += 3;
1826                 }
1827         }
1828         else {
1829                 short dnr;
1830
1831                 /* bevel now in three parts, for proper vertex normals */
1832                 /* part 1, back */
1833
1834                 if ((cu->flag & CU_BACK) || !(cu->flag & CU_FRONT)) {
1835                         dnr = nr = 2 + cu->bevresol;
1836                         if ((cu->flag & (CU_FRONT | CU_BACK)) == 0) {
1837                                 nr = 3 + 2 * cu->bevresol;
1838                         }
1839                         dl = MEM_callocN(sizeof(DispList), "makebevelcurve p1");
1840                         dl->verts = MEM_malloc_arrayN(nr, sizeof(float[3]), "makebevelcurve p1");
1841                         BLI_addtail(disp, dl);
1842                         dl->type = DL_SEGM;
1843                         dl->parts = 1;
1844                         dl->flag = DL_BACK_CURVE;
1845                         dl->nr = nr;
1846
1847                         /* half a circle */
1848                         fp = dl->verts;
1849                         dangle = ((float)M_PI_2 / (dnr - 1));
1850                         angle = -(nr - 1) * dangle;
1851
1852                         for (a = 0; a < nr; a++) {
1853                                 fp[0] = 0.0;
1854                                 fp[1] = (float)(cosf(angle) * (cu->ext2));
1855                                 fp[2] = (float)(sinf(angle) * (cu->ext2)) - cu->ext1;
1856                                 angle += dangle;
1857                                 fp += 3;
1858                         }
1859                 }
1860
1861                 /* part 2, sidefaces */
1862                 if (cu->ext1 != 0.0f) {
1863                         nr = 2;
1864
1865                         dl = MEM_callocN(sizeof(DispList), "makebevelcurve p2");
1866                         dl->verts = MEM_malloc_arrayN(nr, sizeof(float[3]), "makebevelcurve p2");
1867                         BLI_addtail(disp, dl);
1868                         dl->type = DL_SEGM;
1869                         dl->parts = 1;
1870                         dl->nr = nr;
1871
1872                         fp = dl->verts;
1873                         fp[1] = cu->ext2;
1874                         fp[2] = -cu->ext1;
1875                         fp[4] = cu->ext2;
1876                         fp[5] = cu->ext1;
1877
1878                         if ((cu->flag & (CU_FRONT | CU_BACK)) == 0) {
1879                                 dl = MEM_dupallocN(dl);
1880                                 dl->verts = MEM_dupallocN(dl->verts);
1881                                 BLI_addtail(disp, dl);
1882
1883                                 fp = dl->verts;
1884                                 fp[1] = -fp[1];
1885                                 fp[2] = -fp[2];
1886                                 fp[4] = -fp[4];
1887                                 fp[5] = -fp[5];
1888                         }
1889                 }
1890
1891                 /* part 3, front */
1892                 if ((cu->flag & CU_FRONT) || !(cu->flag & CU_BACK)) {
1893                         dnr = nr = 2 + cu->bevresol;
1894                         if ((cu->flag & (CU_FRONT | CU_BACK)) == 0) {
1895                                 nr = 3 + 2 * cu->bevresol;
1896                         }
1897                         dl = MEM_callocN(sizeof(DispList), "makebevelcurve p3");
1898                         dl->verts = MEM_malloc_arrayN(nr, sizeof(float[3]), "makebevelcurve p3");
1899                         BLI_addtail(disp, dl);
1900                         dl->type = DL_SEGM;
1901                         dl->flag = DL_FRONT_CURVE;
1902                         dl->parts = 1;
1903                         dl->nr = nr;
1904
1905                         /* half a circle */
1906                         fp = dl->verts;
1907                         angle = 0.0;
1908                         dangle = ((float)M_PI_2 / (dnr - 1));
1909
1910                         for (a = 0; a < nr; a++) {
1911                                 fp[0] = 0.0;
1912                                 fp[1] = (float)(cosf(angle) * (cu->ext2));
1913                                 fp[2] = (float)(sinf(angle) * (cu->ext2)) + cu->ext1;
1914                                 angle += dangle;
1915                                 fp += 3;
1916                         }
1917                 }
1918         }
1919 }
1920
1921 static int cu_isectLL(const float v1[3], const float v2[3], const float v3[3], const float v4[3],
1922                       short cox, short coy,
1923                       float *lambda, float *mu, float vec[3])
1924 {
1925         /* return:
1926          * -1: collinear
1927          *  0: no intersection of segments
1928          *  1: exact intersection of segments
1929          *  2: cross-intersection of segments
1930          */
1931         float deler;
1932
1933         deler = (v1[cox] - v2[cox]) * (v3[coy] - v4[coy]) - (v3[cox] - v4[cox]) * (v1[coy] - v2[coy]);
1934         if (deler == 0.0f)
1935                 return -1;
1936
1937         *lambda = (v1[coy] - v3[coy]) * (v3[cox] - v4[cox]) - (v1[cox] - v3[cox]) * (v3[coy] - v4[coy]);
1938         *lambda = -(*lambda / deler);
1939
1940         deler = v3[coy] - v4[coy];
1941         if (deler == 0) {
1942                 deler = v3[cox] - v4[cox];
1943                 *mu = -(*lambda * (v2[cox] - v1[cox]) + v1[cox] - v3[cox]) / deler;
1944         }
1945         else {
1946                 *mu = -(*lambda * (v2[coy] - v1[coy]) + v1[coy] - v3[coy]) / deler;
1947         }
1948         vec[cox] = *lambda * (v2[cox] - v1[cox]) + v1[cox];
1949         vec[coy] = *lambda * (v2[coy] - v1[coy]) + v1[coy];
1950
1951         if (*lambda >= 0.0f && *lambda <= 1.0f && *mu >= 0.0f && *mu <= 1.0f) {
1952                 if (*lambda == 0.0f || *lambda == 1.0f || *mu == 0.0f || *mu == 1.0f)
1953                         return 1;
1954                 return 2;
1955         }
1956         return 0;
1957 }
1958
1959
1960 static bool bevelinside(BevList *bl1, BevList *bl2)
1961 {
1962         /* is bl2 INSIDE bl1 ? with left-right method and "lambda's" */
1963         /* returns '1' if correct hole  */
1964         BevPoint *bevp, *prevbevp;
1965         float min, max, vec[3], hvec1[3], hvec2[3], lab, mu;
1966         int nr, links = 0, rechts = 0, mode;
1967
1968         /* take first vertex of possible hole */
1969
1970         bevp = bl2->bevpoints;
1971         hvec1[0] = bevp->vec[0];
1972         hvec1[1] = bevp->vec[1];
1973         hvec1[2] = 0.0;
1974         copy_v3_v3(hvec2, hvec1);
1975         hvec2[0] += 1000;
1976
1977         /* test it with all edges of potential surounding poly */
1978         /* count number of transitions left-right  */
1979
1980         bevp = bl1->bevpoints;
1981         nr = bl1->nr;
1982         prevbevp = bevp + (nr - 1);
1983
1984         while (nr--) {
1985                 min = prevbevp->vec[1];
1986                 max = bevp->vec[1];
1987                 if (max < min) {
1988                         min = max;
1989                         max = prevbevp->vec[1];
1990                 }
1991                 if (min != max) {
1992                         if (min <= hvec1[1] && max >= hvec1[1]) {
1993                                 /* there's a transition, calc intersection point */
1994                                 mode = cu_isectLL(prevbevp->vec, bevp->vec, hvec1, hvec2, 0, 1, &lab, &mu, vec);
1995                                 /* if lab==0.0 or lab==1.0 then the edge intersects exactly a transition
1996                                  * only allow for one situation: we choose lab= 1.0
1997                                  */
1998                                 if (mode >= 0 && lab != 0.0f) {
1999                                         if (vec[0] < hvec1[0]) links++;
2000                                         else rechts++;
2001                                 }
2002                         }
2003                 }
2004                 prevbevp = bevp;
2005                 bevp++;
2006         }
2007
2008         return (links & 1) && (rechts & 1);
2009 }
2010
2011
2012 struct BevelSort {
2013         BevList *bl;
2014         float left;
2015         int dir;
2016 };
2017
2018 static int vergxcobev(const void *a1, const void *a2)
2019 {
2020         const struct BevelSort *x1 = a1, *x2 = a2;
2021
2022         if (x1->left > x2->left)
2023                 return 1;
2024         else if (x1->left < x2->left)
2025                 return -1;
2026         return 0;
2027 }
2028
2029 /* this function cannot be replaced with atan2, but why? */
2030
2031 static void calc_bevel_sin_cos(float x1, float y1, float x2, float y2,
2032                                float *r_sina, float *r_cosa)
2033 {
2034         float t01, t02, x3, y3;
2035
2036         t01 = sqrtf(x1 * x1 + y1 * y1);
2037         t02 = sqrtf(x2 * x2 + y2 * y2);
2038         if (t01 == 0.0f)
2039                 t01 = 1.0f;
2040         if (t02 == 0.0f)
2041                 t02 = 1.0f;
2042
2043         x1 /= t01;
2044         y1 /= t01;
2045         x2 /= t02;
2046         y2 /= t02;
2047
2048         t02 = x1 * x2 + y1 * y2;
2049         if (fabsf(t02) >= 1.0f)
2050                 t02 = M_PI_2;
2051         else
2052                 t02 = (saacos(t02)) / 2.0f;
2053
2054         t02 = sinf(t02);
2055         if (t02 == 0.0f)
2056                 t02 = 1.0f;
2057
2058         x3 = x1 - x2;
2059         y3 = y1 - y2;
2060         if (x3 == 0 && y3 == 0) {
2061                 x3 = y1;
2062                 y3 = -x1;
2063         }
2064         else {
2065                 t01 = sqrtf(x3 * x3 + y3 * y3);
2066                 x3 /= t01;
2067                 y3 /= t01;
2068         }
2069
2070         *r_sina = -y3 / t02;
2071         *r_cosa =  x3 / t02;
2072
2073 }
2074
2075 static void alfa_bezpart(BezTriple *prevbezt, BezTriple *bezt, Nurb *nu, float *tilt_array, float *radius_array,
2076                          float *weight_array, int resolu, int stride)
2077 {
2078         BezTriple *pprev, *next, *last;
2079         float fac, dfac, t[4];
2080         int a;
2081
2082         if (tilt_array == NULL && radius_array == NULL)
2083                 return;
2084
2085         last = nu->bezt + (nu->pntsu - 1);
2086
2087         /* returns a point */
2088         if (prevbezt == nu->bezt) {
2089                 if (nu->flagu & CU_NURB_CYCLIC)
2090                         pprev = last;
2091                 else
2092                         pprev = prevbezt;
2093         }
2094         else
2095                 pprev = prevbezt - 1;
2096
2097         /* next point */
2098         if (bezt == last) {
2099                 if (nu->flagu & CU_NURB_CYCLIC)
2100                         next = nu->bezt;
2101                 else
2102                         next = bezt;
2103         }
2104         else
2105                 next = bezt + 1;
2106
2107         fac = 0.0;
2108         dfac = 1.0f / (float)resolu;
2109
2110         for (a = 0; a < resolu; a++, fac += dfac) {
2111                 if (tilt_array) {
2112                         if (nu->tilt_interp == KEY_CU_EASE) { /* May as well support for tilt also 2.47 ease interp */
2113                                 *tilt_array = prevbezt->alfa +
2114                                         (bezt->alfa - prevbezt->alfa) * (3.0f * fac * fac - 2.0f * fac * fac * fac);
2115                         }
2116                         else {
2117                                 key_curve_position_weights(fac, t, nu->tilt_interp);
2118                                 *tilt_array = t[0] * pprev->alfa + t[1] * prevbezt->alfa + t[2] * bezt->alfa + t[3] * next->alfa;
2119                         }
2120
2121                         tilt_array = POINTER_OFFSET(tilt_array, stride);
2122                 }
2123
2124                 if (radius_array) {
2125                         if (nu->radius_interp == KEY_CU_EASE) {
2126                                 /* Support 2.47 ease interp
2127                                  * Note! - this only takes the 2 points into account,
2128                                  * giving much more localized results to changes in radius, sometimes you want that */
2129                                 *radius_array = prevbezt->radius +
2130                                         (bezt->radius - prevbezt->radius) * (3.0f * fac * fac - 2.0f * fac * fac * fac);
2131                         }
2132                         else {
2133
2134                                 /* reuse interpolation from tilt if we can */
2135                                 if (tilt_array == NULL || nu->tilt_interp != nu->radius_interp) {
2136                                         key_curve_position_weights(fac, t, nu->radius_interp);
2137                                 }
2138                                 *radius_array = 
2139                                         t[0] * pprev->radius + t[1] * prevbezt->radius +
2140                                         t[2] * bezt->radius + t[3] * next->radius;
2141                         }
2142
2143                         radius_array = POINTER_OFFSET(radius_array, stride);
2144                 }
2145
2146                 if (weight_array) {
2147                         /* basic interpolation for now, could copy tilt interp too  */
2148                         *weight_array = 
2149                                 prevbezt->weight +
2150                                 (bezt->weight - prevbezt->weight) * (3.0f * fac * fac - 2.0f * fac * fac * fac);
2151
2152                         weight_array = POINTER_OFFSET(weight_array, stride);
2153                 }
2154         }
2155 }
2156
2157 /* make_bevel_list_3D_* funcs, at a minimum these must
2158  * fill in the bezp->quat and bezp->dir values */
2159
2160 /* utility for make_bevel_list_3D_* funcs */
2161 static void bevel_list_calc_bisect(BevList *bl)
2162 {
2163         BevPoint *bevp2, *bevp1, *bevp0;
2164         int nr;
2165         bool is_cyclic = bl->poly != -1;
2166
2167         if (is_cyclic) {
2168                 bevp2 = bl->bevpoints;
2169                 bevp1 = bevp2 + (bl->nr - 1);
2170                 bevp0 = bevp1 - 1;
2171                 nr = bl->nr;
2172         }
2173         else {
2174                 /* If spline is not cyclic, direction of first and
2175                  * last bevel points matches direction of CV handle.
2176                  *
2177                  * This is getting calculated earlier when we know
2178                  * CV's handles and here we might simply skip evaluation
2179                  * of direction for this guys.
2180                  */
2181
2182                 bevp0 = bl->bevpoints;
2183                 bevp1 = bevp0 + 1;
2184                 bevp2 = bevp1 + 1;
2185
2186                 nr = bl->nr - 2;
2187         }
2188
2189         while (nr--) {
2190                 /* totally simple */
2191                 bisect_v3_v3v3v3(bevp1->dir, bevp0->vec, bevp1->vec, bevp2->vec);
2192
2193                 bevp0 = bevp1;
2194                 bevp1 = bevp2;
2195                 bevp2++;
2196         }
2197 }
2198 static void bevel_list_flip_tangents(BevList *bl)
2199 {
2200         BevPoint *bevp2, *bevp1, *bevp0;
2201         int nr;
2202
2203         bevp2 = bl->bevpoints;
2204         bevp1 = bevp2 + (bl->nr - 1);
2205         bevp0 = bevp1 - 1;
2206
2207         nr = bl->nr;
2208         while (nr--) {
2209                 if (angle_normalized_v3v3(bevp0->tan, bevp1->tan) > DEG2RADF(90.0f))
2210                         negate_v3(bevp1->tan);
2211
2212                 bevp0 = bevp1;
2213                 bevp1 = bevp2;
2214                 bevp2++;
2215         }
2216 }
2217 /* apply user tilt */
2218 static void bevel_list_apply_tilt(BevList *bl)
2219 {
2220         BevPoint *bevp2, *bevp1;
2221         int nr;
2222         float q[4];
2223
2224         bevp2 = bl->bevpoints;
2225         bevp1 = bevp2 + (bl->nr - 1);
2226
2227         nr = bl->nr;
2228         while (nr--) {
2229                 axis_angle_to_quat(q, bevp1->dir, bevp1->alfa);
2230                 mul_qt_qtqt(bevp1->quat, q, bevp1->quat);
2231                 normalize_qt(bevp1->quat);
2232
2233                 bevp1 = bevp2;
2234                 bevp2++;
2235         }
2236 }
2237 /* smooth quats, this function should be optimized, it can get slow with many iterations. */
2238 static void bevel_list_smooth(BevList *bl, int smooth_iter)
2239 {
2240         BevPoint *bevp2, *bevp1, *bevp0;
2241         int nr;
2242
2243         float q[4];
2244         float bevp0_quat[4];
2245         int a;
2246
2247         for (a = 0; a < smooth_iter; a++) {
2248                 bevp2 = bl->bevpoints;
2249                 bevp1 = bevp2 + (bl->nr - 1);
2250                 bevp0 = bevp1 - 1;
2251
2252                 nr = bl->nr;
2253
2254                 if (bl->poly == -1) { /* check its not cyclic */
2255                         /* skip the first point */
2256                         /* bevp0 = bevp1; */
2257                         bevp1 = bevp2;
2258                         bevp2++;
2259                         nr--;
2260
2261                         bevp0 = bevp1;
2262                         bevp1 = bevp2;
2263                         bevp2++;
2264                         nr--;
2265                 }
2266
2267                 copy_qt_qt(bevp0_quat, bevp0->quat);
2268
2269                 while (nr--) {
2270                         /* interpolate quats */
2271                         float zaxis[3] = {0, 0, 1}, cross[3], q2[4];
2272                         interp_qt_qtqt(q, bevp0_quat, bevp2->quat, 0.5);
2273                         normalize_qt(q);
2274
2275                         mul_qt_v3(q, zaxis);
2276                         cross_v3_v3v3(cross, zaxis, bevp1->dir);
2277                         axis_angle_to_quat(q2, cross, angle_normalized_v3v3(zaxis, bevp1->dir));
2278                         normalize_qt(q2);
2279
2280                         copy_qt_qt(bevp0_quat, bevp1->quat);
2281                         mul_qt_qtqt(q, q2, q);
2282                         interp_qt_qtqt(bevp1->quat, bevp1->quat, q, 0.5);
2283                         normalize_qt(bevp1->quat);
2284
2285                         /* bevp0 = bevp1; */ /* UNUSED */
2286                         bevp1 = bevp2;
2287                         bevp2++;
2288                 }
2289         }
2290 }
2291
2292 static void make_bevel_list_3D_zup(BevList *bl)
2293 {
2294         BevPoint *bevp = bl->bevpoints;
2295         int nr = bl->nr;
2296
2297         bevel_list_calc_bisect(bl);
2298
2299         while (nr--) {
2300                 vec_to_quat(bevp->quat, bevp->dir, 5, 1);
2301                 bevp++;
2302         }
2303 }
2304
2305 static void minimum_twist_between_two_points(BevPoint *current_point, BevPoint *previous_point)
2306 {
2307         float angle = angle_normalized_v3v3(previous_point->dir, current_point->dir);
2308         float q[4];
2309
2310         if (angle > 0.0f) { /* otherwise we can keep as is */
2311                 float cross_tmp[3];
2312                 cross_v3_v3v3(cross_tmp, previous_point->dir, current_point->dir);
2313                 axis_angle_to_quat(q, cross_tmp, angle);
2314                 mul_qt_qtqt(current_point->quat, q, previous_point->quat);
2315         }
2316         else {
2317                 copy_qt_qt(current_point->quat, previous_point->quat);
2318         }
2319 }
2320
2321 static void make_bevel_list_3D_minimum_twist(BevList *bl)
2322 {
2323         BevPoint *bevp2, *bevp1, *bevp0; /* standard for all make_bevel_list_3D_* funcs */
2324         int nr;
2325         float q[4];
2326
2327         bevel_list_calc_bisect(bl);
2328
2329         bevp2 = bl->bevpoints;
2330         bevp1 = bevp2 + (bl->nr - 1);
2331         bevp0 = bevp1 - 1;
2332
2333         nr = bl->nr;
2334         while (nr--) {
2335
2336                 if (nr + 4 > bl->nr) { /* first time and second time, otherwise first point adjusts last */
2337                         vec_to_quat(bevp1->quat, bevp1->dir, 5, 1);
2338                 }
2339                 else {
2340                         minimum_twist_between_two_points(bevp1, bevp0);
2341                 }
2342
2343                 bevp0 = bevp1;
2344                 bevp1 = bevp2;
2345                 bevp2++;
2346         }
2347
2348         if (bl->poly != -1) { /* check for cyclic */
2349
2350                 /* Need to correct for the start/end points not matching
2351                  * do this by calculating the tilt angle difference, then apply
2352                  * the rotation gradually over the entire curve
2353                  *
2354                  * note that the split is between last and second last, rather than first/last as youd expect.
2355                  *
2356                  * real order is like this
2357                  * 0,1,2,3,4 --> 1,2,3,4,0
2358                  *
2359                  * this is why we compare last with second last
2360                  * */
2361                 float vec_1[3] = {0, 1, 0}, vec_2[3] = {0, 1, 0}, angle, ang_fac, cross_tmp[3];
2362
2363                 BevPoint *bevp_first;
2364                 BevPoint *bevp_last;
2365
2366
2367                 bevp_first = bl->bevpoints;
2368                 bevp_first += bl->nr - 1;
2369                 bevp_last = bevp_first;
2370                 bevp_last--;
2371
2372                 /* quats and vec's are normalized, should not need to re-normalize */
2373                 mul_qt_v3(bevp_first->quat, vec_1);
2374                 mul_qt_v3(bevp_last->quat, vec_2);
2375                 normalize_v3(vec_1);
2376                 normalize_v3(vec_2);
2377
2378                 /* align the vector, can avoid this and it looks 98% OK but
2379                  * better to align the angle quat roll's before comparing */
2380                 {
2381                         cross_v3_v3v3(cross_tmp, bevp_last->dir, bevp_first->dir);
2382                         angle = angle_normalized_v3v3(bevp_first->dir, bevp_last->dir);
2383                         axis_angle_to_quat(q, cross_tmp, angle);
2384                         mul_qt_v3(q, vec_2);
2385                 }
2386
2387                 angle = angle_normalized_v3v3(vec_1, vec_2);
2388
2389                 /* flip rotation if needs be */
2390                 cross_v3_v3v3(cross_tmp, vec_1, vec_2);
2391                 normalize_v3(cross_tmp);
2392                 if (angle_normalized_v3v3(bevp_first->dir, cross_tmp) < DEG2RADF(90.0f))
2393                         angle = -angle;
2394
2395                 bevp2 = bl->bevpoints;
2396                 bevp1 = bevp2 + (bl->nr - 1);
2397                 bevp0 = bevp1 - 1;
2398
2399                 nr = bl->nr;
2400                 while (nr--) {
2401                         ang_fac = angle * (1.0f - ((float)nr / bl->nr)); /* also works */
2402
2403                         axis_angle_to_quat(q, bevp1->dir, ang_fac);
2404                         mul_qt_qtqt(bevp1->quat, q, bevp1->quat);
2405
2406                         bevp0 = bevp1;
2407                         bevp1 = bevp2;
2408                         bevp2++;
2409                 }
2410         }
2411         else {
2412                 /* Need to correct quat for the first/last point,
2413                  * this is so because previously it was only calculated
2414                  * using it's own direction, which might not correspond
2415                  * the twist of neighbor point.
2416                  */
2417                 bevp1 = bl->bevpoints;
2418                 bevp0 = bevp1 + 1;
2419                 minimum_twist_between_two_points(bevp1, bevp0);
2420
2421                 bevp2 = bl->bevpoints;
2422                 bevp1 = bevp2 + (bl->nr - 1);
2423                 bevp0 = bevp1 - 1;
2424                 minimum_twist_between_two_points(bevp1, bevp0);
2425         }
2426 }
2427
2428 static void make_bevel_list_3D_tangent(BevList *bl)
2429 {
2430         BevPoint *bevp2, *bevp1, *bevp0; /* standard for all make_bevel_list_3D_* funcs */
2431         int nr;
2432
2433         float bevp0_tan[3];
2434
2435         bevel_list_calc_bisect(bl);
2436         bevel_list_flip_tangents(bl);
2437
2438         /* correct the tangents */
2439         bevp2 = bl->bevpoints;
2440         bevp1 = bevp2 + (bl->nr - 1);
2441         bevp0 = bevp1 - 1;
2442
2443         nr = bl->nr;
2444         while (nr--) {
2445                 float cross_tmp[3];
2446                 cross_v3_v3v3(cross_tmp, bevp1->tan, bevp1->dir);
2447                 cross_v3_v3v3(bevp1->tan, cross_tmp, bevp1->dir);
2448                 normalize_v3(bevp1->tan);
2449
2450                 bevp0 = bevp1;
2451                 bevp1 = bevp2;
2452                 bevp2++;
2453         }
2454
2455
2456         /* now for the real twist calc */
2457         bevp2 = bl->bevpoints;
2458         bevp1 = bevp2 + (bl->nr - 1);
2459         bevp0 = bevp1 - 1;
2460
2461         copy_v3_v3(bevp0_tan, bevp0->tan);
2462
2463         nr = bl->nr;
2464         while (nr--) {
2465                 /* make perpendicular, modify tan in place, is ok */
2466                 float cross_tmp[3];
2467                 float zero[3] = {0, 0, 0};
2468
2469                 cross_v3_v3v3(cross_tmp, bevp1->tan, bevp1->dir);
2470                 normalize_v3(cross_tmp);
2471                 tri_to_quat(bevp1->quat, zero, cross_tmp, bevp1->tan); /* XXX - could be faster */
2472
2473                 /* bevp0 = bevp1; */ /* UNUSED */
2474                 bevp1 = bevp2;
2475                 bevp2++;
2476         }
2477 }
2478
2479 static void make_bevel_list_3D(BevList *bl, int smooth_iter, int twist_mode)
2480 {
2481         switch (twist_mode) {
2482                 case CU_TWIST_TANGENT:
2483                         make_bevel_list_3D_tangent(bl);
2484                         break;
2485                 case CU_TWIST_MINIMUM:
2486                         make_bevel_list_3D_minimum_twist(bl);
2487                         break;
2488                 default: /* CU_TWIST_Z_UP default, pre 2.49c */
2489                         make_bevel_list_3D_zup(bl);
2490                         break;
2491         }
2492
2493         if (smooth_iter)
2494                 bevel_list_smooth(bl, smooth_iter);
2495
2496         bevel_list_apply_tilt(bl);
2497 }
2498
2499 /* only for 2 points */
2500 static void make_bevel_list_segment_3D(BevList *bl)
2501 {
2502         float q[4];
2503
2504         BevPoint *bevp2 = bl->bevpoints;
2505         BevPoint *bevp1 = bevp2 + 1;
2506
2507         /* simple quat/dir */
2508         sub_v3_v3v3(bevp1->dir, bevp1->vec, bevp2->vec);
2509         normalize_v3(bevp1->dir);
2510
2511         vec_to_quat(bevp1->quat, bevp1->dir, 5, 1);
2512
2513         axis_angle_to_quat(q, bevp1->dir, bevp1->alfa);
2514         mul_qt_qtqt(bevp1->quat, q, bevp1->quat);
2515         normalize_qt(bevp1->quat);
2516         copy_v3_v3(bevp2->dir, bevp1->dir);
2517         copy_qt_qt(bevp2->quat, bevp1->quat);
2518 }
2519
2520 /* only for 2 points */
2521 static void make_bevel_list_segment_2D(BevList *bl)
2522 {
2523         BevPoint *bevp2 = bl->bevpoints;
2524         BevPoint *bevp1 = bevp2 + 1;
2525
2526         const float x1 = bevp1->vec[0] - bevp2->vec[0];
2527         const float y1 = bevp1->vec[1] - bevp2->vec[1];
2528
2529         calc_bevel_sin_cos(x1, y1, -x1, -y1, &(bevp1->sina), &(bevp1->cosa));
2530         bevp2->sina = bevp1->sina;
2531         bevp2->cosa = bevp1->cosa;
2532
2533         /* fill in dir & quat */
2534         make_bevel_list_segment_3D(bl);
2535 }
2536
2537 static void make_bevel_list_2D(BevList *bl)
2538 {
2539         /* note: bevp->dir and bevp->quat are not needed for beveling but are
2540          * used when making a path from a 2D curve, therefor they need to be set - Campbell */
2541
2542         BevPoint *bevp0, *bevp1, *bevp2;
2543         int nr;
2544
2545         if (bl->poly != -1) {
2546                 bevp2 = bl->bevpoints;
2547                 bevp1 = bevp2 + (bl->nr - 1);
2548                 bevp0 = bevp1 - 1;
2549                 nr = bl->nr;
2550         }
2551         else {
2552                 bevp0 = bl->bevpoints;
2553                 bevp1 = bevp0 + 1;
2554                 bevp2 = bevp1 + 1;
2555
2556                 nr = bl->nr - 2;
2557         }
2558
2559         while (nr--) {
2560                 const float x1 = bevp1->vec[0] - bevp0->vec[0];
2561                 const float x2 = bevp1->vec[0] - bevp2->vec[0];
2562                 const float y1 = bevp1->vec[1] - bevp0->vec[1];
2563                 const float y2 = bevp1->vec[1] - bevp2->vec[1];
2564
2565                 calc_bevel_sin_cos(x1, y1, x2, y2, &(bevp1->sina), &(bevp1->cosa));
2566
2567                 /* from: make_bevel_list_3D_zup, could call but avoid a second loop.
2568                  * no need for tricky tilt calculation as with 3D curves */
2569                 bisect_v3_v3v3v3(bevp1->dir, bevp0->vec, bevp1->vec, bevp2->vec);
2570                 vec_to_quat(bevp1->quat, bevp1->dir, 5, 1);
2571                 /* done with inline make_bevel_list_3D_zup */
2572
2573                 bevp0 = bevp1;
2574                 bevp1 = bevp2;
2575                 bevp2++;
2576         }
2577
2578         /* correct non-cyclic cases */
2579         if (bl->poly == -1) {
2580                 BevPoint *bevp;
2581                 float angle;
2582
2583                 /* first */
2584                 bevp = bl->bevpoints;
2585                 angle = atan2f(bevp->dir[0], bevp->dir[1]) - (float)M_PI_2;
2586                 bevp->sina = sinf(angle);
2587                 bevp->cosa = cosf(angle);
2588                 vec_to_quat(bevp->quat, bevp->dir, 5, 1);
2589
2590                 /* last */
2591                 bevp = bl->bevpoints;
2592                 bevp += (bl->nr - 1);
2593                 angle = atan2f(bevp->dir[0], bevp->dir[1]) - (float)M_PI_2;
2594                 bevp->sina = sinf(angle);
2595                 bevp->cosa = cosf(angle);
2596                 vec_to_quat(bevp->quat, bevp->dir, 5, 1);
2597         }
2598 }
2599
2600 static void bevlist_firstlast_direction_calc_from_bpoint(Nurb *nu, BevList *bl)
2601 {
2602         if (nu->pntsu > 1) {
2603                 BPoint *first_bp = nu->bp, *last_bp = nu->bp + (nu->pntsu - 1);
2604                 BevPoint *first_bevp, *last_bevp;
2605
2606                 first_bevp = bl->bevpoints;
2607                 last_bevp = first_bevp + (bl->nr - 1);
2608
2609                 sub_v3_v3v3(first_bevp->dir, (first_bp + 1)->vec, first_bp->vec);
2610                 normalize_v3(first_bevp->dir);
2611
2612                 sub_v3_v3v3(last_bevp->dir, last_bp->vec, (last_bp - 1)->vec);
2613                 normalize_v3(last_bevp->dir);
2614         }
2615 }
2616
2617 void BKE_curve_bevelList_free(ListBase *bev)
2618 {
2619         BevList *bl, *blnext;
2620         for (bl = bev->first; bl != NULL; bl = blnext) {
2621                 blnext = bl->next;
2622                 if (bl->seglen != NULL) {
2623                         MEM_freeN(bl->seglen);
2624                 }
2625                 if (bl->segbevcount != NULL) {
2626                         MEM_freeN(bl->segbevcount);
2627                 }
2628                 if (bl->bevpoints != NULL) {
2629                         MEM_freeN(bl->bevpoints);
2630                 }
2631                 MEM_freeN(bl);
2632         }
2633
2634         BLI_listbase_clear(bev);
2635 }
2636
2637 void BKE_curve_bevelList_make(Object *ob, ListBase *nurbs, bool for_render)
2638 {
2639         /*
2640          * - convert all curves to polys, with indication of resol and flags for double-vertices
2641          * - possibly; do a smart vertice removal (in case Nurb)
2642          * - separate in individual blocks with BoundBox
2643          * - AutoHole detection
2644          */
2645
2646         /* this function needs an object, because of tflag and upflag */
2647         Curve *cu = ob->data;
2648         Nurb *nu;
2649         BezTriple *bezt, *prevbezt;
2650         BPoint *bp;
2651         BevList *bl, *blnew, *blnext;
2652         BevPoint *bevp2, *bevp1 = NULL, *bevp0;
2653         const float treshold = 0.00001f;
2654         float min, inp;
2655         float *seglen = NULL;
2656         struct BevelSort *sortdata, *sd, *sd1;
2657         int a, b, nr, poly, resolu = 0, len = 0, segcount;
2658         int *segbevcount;
2659         bool do_tilt, do_radius, do_weight;
2660         bool is_editmode = false;
2661         ListBase *bev;
2662
2663         /* segbevcount alsp requires seglen. */
2664         const bool need_seglen =
2665                 ELEM(cu->bevfac1_mapping, CU_BEVFAC_MAP_SEGMENT, CU_BEVFAC_MAP_SPLINE) ||
2666                 ELEM(cu->bevfac2_mapping, CU_BEVFAC_MAP_SEGMENT, CU_BEVFAC_MAP_SPLINE);
2667
2668
2669         bev = &ob->curve_cache->bev;
2670
2671         /* do we need to calculate the radius for each point? */
2672         /* do_radius = (cu->bevobj || cu->taperobj || (cu->flag & CU_FRONT) || (cu->flag & CU_BACK)) ? 0 : 1; */
2673
2674         /* STEP 1: MAKE POLYS  */
2675
2676         BKE_curve_bevelList_free(&ob->curve_cache->bev);
2677         nu = nurbs->first;
2678         if (cu->editnurb && ob->type != OB_FONT) {
2679                 is_editmode = 1;
2680         }
2681
2682         for (; nu; nu = nu->next) {
2683                 
2684                 if (nu->hide && is_editmode)
2685                         continue;
2686                 
2687                 /* check if we will calculate tilt data */
2688                 do_tilt = CU_DO_TILT(cu, nu);
2689                 do_radius = CU_DO_RADIUS(cu, nu); /* normal display uses the radius, better just to calculate them */
2690                 do_weight = true;
2691
2692                 /* check we are a single point? also check we are not a surface and that the orderu is sane,
2693                  * enforced in the UI but can go wrong possibly */
2694                 if (!BKE_nurb_check_valid_u(nu)) {
2695                         bl = MEM_callocN(sizeof(BevList), "makeBevelList1");
2696                         bl->bevpoints = MEM_calloc_arrayN(1, sizeof(BevPoint), "makeBevelPoints1");
2697                         BLI_addtail(bev, bl);
2698                         bl->nr = 0;
2699                         bl->charidx = nu->charidx;
2700                 }
2701                 else {
2702                         BevPoint *bevp;
2703
2704                         if (for_render && cu->resolu_ren != 0)
2705                                 resolu = cu->resolu_ren;
2706                         else
2707                                 resolu = nu->resolu;
2708
2709                         segcount = SEGMENTSU(nu);
2710
2711                         if (nu->type == CU_POLY) {
2712                                 len = nu->pntsu;
2713                                 bl = MEM_callocN(sizeof(BevList), "makeBevelList2");
2714                                 bl->bevpoints = MEM_calloc_arrayN(len, sizeof(BevPoint), "makeBevelPoints2");
2715                                 if (need_seglen && (nu->flagu & CU_NURB_CYCLIC) == 0) {
2716                                         bl->seglen = MEM_malloc_arrayN(segcount, sizeof(float), "makeBevelList2_seglen");
2717                                         bl->segbevcount = MEM_malloc_arrayN(segcount, sizeof(int), "makeBevelList2_segbevcount");
2718                                 }
2719                                 BLI_addtail(bev, bl);
2720
2721                                 bl->poly = (nu->flagu & CU_NURB_CYCLIC) ? 0 : -1;
2722                                 bl->nr = len;
2723                                 bl->dupe_nr = 0;
2724                                 bl->charidx = nu->charidx;
2725                                 bevp = bl->bevpoints;
2726                                 bevp->offset = 0;
2727                                 bp = nu->bp;
2728                                 seglen = bl->seglen;
2729                                 segbevcount = bl->segbevcount;
2730
2731                                 while (len--) {
2732                                         copy_v3_v3(bevp->vec, bp->vec);
2733                                         bevp->alfa = bp->alfa;
2734                                         bevp->radius = bp->radius;
2735                                         bevp->weight = bp->weight;
2736                                         bevp->split_tag = true;
2737                                         bp++;
2738                                         if (seglen != NULL && len != 0) {
2739                                                 *seglen = len_v3v3(bevp->vec, bp->vec);
2740                                                 bevp++;
2741                                                 bevp->offset = *seglen;
2742                                                 if (*seglen > treshold) *segbevcount = 1;
2743                                                 else *segbevcount = 0;
2744                                                 seglen++;
2745                                                 segbevcount++;
2746                                         }
2747                                         else {
2748                                                 bevp++;
2749                                         }
2750                                 }
2751
2752                                 if ((nu->flagu & CU_NURB_CYCLIC) == 0) {
2753                                         bevlist_firstlast_direction_calc_from_bpoint(nu, bl);
2754                                 }
2755                         }
2756                         else if (nu->type == CU_BEZIER) {
2757                                 /* in case last point is not cyclic */
2758                                 len = segcount * resolu + 1;
2759
2760                                 bl = MEM_callocN(sizeof(BevList), "makeBevelBPoints");
2761                                 bl->bevpoints = MEM_calloc_arrayN(len, sizeof(BevPoint), "makeBevelBPointsPoints");
2762                                 if (need_seglen && (nu->flagu & CU_NURB_CYCLIC) == 0) {
2763                                         bl->seglen = MEM_malloc_arrayN(segcount, sizeof(float), "makeBevelBPoints_seglen");
2764                                         bl->segbevcount = MEM_malloc_arrayN(segcount, sizeof(int), "makeBevelBPoints_segbevcount");
2765                                 }
2766                                 BLI_addtail(bev, bl);
2767
2768                                 bl->poly = (nu->flagu & CU_NURB_CYCLIC) ? 0 : -1;
2769                                 bl->charidx = nu->charidx;
2770
2771                                 bevp = bl->bevpoints;
2772                                 seglen = bl->seglen;
2773                                 segbevcount = bl->segbevcount;
2774
2775                                 bevp->offset = 0;
2776                                 if (seglen != NULL) {
2777                                         *seglen = 0;
2778                                         *segbevcount = 0;
2779                                 }
2780
2781                                 a = nu->pntsu - 1;
2782                                 bezt = nu->bezt;
2783                                 if (nu->flagu & CU_NURB_CYCLIC) {
2784                                         a++;
2785                                         prevbezt = nu->bezt + (nu->pntsu - 1);
2786                                 }
2787                                 else {
2788                                         prevbezt = bezt;
2789                                         bezt++;
2790                                 }
2791
2792                                 sub_v3_v3v3(bevp->dir, prevbezt->vec[2], prevbezt->vec[1]);
2793                                 normalize_v3(bevp->dir);
2794
2795                                 BLI_assert(segcount >= a);
2796
2797                                 while (a--) {
2798                                         if (prevbezt->h2 == HD_VECT && bezt->h1 == HD_VECT) {
2799
2800                                                 copy_v3_v3(bevp->vec, prevbezt->vec[1]);
2801                                                 bevp->alfa = prevbezt->alfa;
2802                                                 bevp->radius = prevbezt->radius;
2803                                                 bevp->weight = prevbezt->weight;
2804                                                 bevp->split_tag = true;
2805                                                 bevp->dupe_tag = false;
2806                                                 bevp++;
2807                                                 bl->nr++;
2808                                                 bl->dupe_nr = 1;
2809                                                 if (seglen != NULL) {
2810                                                         *seglen = len_v3v3(prevbezt->vec[1], bezt->vec[1]);
2811                                                         bevp->offset = *seglen;
2812                                                         seglen++;
2813                                                         /* match segbevcount to the cleaned up bevel lists (see STEP 2) */
2814                                                         if (bevp->offset > treshold) *segbevcount = 1;
2815                                                         segbevcount++;
2816                                                 }
2817                                         }
2818                                         else {
2819                                                 /* always do all three, to prevent data hanging around */
2820                                                 int j;
2821
2822                                                 /* BevPoint must stay aligned to 4 so sizeof(BevPoint)/sizeof(float) works */
2823                                                 for (j = 0; j < 3; j++) {
2824                                                         BKE_curve_forward_diff_bezier(prevbezt->vec[1][j],  prevbezt->vec[2][j],
2825                                                                                       bezt->vec[0][j],      bezt->vec[1][j],
2826                                                                                       &(bevp->vec[j]), resolu, sizeof(BevPoint));
2827                                                 }
2828
2829                                                 /* if both arrays are NULL do nothiong */
2830                                                 alfa_bezpart(prevbezt, bezt, nu,
2831                                                              do_tilt    ? &bevp->alfa : NULL,
2832                                                              do_radius  ? &bevp->radius : NULL,
2833                                                              do_weight  ? &bevp->weight : NULL,
2834                                                              resolu, sizeof(BevPoint));
2835
2836
2837                                                 if (cu->twist_mode == CU_TWIST_TANGENT) {
2838                                                         forward_diff_bezier_cotangent(prevbezt->vec[1], prevbezt->vec[2],
2839                                                                                       bezt->vec[0],     bezt->vec[1],
2840                                                                                       bevp->tan, resolu, sizeof(BevPoint));
2841                                                 }
2842
2843                                                 /* indicate with handlecodes double points */
2844                                                 if (prevbezt->h1 == prevbezt->h2) {
2845                                                         if (prevbezt->h1 == 0 || prevbezt->h1 == HD_VECT)
2846                                                                 bevp->split_tag = true;
2847                                                 }
2848                                                 else {
2849                                                         if (prevbezt->h1 == 0 || prevbezt->h1 == HD_VECT)
2850                                                                 bevp->split_tag = true;
2851                                                         else if (prevbezt->h2 == 0 || prevbezt->h2 == HD_VECT)
2852                                                                 bevp->split_tag = true;
2853                                                 }
2854
2855                                                 /* seglen */
2856                                                 if (seglen != NULL) {
2857                                                         *seglen = 0;
2858                                                         *segbevcount = 0;
2859                                                         for (j = 0; j < resolu; j++) {
2860                                                                 bevp0 = bevp;
2861                                                                 bevp++;
2862                                                                 bevp->offset = len_v3v3(bevp0->vec, bevp->vec);
2863                                                                 /* match seglen and segbevcount to the cleaned up bevel lists (see STEP 2) */
2864                                                                 if (bevp->offset > treshold) {
2865                                                                         *seglen += bevp->offset;
2866                                                                         *segbevcount += 1;
2867                                                                 }
2868                                                         }
2869                                                         seglen++;
2870                                                         segbevcount++;
2871                                                 }
2872                                                 else {
2873                                                         bevp += resolu;
2874                                                 }
2875                                                 bl->nr += resolu;
2876                                         }
2877                                         prevbezt = bezt;
2878                                         bezt++;
2879                                 }
2880
2881                                 if ((nu->flagu & CU_NURB_CYCLIC) == 0) {      /* not cyclic: endpoint */
2882                                         copy_v3_v3(bevp->vec, prevbezt->vec[1]);
2883                                         bevp->alfa = prevbezt->alfa;
2884                                         bevp->radius = prevbezt->radius;
2885                                         bevp->weight = prevbezt->weight;
2886
2887                                         sub_v3_v3v3(bevp->dir, prevbezt->vec[1], prevbezt->vec[0]);
2888                                         normalize_v3(bevp->dir);
2889
2890                                         bl->nr++;
2891                                 }
2892                         }
2893                         else if (nu->type == CU_NURBS) {
2894                                 if (nu->pntsv == 1) {
2895                                         len = (resolu * segcount);
2896
2897                                         bl = MEM_callocN(sizeof(BevList), "makeBevelList3");
2898                                         bl->bevpoints = MEM_calloc_arrayN(len, sizeof(BevPoint), "makeBevelPoints3");
2899                                         if (need_seglen && (nu->flagu & CU_NURB_CYCLIC) == 0) {
2900                                                 bl->seglen = MEM_malloc_arrayN(segcount, sizeof(float), "makeBevelList3_seglen");
2901                                                 bl->segbevcount = MEM_malloc_arrayN(segcount, sizeof(int), "makeBevelList3_segbevcount");
2902                                         }
2903                                         BLI_addtail(bev, bl);
2904                                         bl->nr = len;
2905                                         bl->dupe_nr = 0;
2906                                         bl->poly = (nu->flagu & CU_NURB_CYCLIC) ? 0 : -1;
2907                                         bl->charidx = nu->charidx;
2908
2909                                         bevp = bl->bevpoints;
2910                                         seglen = bl->seglen;
2911                                         segbevcount = bl->segbevcount;
2912
2913                                         BKE_nurb_makeCurve(nu, &bevp->vec[0],
2914                                                            do_tilt      ? &bevp->alfa : NULL,
2915                                                            do_radius    ? &bevp->radius : NULL,
2916                                                            do_weight    ? &bevp->weight : NULL,
2917                                                            resolu, sizeof(BevPoint));
2918
2919                                         /* match seglen and segbevcount to the cleaned up bevel lists (see STEP 2) */
2920                                         if (seglen != NULL) {
2921                                                 nr = segcount;
2922                                                 bevp0 = bevp;
2923                                                 bevp++;
2924                                                 while (nr) {
2925                                                         int j;
2926                                                         *seglen = 0;
2927                                                         *segbevcount = 0;
2928                                                         /* We keep last bevel segment zero-length. */
2929                                                         for (j = 0; j < ((nr == 1) ? (resolu - 1) : resolu); j++) {
2930                                                                 bevp->offset = len_v3v3(bevp0->vec, bevp->vec);
2931                                                                 if (bevp->offset > treshold) {
2932                                                                         *seglen += bevp->offset;
2933                                                                         *segbevcount += 1;
2934                                                                 }
2935                                                                 bevp0 = bevp;
2936                                                                 bevp++;
2937                                                         }
2938                                                         seglen++;
2939                                                         segbevcount++;
2940                                                         nr--;
2941                                                 }
2942                                         }
2943
2944                                         if ((nu->flagu & CU_NURB_CYCLIC) == 0) {
2945                                                 bevlist_firstlast_direction_calc_from_bpoint(nu, bl);
2946                                         }
2947                                 }
2948                         }
2949                 }
2950         }
2951
2952         /* STEP 2: DOUBLE POINTS AND AUTOMATIC RESOLUTION, REDUCE DATABLOCKS */
2953         bl = bev->first;
2954         while (bl) {
2955                 if (bl->nr) { /* null bevel items come from single points */
2956                         bool is_cyclic = bl->poly != -1;
2957                         nr = bl->nr;
2958                         if (is_cyclic) {
2959                                 bevp1 = bl->bevpoints;
2960                                 bevp0 = bevp1 + (nr - 1);
2961                         }
2962                         else {
2963                                 bevp0 = bl->bevpoints;
2964                                 bevp0->offset = 0;
2965                                 bevp1 = bevp0 + 1;
2966                         }
2967                         nr--;
2968                         while (nr--) {
2969                                 if (seglen != NULL) {
2970                                         if (fabsf(bevp1->offset) < treshold) {
2971                                                 bevp0->dupe_tag = true;
2972                                                 bl->dupe_nr++;
2973                                         }
2974                                 }
2975                                 else {
2976                                         if (fabsf(bevp0->vec[0] - bevp1->vec[0]) < 0.00001f) {
2977                                                 if (fabsf(bevp0->vec[1] - bevp1->vec[1]) < 0.00001f) {
2978                                                         if (fabsf(bevp0->vec[2] - bevp1->vec[2]) < 0.00001f) {
2979                                                                 bevp0->dupe_tag = true;
2980                                                                 bl->dupe_nr++;
2981                                                         }
2982                                                 }
2983                                         }
2984                                 }
2985                                 bevp0 = bevp1;
2986                                 bevp1++;
2987                         }
2988                 }
2989                 bl = bl->next;
2990         }
2991         bl = bev->first;
2992         while (bl) {
2993                 blnext = bl->next;
2994                 if (bl->nr && bl->dupe_nr) {
2995                         nr = bl->nr - bl->dupe_nr + 1;  /* +1 because vectorbezier sets flag too */
2996                         blnew = MEM_callocN(sizeof(BevList), "makeBevelList4");
2997                         memcpy(blnew, bl, sizeof(BevList));
2998                         blnew->bevpoints = MEM_calloc_arrayN(nr, sizeof(BevPoint), "makeBevelPoints4");
2999                         if (!blnew->bevpoints) {
3000                                 MEM_freeN(blnew);
3001                                 break;
3002                         }
3003                         blnew->segbevcount = bl->segbevcount;
3004                         blnew->seglen = bl->seglen;
3005                         blnew->nr = 0;
3006                         BLI_remlink(bev, bl);
3007                         BLI_insertlinkbefore(bev, blnext, blnew);    /* to make sure bevlijst is tuned with nurblist */
3008                         bevp0 = bl->bevpoints;
3009                         bevp1 = blnew->bevpoints;
3010                         nr = bl->nr;
3011                         while (nr--) {
3012                                 if (bevp0->dupe_tag == 0) {
3013                                         memcpy(bevp1, bevp0, sizeof(BevPoint));
3014                                         bevp1++;
3015                                         blnew->nr++;
3016                                 }
3017                                 bevp0++;
3018                         }
3019                         if (bl->bevpoints != NULL) {
3020                                 MEM_freeN(bl->bevpoints);
3021                         }
3022                         MEM_freeN(bl);
3023                         blnew->dupe_nr = 0;
3024                 }
3025                 bl = blnext;
3026         }
3027
3028         /* STEP 3: POLYS COUNT AND AUTOHOLE */
3029         bl = bev->first;
3030         poly = 0;
3031         while (bl) {
3032                 if (bl->nr && bl->poly >= 0) {
3033                         poly++;
3034                         bl->poly = poly;
3035                         bl->hole = 0;
3036                 }
3037                 bl = bl->next;
3038         }
3039
3040         /* find extreme left points, also test (turning) direction */
3041         if (poly > 0) {
3042                 sd = sortdata = MEM_malloc_arrayN(poly, sizeof(struct BevelSort), "makeBevelList5");
3043                 bl = bev->first;
3044                 while (bl) {
3045                         if (bl->poly > 0) {
3046                                 BevPoint *bevp;
3047
3048                                 min = 300000.0;
3049                                 bevp = bl->bevpoints;
3050                                 nr = bl->nr;
3051                                 while (nr--) {
3052                                         if (min > bevp->vec[0]) {
3053                                                 min = bevp->vec[0];
3054                                                 bevp1 = bevp;
3055                                         }
3056                                         bevp++;
3057                                 }
3058                                 sd->bl = bl;
3059                                 sd->left = min;
3060
3061                                 bevp = bl->bevpoints;
3062                                 if (bevp1 == bevp)
3063                                         bevp0 = bevp + (bl->nr - 1);
3064                                 else
3065                                         bevp0 = bevp1 - 1;
3066                                 bevp = bevp + (bl->nr - 1);