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